Compare commits

..
46 Commits
Author SHA1 Message Date
DrSmoothl f2ea3354f8 chore(release): v2.4.2 2026-11-07 19:49:06 +08:00
DrSmoothl efcbf988b2 fix(runtime): improve ARM64 compatibility 2026-11-07 19:38:35 +08:00
DrSmoothl a341fa4b15 docs(readme): add Docker pulls badge 2026-11-07 17:22:46 +08:00
DrSmoothl 8bea681aa2 fix(core): handle group file storage limits
Retry eligible storage failures as temporary files and preserve their storage type for later use. Reject incompatible mixed content before chat publication.

Refs #644
2026-11-07 15:14:55 +08:00
DrSmoothl 84f4cde85e chore(release): v2.4.1 2026-11-07 14:20:00 +08:00
DrSmoothl 6c8866b108 fix(protocol): improve upload recovery and time limits
Apply configurable idle and total transfer deadlines, cover supplied upload candidates, and retain recent endpoint outcomes per account and upload type. Preserve failed action responses and resource cleanup.

Refs #637
2026-11-07 14:10:56 +08:00
DrSmoothl f2ade5603f fix(onebot): preserve images in message history
Refs #659
2026-11-07 13:31:14 +08:00
DrSmoothl 87f7bd8c54 fix(websocket): settle failed sends and enforce SDK request deadlines
Settle queued sends once when a connection fails or closes before opening,
and reject further sends while preserving the original failure.

Include connection waits in SDK request deadlines without closing shared
connections or sending expired actions after a late connection.

Refs #665
Refs #666
2026-11-07 12:57:25 +08:00
DrSmoothl 9edc255a02 fix(onebot): distinguish group invitation identities
Expose joining members, inviters and request operators separately.
Preserve existing notice fields and report unavailable invitation identities explicitly.

Refs #643
2026-11-06 23:37:00 +08:00
DrSmoothl 7425cfae20 fix(bridge): restore Windows account readiness
Keep account confirmation active until a valid login is ready and clear stale bindings when readiness is lost.

Update Windows components and cover login recovery.

Refs #638
2026-11-06 22:49:52 +08:00
DrSmoothl 1b80487119 test(common): pin logger benchmark file level
Refs #651
2026-11-06 22:49:52 +08:00
DrSmoothl 43b63e9a75 fix(onebot): restore group join request delivery
Refs #658
2026-11-06 22:49:52 +08:00
DrSmoothl b0612d8d12 fix(onebot): identify QQ automatic replies in private messages
Refs #663
2026-11-06 22:49:52 +08:00
晚晴 e031cd4108 perf(common): reduce log snapshot and file-only allocation overhead (#656)
Refs #651
2026-11-06 21:51:46 +08:00
DrSmoothl b6b433af98 fix(common): release retained cache and log memory
Dispose contact caches with account sessions and prevent late loads from restoring timers. Release discarded log content while preserving visible text.

Refs #651
2026-11-04 23:23:44 +08:00
DrSmoothl ae1ec3be0e fix(protocol): decode styled group member cards
Use the display text for group messages and member lookups. Refresh unreadable cached cards on demand.

Refs #646
2026-11-04 23:23:44 +08:00
晚晴 33bebb4446 perf(common): reduce retained memory in logs and TTL caches (#652) 2026-11-04 22:29:39 +08:00
Hao_Ming bab5aafd91 docs(readme): move mascot into heading to fix border overlap (#641) 2026-11-03 13:19:35 +08:00
DrSmoothl e44e4ced17 chore(release): v2.4.0 2026-11-03 11:07:44 +08:00
DrSmoothl f452c657ed fix(webui): tint default surfaces with the active accent 2026-11-03 11:03:29 +08:00
DrSmoothl 1cd838e7a1 feat(webui): adopt lavender mascot branding 2026-11-03 10:41:11 +08:00
DrSmoothl a8f460499b fix(deps): update vulnerable transitive dependencies 2026-11-03 09:41:20 +08:00
DrSmoothl a977228a09 docs(readme): introduce the SnowLuma mascot 2026-11-03 09:39:21 +08:00
DrSmoothl e9faec0e28 chore(release): v2.3.4 2026-11-02 09:09:06 +08:00
DrSmoothl 4a10f38743 fix(onebot): resolve private reply targets consistently
Refs #618
2026-11-02 08:47:26 +08:00
DrSmoothl a1688a33b0 fix(bridge): detect initial connection timeouts
Keep connection timeouts recoverable through retry or unload.

Refs #578
2026-11-02 08:25:15 +08:00
DrSmoothl 45c3a6841a feat(onebot): expose public contact profiles
Refs #615
2026-11-02 08:06:27 +08:00
DrSmoothl 2b63f375fc fix(onebot): handle non-friend group invitations
Refs #636
2026-11-02 07:55:40 +08:00
DrSmoothl 0fa912a32e feat(sdk): accept reverse WebSocket connections
Refs #617
2026-11-01 23:26:50 +08:00
DrSmoothl 5f1700fc1b feat(onebot): add HTTP event streaming
Refs #593
2026-11-01 23:15:51 +08:00
DrSmoothl 54038c775a fix(runtime): report private messages sent from the client
Refs #603
2026-11-01 23:01:38 +08:00
DrSmoothl c15ecd0402 feat(qzone): add complete feed lookup by tid
Refs #633
2026-11-01 21:31:52 +08:00
DrSmoothl f79187f36a ci: enforce dev targets and issue references for pull requests
Explain policy violations before closing pull requests, validate linked issues, and cover the guard with isolated tests. Align contributor guidance and keep feature details out of the root README.
2026-11-01 21:09:48 +08:00
DrSmoothl 24ec8a7eba docs(readme): remove the media size limitations section 2026-11-01 20:47:25 +08:00
DrSmoothl 3773106425 fix(onebot): validate payload limits and correct frame diagnostics
Reject invalid payload limits consistently in configuration files, restores, and API writes. Preserve pending frame bytes when reporting oversized messages.

Refs #627
2026-11-01 20:42:20 +08:00
DrSmoothl f65880b164 fix(protocol): handle null Qzone share errors
Refs #625
2026-11-01 20:42:20 +08:00
KazusaUwU 8d9f44b6b0 feat(onebot): make the websocket frame cap configurable and diagnosable (#631)
- expose DEFAULT_MAX_PAYLOAD_BYTES; an inbound frame over the cap now reports its
  declared byte size, message type and the effective limit, recovered by walking
  the buffered frame stream so the number is right when a chunk carries several
  frames, the oversized header spans chunks, or control frames are interleaved;
  when the walk cannot reach a verdict the error names the cap without a size
- truncate close reasons to the RFC 6455 control-frame room on a UTF-8 boundary
  (an over-long reason previously produced an invalid control frame)
- add optional maxPayloadBytes (default 100 MiB unchanged) to the three adapters
  that read WebSocket frames: wsServers, wsClients and httpServers with
  enableWebSocket. httpClients rejects the field because it has no WebSocket
  transport, and the value is part of the binding signature so a change rebinds
  the transport instead of being saved without taking effect
- keep the existing 1009 log lines and append the actionable hint instead of
  replacing the template
- WebUI field (including httpServers once the embedded listener is on) and README
  docs for the 100 MiB => ~445 s (7:26) inline PCM consequence
2026-11-01 20:29:16 +08:00
KazusaUwU bd40ac3522 feat(protocol): make highway media download limits configurable (#632)
Bound the two hardcoded limits of the shared HTTP media download engine
(`loadBinarySource` / `stageSourceToDisk`) with deployment-wide environment
settings, following the existing `positiveIntEnv` convention:

- SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS (default 60000): one download attempt.
- SNOWLUMA_MAX_BINARY_DOWNLOAD_BYTES (default 1073741824): the implicit cap on
  a binary source buffered in memory.

Both defaults are unchanged, so an unconfigured deployment behaves exactly as
before, and unusable values are logged and ignored. Callers that pass their own
ceiling keep it: group/private files and flash transfer still use 4 GiB, inline
`base64://` / `data:` flash sources keep the 1 GiB buffered-load ceiling, and
video upload has its own limit. Documented in HIGHWAY_UPLOADS.md.
2026-11-01 20:29:01 +08:00
DrSmoothl 60733aacab chore(release): v2.3.3 2026-11-01 14:05:51 +08:00
DrSmoothl a2ce3b2c19 fix(runtime): improve Linux startup compatibility 2026-11-01 13:58:15 +08:00
DrSmoothl 7882081bdb chore(release): v2.3.2 2026-11-01 01:04:27 +08:00
DrSmoothl f1ef07544d fix(runtime): improve Linux client startup and message reception
Refs #623
2026-11-01 01:02:44 +08:00
DrSmoothl c120b0fb97 chore(release): v2.3.1 2026-10-31 23:41:23 +08:00
DrSmoothl 93290e4d0c fix(protocol): allow clearing group member cards
Refs #620
2026-10-31 23:25:45 +08:00
DrSmoothl fa4870bdca fix(runtime): improve Windows message reception 2026-10-31 23:03:23 +08:00
DrSmoothl b126b5c166 fix(runtime): prevent Windows client crashes during startup
Refs #619
2026-10-31 22:02:31 +08:00
234 changed files with 15367 additions and 1950 deletions

No files matched your search

+6 -1
View File
@@ -2,7 +2,11 @@
## 关联 Issue
<!-- 例如 Closes #123。若无关联 issue,请说明这个 PR 解决什么问题、为何现在做。 -->
<!-- 必填:在本段填写 Refs #编号 或 Closes #编号(也支持 Fixes / Resolves)。
必须关联至少一个先于本 PR 创建、仍开放且通过模板检查的本仓库 issue。
先通过 GitHub 网页模板提交 issue,或认领已有对应 issue,再可选地提交 PR。
请把关联标记写在本注释之外,不要只保留示例或只填写编号。
目标分支不是 dev,或缺少有效关联 issue 的 PR 会被自动关闭。 -->
## 变更说明
@@ -10,6 +14,7 @@
## 提交前检查
- [ ] 目标分支为 `dev`,正文已关联符合上述要求的 issue
- [ ] 本 PR 聚焦单一目标,未夹带无关改动
- [ ] 已通过 `pnpm lint` 与 `pnpm typecheck`
- [ ] 已补充/更新相关测试,且 `pnpm test` 通过
+204
View File
@@ -0,0 +1,204 @@
const COMMENT_MARKER = '<!-- snowluma-pr-policy-guard -->';
const TEMPLATE_LABELS = new Set(['bug', 'enhancement']);
const PRIVILEGED_AUTHORS = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']);
function prose(body) {
let fence = null;
return (body || '')
.replace(/<!--[\s\S]*?(?:-->|$)/g, '')
.split(/\r?\n/)
.map((line) => {
const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
if (fence) {
if (
marker &&
marker[1][0] === fence[0] &&
marker[1].length >= fence.length &&
!marker[2].trim()
) {
fence = null;
}
return '';
}
if (marker) {
fence = marker[1];
return '';
}
if (/^(?: {4}|\t|\s*>)/.test(line)) {
return '';
}
return line;
})
.join('\n')
.replace(/(`+)[\s\S]*?\1/g, '');
}
function referencedIssues(body, context) {
const repository = `${context.repo.owner}/${context.repo.repo}`.toLowerCase();
const references = new Set();
const pattern =
/\b(?:refs?|close[sd]?|fix(?:e[sd])?|resolve[sd]?):?[ \t]+(https?:\/\/[^\s<>]+|(?:[\w.-]+\/[\w.-]+)?#[1-9]\d*)(?![\w/#-])/gi;
for (const match of prose(body).matchAll(pattern)) {
const reference = match[1].replace(/[),.;!?]+$/, '');
let number;
if (/^https?:\/\//i.test(reference)) {
let url;
try {
url = new URL(reference);
} catch {
continue;
}
const path = url.pathname.match(/^\/([^/]+\/[^/]+)\/issues\/([1-9]\d*)\/?$/i);
if (!path || url.origin !== context.serverUrl || path[1].toLowerCase() !== repository) {
continue;
}
number = Number(path[2]);
} else {
const [name, id] = reference.split('#');
if (name && name.toLowerCase() !== repository) {
continue;
}
number = Number(id);
}
if (Number.isSafeInteger(number) && number > 0) {
references.add(number);
}
}
return [...references];
}
async function violation(pr, github, context) {
if (pr.base.ref !== 'dev') {
return 'PR 的目标分支必须是 `dev`;`main` 仅由维护者的发布流程更新。';
}
const numbers = referencedIssues(pr.body, context);
if (numbers.length === 0) {
return 'PR 正文缺少本仓库 issue 的关联标记。请填写 `Refs #编号`、`Closes #编号`、`Fixes #编号` 或 `Resolves #编号`。';
}
const failures = [];
for (const issue_number of numbers) {
let issue;
try {
({ data: issue } = await github.rest.issues.get({ ...context.repo, issue_number }));
} catch (error) {
if (error.status !== 404 && error.status !== 410) {
throw error;
}
failures.push(`#${issue_number} 不存在或不可访问`);
continue;
}
const expectedUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/issues/${issue_number}`;
if (issue.pull_request) {
failures.push(`#${issue_number} 是 PR,不是 issue`);
} else if (issue.html_url.toLowerCase() !== expectedUrl.toLowerCase()) {
failures.push(`#${issue_number} 已不属于本仓库`);
} else if (issue.state !== 'open') {
failures.push(`#${issue_number} 已关闭`);
} else if (Date.parse(issue.created_at) > Date.parse(pr.created_at)) {
failures.push(`#${issue_number} 晚于本 PR 创建,请先提 issue 再创建 PR`);
} else if (
!PRIVILEGED_AUTHORS.has(issue.author_association) &&
!issue.labels.some((label) =>
TEMPLATE_LABELS.has(typeof label === 'string' ? label : label.name),
)
) {
// Match issue-template-guard.yml immediately, without racing its
// asynchronous close action. Its GITHUB_TOKEN cannot trigger us.
failures.push(`#${issue_number} 未通过 issue 模板检查`);
} else {
return null;
}
}
return `没有有效的关联 issue:${failures.join(';')}。`;
}
module.exports = async function guard({ github, context, core }) {
const params = { ...context.repo, pull_number: context.issue.number };
const { data: pr } = await github.rest.pulls.get(params);
if (pr.state !== 'open' || pr.merged) {
core.info('PR is no longer open; nothing to enforce.');
return;
}
const reason = await violation(pr, github, context);
if (!reason) {
core.info(`PR #${pr.number} targets dev and references an eligible issue.`);
return;
}
// An edit may have fixed the policy while its issue lookup was in flight.
const { data: current } = await github.rest.pulls.get(params);
if (
current.state !== 'open' ||
current.merged ||
current.body !== pr.body ||
current.base.ref !== pr.base.ref
) {
core.info('PR changed during validation; leaving it to the next event.');
return;
}
const commentParams = { ...context.repo, issue_number: pr.number };
const comments = await github.paginate(github.rest.issues.listComments, {
...commentParams,
per_page: 100,
});
const previous = comments.find(
(comment) =>
comment.user?.login === 'github-actions[bot]' && comment.body?.startsWith(COMMENT_MARKER),
);
const body = [
COMMENT_MARKER,
'此 PR 未满足贡献要求,现自动关闭。',
'',
reason,
'',
'请先通过 [GitHub 网页模板](' +
context.serverUrl +
'/' +
context.repo.owner +
'/' +
context.repo.repo +
'/issues/new/choose) 提交 issue;也可以认领已有的对应 issue。',
'PR 必须指向 `dev`,并在正文引用至少一个先于 PR 创建、仍开放且通过模板检查的本仓库 issue。注释、代码示例和引用块中的标记不计入。',
'若已有符合要求的 issue,可修改目标分支或正文后重新打开 PR;若需新建 issue,请先完成 issue 再创建新的 PR。',
].join('\n');
if (previous) {
if (previous.body !== body) {
await github.rest.issues.updateComment({ ...context.repo, comment_id: previous.id, body });
}
} else {
await github.rest.issues.createComment({ ...commentParams, body });
}
await github.rest.pulls.update({ ...params, state: 'closed' });
core.setFailed(`Closed PR #${pr.number}: ${reason}`);
};
+313
View File
@@ -0,0 +1,313 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const guard = require('./pr-policy-guard.cjs');
function fixture() {
const pr = {
number: 100,
state: 'open',
merged: false,
base: { ref: 'dev' },
body: 'Refs #42',
created_at: '2026-11-01T10:00:00Z',
};
const issue = {
number: 42,
state: 'open',
html_url: 'https://github.com/SnowLuma/SnowLuma/issues/42',
created_at: '2026-11-01T09:00:00Z',
author_association: 'NONE',
labels: [{ name: 'bug' }],
};
const state = {
pr,
issue,
issues: new Map([[42, issue]]),
comments: [],
lookups: [],
mutations: [],
failures: [],
refresh: null,
requests: 0,
};
const context = {
repo: { owner: 'SnowLuma', repo: 'SnowLuma' },
issue: { number: 100 },
serverUrl: 'https://github.com',
};
const github = {
rest: {
pulls: {
get: async () => {
state.requests += 1;
return {
data: structuredClone(state.requests > 1 && state.refresh ? state.refresh : pr),
};
},
update: async (params) => state.mutations.push({ action: 'close', ...params }),
},
issues: {
get: async ({ issue_number }) => {
state.lookups.push(issue_number);
const result = state.issues.get(issue_number);
if (result instanceof Error) {
throw result;
}
if (!result) {
throw Object.assign(new Error('Not found'), { status: 404 });
}
return { data: structuredClone(result) };
},
listComments: () => {},
createComment: async (params) => state.mutations.push({ action: 'comment', ...params }),
updateComment: async (params) =>
state.mutations.push({ action: 'edit-comment', ...params }),
},
},
paginate: async () => structuredClone(state.comments),
};
const core = {
info: () => {},
setFailed: (reason) => state.failures.push(reason),
};
return { ...state, state, github, run: () => guard({ github, context, core }) };
}
function assertClosed(f, reason) {
assert.deepEqual(
f.mutations.map((entry) => entry.action),
['comment', 'close'],
);
assert.equal(f.mutations[1].pull_number, 100);
assert.equal(f.mutations[1].state, 'closed');
assert.match(f.mutations[0].body, reason);
assert.equal(f.failures.length, 1);
}
for (const body of [
'Refs #42',
'refs: #42',
'Ref #42',
'Close #42',
'Closes #42',
'Closed #42',
'Fix #42',
'Fixes #42',
'Fixed #42',
'Resolve #42',
'Resolves #42',
'Resolved #42',
'This change fixes #42.',
'CLOSES: #42',
'Refs SnowLuma/SnowLuma#42',
'Refs snowluma/snowluma#42',
'Refs https://github.com/SnowLuma/SnowLuma/issues/42',
]) {
test(`accepts a real issue reference: ${body}`, async () => {
const f = fixture();
f.pr.body = body;
await f.run();
assert.deepEqual(f.lookups, [42]);
assert.deepEqual(f.mutations, []);
assert.deepEqual(f.failures, []);
});
}
for (const body of [
'',
null,
'#42',
'prefixRefs #42',
'Refs #0',
'Refs #42abc',
'Refs #42/other',
'Refs #9007199254740993',
'Refs other/repo#42',
'Refs https://github.com/other/repo/issues/42',
'Refs https://example.org/SnowLuma/SnowLuma/issues/42',
'Refs https://github.com/SnowLuma/SnowLuma/pull/42',
'Refs https://%',
'<!-- Closes #42 -->',
'<!-- Closes #42',
'`Refs #42`',
'```text\nRefs #42\n```',
'~~~\nRefs #42\n~~~',
'```\nRefs #42',
'> Closes #42',
' Refs #42',
'\tRefs #42',
]) {
test(`does not treat examples or invalid references as an issue: ${JSON.stringify(body)}`, async () => {
const f = fixture();
f.pr.body = body;
await f.run();
assert.deepEqual(f.lookups, []);
assertClosed(f, /缺少本仓库 issue/);
});
}
for (const base of ['main', 'release/v2', 'feature/example']) {
test(`closes a PR targeting ${base} before looking up issues`, async () => {
const f = fixture();
f.pr.base.ref = base;
await f.run();
assert.deepEqual(f.lookups, []);
assertClosed(f, /目标分支必须是 `dev`/);
});
}
for (const [patch, reason] of [
[{ pull_request: {} }, /是 PR,不是 issue/],
[{ state: 'closed', state_reason: 'not_planned' }, /已关闭/],
[{ state: 'closed', state_reason: 'completed' }, /已关闭/],
[{ html_url: 'https://github.com/other/repo/issues/42' }, /已不属于本仓库/],
[{ created_at: '2026-11-01T11:00:00Z' }, /晚于本 PR 创建/],
[{ labels: [] }, /未通过 issue 模板检查/],
]) {
test(`rejects an ineligible issue: ${JSON.stringify(patch)}`, async () => {
const f = fixture();
Object.assign(f.issue, patch);
await f.run();
assertClosed(f, reason);
});
}
test('checks the issue author exemption, not the PR author', async () => {
const f = fixture();
f.pr.author_association = 'OWNER';
f.issue.labels = [];
await f.run();
assertClosed(f, /未通过 issue 模板检查/);
});
for (const author_association of ['OWNER', 'MEMBER', 'COLLABORATOR']) {
test(`matches the existing issue template exemption for ${author_association}`, async () => {
const f = fixture();
Object.assign(f.issue, { author_association, labels: [] });
await f.run();
assert.deepEqual(f.mutations, []);
assert.deepEqual(f.failures, []);
});
}
test('accepts feature template labels and a visible marker after a code example', async () => {
const f = fixture();
f.issue.labels = ['enhancement'];
f.pr.body = '```text\nRefs #999\n```\nRefs #42';
await f.run();
assert.deepEqual(f.lookups, [42]);
assert.deepEqual(f.mutations, []);
});
test('deduplicates references and accepts at least one eligible issue', async () => {
const f = fixture();
f.pr.body = 'Refs #404\nCloses #404\nRefs #42';
await f.run();
assert.deepEqual(f.lookups, [404, 42]);
assert.deepEqual(f.mutations, []);
});
for (const status of [404, 410]) {
test(`rejects a missing or deleted issue (${status})`, async () => {
const f = fixture();
f.issues.set(42, Object.assign(new Error('Unavailable'), { status }));
await f.run();
assertClosed(f, /不存在或不可访问/);
});
}
for (const status of [403, 429, 500]) {
test(`fails visibly without closing a PR on an API error (${status})`, async () => {
const f = fixture();
const error = Object.assign(new Error('API unavailable'), { status });
f.issues.set(42, error);
await assert.rejects(f.run, error);
assert.deepEqual(f.mutations, []);
});
}
test('does not close a PR whose author fixed the body during validation', async () => {
const f = fixture();
f.pr.body = '';
f.state.refresh = { ...f.pr, body: 'Refs #42' };
await f.run();
assert.deepEqual(f.mutations, []);
assert.deepEqual(f.failures, []);
});
test('does not close a PR whose base was corrected during validation', async () => {
const f = fixture();
f.pr.base.ref = 'main';
f.state.refresh = { ...f.pr, base: { ref: 'dev' } };
await f.run();
assert.deepEqual(f.mutations, []);
});
test('leaves closed and merged PRs alone', async () => {
const f = fixture();
Object.assign(f.pr, { state: 'closed', merged: true });
await f.run();
assert.deepEqual(f.lookups, []);
assert.deepEqual(f.mutations, []);
});
test('updates its own previous rejection comment when a PR is reopened', async () => {
const f = fixture();
f.pr.body = '';
f.comments.push({
id: 7,
user: { login: 'github-actions[bot]' },
body: '<!-- snowluma-pr-policy-guard -->\nold reason',
});
await f.run();
assert.deepEqual(
f.mutations.map((entry) => entry.action),
['edit-comment', 'close'],
);
assert.equal(f.mutations[0].comment_id, 7);
});
test('does not overwrite a contributor comment containing the guard marker', async () => {
const f = fixture();
f.pr.body = '';
f.comments.push({
id: 7,
user: { login: 'contributor' },
body: '<!-- snowluma-pr-policy-guard -->',
});
await f.run();
assertClosed(f, /缺少本仓库 issue/);
});
test('does not close the PR if its explanation cannot be posted', async () => {
const f = fixture();
f.pr.body = '';
const error = Object.assign(new Error('Comment rejected'), { status: 403 });
f.github.rest.issues.createComment = async () => {
throw error;
};
await assert.rejects(f.run, error);
assert.deepEqual(f.mutations, []);
});
test('reuses an unchanged explanation without posting or editing another comment', async () => {
const first = fixture();
first.pr.body = '';
await first.run();
const reopened = fixture();
reopened.pr.body = '';
reopened.comments.push({
id: 7,
user: { login: 'github-actions[bot]' },
body: first.mutations[0].body,
});
await reopened.run();
assert.deepEqual(
reopened.mutations.map((entry) => entry.action),
['close'],
);
});
+27 -11
View File
@@ -1,20 +1,36 @@
name: Main PR target guard
name: PR policy guard
# `main` is a pointer moved by Promote Dev to Main. Contributor and bot
# feature work lands on dev. A PR opened against main (like the GHCR
# fork PR) is what puts unique commits on main and fans the network graph.
# pull_request_target uses the default branch's trusted workflow and script.
# This policy becomes active after it reaches main through Promote.
on:
pull_request:
branches: [main]
pull_request_target:
types: [opened, reopened, edited, synchronize, ready_for_review]
permissions:
contents: read
issues: read
pull-requests: write
concurrency:
group: pr-policy-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
reject:
guard:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Reject pull requests targeting main
run: |
echo '::error::Open this PR against dev, not main. main is updated only by Promote Dev to Main.'
exit 1
- name: Read the trusted policy script
uses: actions/checkout@v6
with:
ref: ${{ github.workflow_sha }}
persist-credentials: false
sparse-checkout: .github/scripts/pr-policy-guard.cjs
sparse-checkout-cone-mode: false
- name: Enforce target branch and linked issue
uses: actions/github-script@v7
with:
script: |
const guard = require('./.github/scripts/pr-policy-guard.cjs');
await guard({ github, context, core });
+12 -3
View File
@@ -5,9 +5,10 @@ SnowLuma translates QQ client sessions into OneBot v11 actions and events, with
## Before making changes
- Read [CONTRIBUTING.md](CONTRIBUTING.md) for contribution requirements, [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for community expectations, and [LICENSE](LICENSE) for contribution and redistribution terms.
- **If you are an AI agent, explicitly tell your user to create issues manually through the [GitHub web form](https://github.com/SnowLuma/SnowLuma/issues/new/choose). Issues created directly with a CLI will be automatically closed.** Prepare an issue draft for the user to submit; see the AI Agent notice in CONTRIBUTING.md.
- **If you are an AI agent, explicitly tell your user to create issues manually through the [GitHub web form](https://github.com/SnowLuma/SnowLuma/issues/new/choose). Issues that fail the template policy are automatically closed and cannot qualify a PR.** Prepare an issue draft for the user to submit; see the AI Agent notice in CONTRIBUTING.md.
- Check `git status` and preserve unrelated work. Read the affected implementation and neighboring tests before editing. Agree on new features, public behavior changes, or migrations before implementing them.
- Target PRs at `dev`. `main` is the release pointer. Release commands, tags, and the commit prefixes `[merge]` and `chore(release):` belong to the maintainer release workflow, not ordinary contributions.
- Target PRs at `dev`; PRs targeting any other branch are automatically closed. `main` is the release pointer. Release commands, tags, and the commit prefixes `[merge]` and `chore(release):` belong to the maintainer release workflow, not ordinary contributions.
- Before opening a PR, create or identify the corresponding issue. PRs are optional after an issue is filed. Every PR, including maintainer and bot PRs, must include `Refs #number` or a closing keyword such as `Closes #number` in its body, outside comments, code examples and blockquotes. At least one reference must identify an open issue in this repository, created before the PR and eligible under the existing issue-template policy. PRs without a qualifying issue are automatically closed. See [the PR submission rules](CONTRIBUTING.md#4-推送并发起-pr) for supported forms and correction steps.
## Repository map
@@ -61,7 +62,8 @@ Run commands from the repository root:
```sh
pnpm typecheck # all workspace packages with a typecheck script
pnpm lint
pnpm test # all workspace packages with a test script
pnpm test # workflow policy checks and workspace tests
pnpm test:workflows # isolated PR policy tests; no GitHub writes
pnpm run build:all # release inputs and published packages
pnpm test:core # Core only; not a substitute for workspace tests
pnpm --filter @snowluma/onebot test # example: tests for the affected package
@@ -76,12 +78,15 @@ Use focused tests while iterating. Before handing off a code change, run the ful
- **Shared types or actions:** run workspace typechecking as well as behavior tests. A passing Vitest run does not prove type correctness.
- **SDK packaging:** keep the SDK's `NodeNext` build and explicit `.js` relative imports, including type-only exports. Its package tests compile fresh output and check native Node.js imports, consumer declarations, and complete action-map coverage. The SDK action catalog must match OneBot's executable names; `packages/onebot/tests/sdk-actions.test.ts` checks this without adding a runtime dependency on server code. SDK parameter/result contracts remain independent of server types; keep consumer examples under `packages/sdk/tests/fixtures` aligned with the server parser checks in `packages/onebot/tests/sdk-action-params.test.ts`.
- **SDK streams:** preserve the single-response client methods and use the additive interfaces in [STREAMING.md](packages/sdk/STREAMING.md) for file transfers. Test framing, cancellation, bounded buffering and incomplete transfers in the SDK; `packages/onebot/tests/sdk-streaming.test.ts` checks real adapter/handler round trips in temporary storage without QQ.
- **SDK reverse WebSocket:** Node-only listeners accept OneBot implementation connections, never substitute an outgoing SDK client for a protocol implementation. Reuse the shared client session for actions/events/streams and preserve per-account identity, API/Event pairing, bounded buffers and pending-request rejection on disconnect. Test the real runtime reverse adapter and fresh published imports; see [REVERSE_WEBSOCKET.md](packages/sdk/REVERSE_WEBSOCKET.md).
- **SDK messaging:** preserve existing string-path and ordinary reply semantics when extending the helpers in [MESSAGING.md](packages/sdk/MESSAGING.md). Filesystem access belongs only in the optional `@snowluma/sdk/node` entry point. Media sends must await upload completion and retain failure context without automatic retries; event waits follow public middleware dispatch and release listeners on every outcome. Keep legacy handler/context types assignable when adding richer SDK-created contexts.
- **MCP agents:** preserve existing text results, business-error envelopes, default search matching and mode gates when extending the tools. Use the server SDK's `serveStdio` entry to support modern discovery and legacy initialization from the same command; test both with freshly compiled output. Cache hints belong only on bundled catalog discovery, never execution or account data. Keep trace metadata out of action parameters and sensitive data out of diagnostics. Protocol compatibility, tracing and the additive agent features are documented in [AGENT_FEATURES.md](packages/mcp/AGENT_FEATURES.md). Use isolated HTTP and MCP transports in tests; local runtime inspection must not query a live account.
- **MCP execution services:** keep background tasks and event connections opt-in. Persist task state before effects, never replay interrupted writes, and finish durable cleanup before draining the protocol on shutdown. Input continuations must retain their original arguments and execute at most once. Event buffers require explicit account binding, bounded storage and visible gaps. Build the bundled message preview through `packages/mcp/scripts/build-message-app.mjs`; loading a preview must not send a message. Test restart, cancellation and legacy compatibility using isolated transports, including the compiled CLI.
- **Protocol codecs:** keep the existing Proton integration in tests so they exercise the same transformations as production. Import real implementations; do not duplicate the algorithm in the test.
- **Video uploads:** preserve the single-connection default and the additive global setting in [HIGHWAY_UPLOADS.md](packages/protocol/HIGHWAY_UPLOADS.md). Only video bodies opt into parallel chunks. Confirm every chunk before completion, bound both concurrency and lookahead, and drain outstanding reads and requests before closing the source. Keep retries bounded and backpressure changes visible. Test the actual uploader with isolated transports; passing tests do not prove live throughput.
- **Highway upload recovery:** all chunks and workers share one file transfer deadline. Keep node observations bounded, short-lived and isolated by account session, upload type and full host/port; select only current server-supplied candidates. Only validated acknowledgements establish success. Preserve terminal failure reporting and drain pending file reads after cancellation. Test deadline cleanup and candidate rotation with isolated transports, including real loopback sockets; see [upload policy](packages/protocol/HIGHWAY_UPLOADS.md#upload-timeouts-and-node-selection).
- **Native coverage:** `pnpm test:native` is separate from default protocol tests and requires compatible native artifacts. A missing artifact or unavailable target is a reported limitation, not permission to bypass the check.
- **OneBot SSE:** HTTP event streams share the HTTP adapter's binding and authentication. Preserve account isolation, bounded replay, visible expired-cursor errors, report filtering and slow-reader limits described in [HTTP_SSE.md](packages/onebot/HTTP_SSE.md). Token/report-policy changes revoke existing streams and invalidate replay; test shutdown and reload with active connections.
- **Live QQ behavior:** fixture tests and a successful API response do not prove delivery or client rendering. State what was tested locally and what still needs a real client.
`pnpm dev` starts Core and can attach to local QQ processes; use it only when runtime testing is intended. `pnpm dev:web` starts the frontend, which expects a WebUI backend. Follow the existing test fakes for isolated work rather than starting a live account unnecessarily.
@@ -117,6 +122,10 @@ After changing an action name, parameter, result description/schema, example or
SDK breaking changes also update [CHANGELOG.md](packages/sdk/CHANGELOG.md) and [VERSIONING.md](packages/sdk/VERSIONING.md). WebUI changes follow its [interaction conventions](packages/webui/README.md). Keep user-facing documentation aligned with behavior.
Standalone WebUI branding uses the [SnowLuma mascot](assets/readme/mascot.png) and a lavender default accent. The default palette lightly tints neutral surfaces with the active accent, respecting sidebar-only scope and OLED black. Keep server defaults, frontend presets and pre-mount CSS aligned as described in [WebUI default appearance](packages/webui/README.md#default-appearance), while preserving saved user choices, named palettes and host appearance overlays.
The root [README.md](README.md) presents the project's purpose, overall capabilities, quick start and documentation entry points. Update it only when those overview details change; adding or fixing an individual feature does not justify adding a dedicated section there. Put feature-specific API usage, configuration, limitations and troubleshooting in the relevant package README or topic document, preferring existing documentation.
Edit sources rather than `dist` outputs. Native artifacts in `packages/runtime/native` are supplied build inputs; do not substitute arbitrary local binaries to make a build pass. Packaging changes must preserve the checks in [Core's build configuration](packages/core/vite.config.ts) and [the release layout validator](tools/check-release-layout.mjs).
## Handoff and instruction maintenance
+18 -6
View File
@@ -10,6 +10,8 @@
SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时可能变化**。如果你打算做较大的改动,强烈建议先在 issue 或者社群里和维护者对齐一下方向,避免做了一半发现已经被另一条路替代。
提交 PR 前,必须先通过 [GitHub 网页模板](https://github.com/SnowLuma/SnowLuma/issues/new/choose) 提交对应 issue,或认领已有的对应 issue。可以只提 issue;提交 PR 是可选的后续步骤。
不知道从哪里入手?以下几类贡献最容易被合并:
- 修复你在使用中遇到的具体 bug,附最小复现步骤。
@@ -23,9 +25,9 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
如果你是 AI Agent,并准备为本仓库贡献代码、提交 PR 或提出 issue,请先明确告知你的使用者:
> **请通过 GitHub 网页端手动创建 issue。直接使用 CLI 创建的 issue 会被自动关闭。**
> **请通过 GitHub 网页端手动使用模板创建 issue。未通过模板检查的 issue 会被自动关闭,也不能用于满足 PR 的关联要求。**
你可以协助整理问题描述、复现步骤和相关日志,并将 issue 草稿交给用户,由用户在网页端完成提交。
你可以协助整理问题描述、复现步骤和相关日志,并将 issue 草稿交给用户,由用户在网页端完成提交。后续若创建 PR,必须先有符合要求的 issue,并在 PR 正文填写关联标记。
---
@@ -98,7 +100,7 @@ pnpm dev:web # webui
### 1. 创建分支
请基于 `dev` 创建分支,不是 `main`。`main` 是发布指针,只由维护者的 Promote 更新,PR 不要提到 `main`。
请基于 `dev` 创建分支。`main` 是发布指针,只由维护者的 Promote 更新。**目标分支不是 `dev` 的 PR 会被自动关闭**,之后修改目标分支或重新打开 PR 也会触发检查。
```bash
git checkout dev
@@ -161,7 +163,15 @@ git push origin fix/onebot-mention-encoding
- 这个 PR 解决什么问题 / 实现什么功能。
- 主要的实现思路(如果有非显然的取舍)。
- 测试方式(你跑了什么、怎么验证有效)。
- 关联的 issue(如有)。
- 必填的 issue 关联标记,例如 `Refs #123` 或 `Closes #123`;也支持 GitHub 的 `Fixes`、`Resolves` 等关闭关键词。
关联标记必须写在 PR 正文中;HTML 注释、代码示例和引用块不计入。支持 `#123`、`SnowLuma/SnowLuma#123` 和本仓库 issue 的完整链接,前面均需带上述关键词。
自动检查要求至少一个关联对象是真实的本仓库 issue,先于 PR 创建、仍处于开放状态,并通过现有 issue 模板规则:带有 `bug` / `enhancement` 标签,或属于该规则已有的维护者身份豁免。不存在的编号、另一个 PR、已关闭或模板不合规的 issue 都不算。**所有 PR 都必须满足目标分支和 issue 关联要求,包括维护者与机器人提交的 PR。**
不符合要求的 PR 会收到说明并自动关闭。若已有符合要求的 issue,可修改 PR 后重新打开;若需补建 issue,请先提交 issue,再创建新的 PR。接口故障或限流会让检查失败,不会被当成 PR 违规而自动关闭。
`Refs` 用于关联;`Closes` 等关键词在这里也用于关联检查。由于 PR 目标为 `dev`,合并到 `dev` 本身不会触发 GitHub 针对默认分支的 issue 自动关闭机制。
### 5. Code Review 与合并
@@ -205,10 +215,12 @@ Prettier,并按需开启保存时格式化。
- 单测放在被测代码同包的 `tests/` 或同目录的 `*.test.ts`,按既有风格走。
- 测试要描述行为,不要测实现细节。`it('should call internal foo')` 这种是反例。
- 涉及 IO / 时序 / 外部进程的,用现有的 fake/stub 模式,参考 `packages/onebot/tests/` 中的 Bridge 测试替身。
- PR 自动检查的隔离回归可运行 `pnpm test:workflows`;`pnpm test` 已包含此检查,不需要创建真实 PR 来测试自动关闭。
### 文档
- 用户/贡献者可见的行为变化,需要相应更新 README 或对应 package 下的文档。
- **主 README 的定位**:根目录 [`README.md`](./README.md) 用于展示项目定位、整体能力、快速开始和文档入口,仅在这些总体信息发生变化时更新。不要因为新增或修复某个具体功能,就在主 README 增加该功能的专门说明。
- **具体功能的说明位置**:接口用法、配置项、功能限制和排障说明写入对应 package 的 README 或专题文档,优先更新已有文档。用户/贡献者可见的行为变化,仍需同步维护对应文档。
- SDK 的破坏性变更必须更新 `packages/sdk/CHANGELOG.md` 和 `packages/sdk/VERSIONING.md`。
---
@@ -315,7 +327,7 @@ git push origin v1.7.0 # → 仅触发 release.yml
- 看一下已有的 issue 和 PR,可能你的问题已经被讨论过。
- 去社群问一句(QQ / TG 链接见上方)。
- 如果只是想确认"我这么改 OK 吗",欢迎开 draft PR,先把代码亮出来再讨论。
- 有对应 issue 后,如果只是想确认"我这么改 OK 吗",欢迎开 draft PR,把代码亮出来再讨论。
感谢你愿意花时间贡献 SnowLuma —— 这个项目能走多远,取决于你们每一个人。❄️
+17 -10
View File
@@ -1,22 +1,29 @@
<p align="center">
<img src="./assets/readme/hero.svg" width="100%" alt="SnowLuma 将 QQ 原生会话桥接到 OneBot、WebUI 与自动化工具" />
</p>
# SnowLuma<picture><img align="right" src="./assets/readme/mascot.png" width="34%" alt="" /></picture>
<p align="center">
**让 QQ 原生会话,连接你的应用。**
QQ 客户端的 TypeScript 互操作运行时。<br>
OneBot v11 · WebUI · SDK · MCP
<p>
<a href="https://github.com/SnowLuma/SnowLuma/releases"><img alt="最新版本" src="https://img.shields.io/github/v/release/SnowLuma/SnowLuma?label=release&style=flat-square"></a>
<a href="https://github.com/SnowLuma/SnowLuma/actions/workflows/dev-build.yml"><img alt="构建状态" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/dev-build.yml?branch=dev&style=flat-square&label=build"></a>
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="SnowLuma SDK 版本" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=sdk&color=287fb8"></a>
<a href="https://www.npmjs.com/package/@snowluma/mcp"><img alt="SnowLuma MCP 版本" src="https://img.shields.io/npm/v/%40snowluma%2Fmcp?style=flat-square&label=mcp&color=7658c7"></a>
<a href="https://hub.docker.com/r/motricseven7/snowluma"><img alt="Docker 拉取次数" src="https://img.shields.io/docker/pulls/motricseven7/snowluma?style=flat-square&label=docker%20pulls"></a>
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="GitHub Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
</p>
<p align="center">
<a href="#快速开始">快速开始</a> ·
<a href="https://snowluma.github.io/zh/docs/api">动作参考</a> ·
<a href="https://github.com/SnowLuma/SnowLuma/issues">问题反馈</a>
</p>
将 QQ 原生会话转换为 [OneBot v11](https://github.com/botuniverse/onebot-11) 动作与事件,通过 WebSocket、HTTP、WebUI、SDK 和 MCP 提供统一入口。
SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生会话转换为 [OneBot v11](https://github.com/botuniverse/onebot-11) 动作与事件,并通过 WebSocket、HTTP、WebUI、SDK 和 MCP 提供统一入口。
多账号会话、消息与媒体、连接配置和实时日志,在一个运行时中管理。
**[下载发行版](https://github.com/SnowLuma/SnowLuma/releases)** · **[快速开始](#快速开始)**<br>
[部署指南](https://snowluma.github.io/zh/docs/guide/deploy) · [动作参考](https://snowluma.github.io/zh/docs/api) · [问题反馈](https://github.com/SnowLuma/SnowLuma/issues)
<sub>Windows x64 · Linux x64 / arm64</sub>
<br clear="both" />
> [!CAUTION]
> SnowLuma 是独立的第三方项目,与腾讯 / QQ 无隶属或授权关系。项目仅供学习与技术研究,请遵守《QQ 用户协议》及适用法律;软件按“现状”提供,使用风险自负。详见 [`EULA.md`](EULA.md)。
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

+3 -2
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "2.3.0",
"version": "2.4.2",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -15,7 +15,8 @@
"dev": "pnpm --filter @snowluma/core dev",
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
"dev:web": "pnpm --filter webui dev",
"test": "pnpm --filter=\"./packages/**\" -r --no-bail --if-present test",
"test": "pnpm test:workflows && pnpm --filter=\"./packages/**\" -r --no-bail --if-present test",
"test:workflows": "node --test .github/scripts/*.test.cjs",
"test:core": "pnpm --filter @snowluma/core test",
"test:watch": "pnpm --filter @snowluma/core test:watch",
"test:common": "pnpm --filter @snowluma/common test",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "2.3.0",
"version": "2.4.2",
"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).",
+241 -34
View File
@@ -23,6 +23,14 @@ const LOGIN_IDENTITY_OBSERVE_INTERVAL_MS = 30_000;
const LOGIN_HINT_MAX_ATTEMPTS = 3;
const LOGIN_HINT_RETRY_DELAYS_MS = [3000, 9000] as const;
/** Bounds channel discovery and handshakes, not account login. */
const INITIAL_CONNECTION_TIMEOUT_MS = 60_000;
type InitialConnectionWatch = {
startedAt: number;
timer: ReturnType<typeof setTimeout>;
};
/** QQ emits this response periodically while its MSF receive path is healthy.
* Seeing it once arms the watchdog; before that, silence is UNKNOWN rather
* than unhealthy so QQ versions that do not expose this command cannot be
@@ -103,7 +111,14 @@ export class HookSession extends EventEmitter {
private bound = false;
private opChain: Promise<unknown> = Promise.resolve();
private disposed = false;
private initialConnectionWatch: InitialConnectionWatch | null = null;
private initialConnectionError = '';
private hasConnected = false;
private cancelConnectAttempt: (() => void) | null = null;
private pipeUpPending = false;
private loginReconcileTimer: ReturnType<typeof setInterval> | null = null;
private loginIdentityEpoch = 0;
private invalidLoginStateReported = false;
private detecting = false;
private lastDetectFailure = '';
private acceptedLoginHintUin = '';
@@ -184,6 +199,7 @@ export class HookSession extends EventEmitter {
}
unload(): Promise<HookProcessInfo> {
this.cancelConnectAttempt?.();
return this.traceCommand('unload', () => this.unloadInternal());
}
@@ -197,19 +213,26 @@ export class HookSession extends EventEmitter {
* attempts and adopts pre-existing hooks. Idempotent; safe to call on
* every watcher tick where the pipe is live. */
onPipeUp(): void {
if (this.disposed) {
if (this.disposed || this.pipeUpPending || this.cancelConnectAttempt) {
return;
}
// Watcher ticks must not queue a backlog of stalled handshakes ahead of
// user commands. The next tick can retry once this attempt has settled.
this.pipeUpPending = true;
void this.serialize(async () => {
if (this.disposed) {
return;
}
await this.reconcilePipeUp();
}).catch((err) =>
this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errorMessage(err)),
);
})
.catch((err) =>
this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errorMessage(err)),
)
.finally(() => {
this.pipeUpPending = false;
});
}
onPipeDown(): void {
@@ -235,6 +258,7 @@ export class HookSession extends EventEmitter {
return;
}
this.cancelConnectAttempt?.();
void this.serialize(async () => {
if (this.disposed) {
return;
@@ -248,6 +272,7 @@ export class HookSession extends EventEmitter {
this.pid,
renderParamsVerbose(this.toInfo()),
]);
this.stopInitialConnectionWatch();
this.tearDownClient();
this.injected = false;
this.injectResult = null;
@@ -292,6 +317,7 @@ export class HookSession extends EventEmitter {
const wasLoggedIn = this.loggedIn;
this.disposed = true;
this.stopInitialConnectionWatch();
this.tearDownClient();
// Process shutdown must take the same PID-detach path as a live drop.
@@ -374,6 +400,10 @@ export class HookSession extends EventEmitter {
// ─────────────── internal transitions ───────────────
private async loadInternal(): Promise<HookProcessInfo> {
if (this.disposed) {
return this.toInfo();
}
this._error = '';
this.setStatus('loading', '');
@@ -407,6 +437,14 @@ export class HookSession extends EventEmitter {
}
}
if (this.disposed) {
return this.toInfo();
}
// A retry reuses the loaded component and its unload handle. Only an
// expired deadline is restarted; repeated clicks cannot postpone it.
this.initialConnectionError = '';
this.startInitialConnectionWatch();
this.applyStatus();
} catch (error) {
this._error = errorMessage(error);
@@ -429,6 +467,9 @@ export class HookSession extends EventEmitter {
private async unloadInternal(): Promise<HookProcessInfo> {
this._error = '';
this.stopInitialConnectionWatch();
this.initialConnectionError = '';
this.hasConnected = false;
try {
const wasLoggedIn = this.loggedIn;
@@ -506,6 +547,11 @@ export class HookSession extends EventEmitter {
return;
}
if (this.initialConnectionError) {
this.setStatus('error', this.initialConnectionError);
return;
}
this.setStatus(
statusFor({
injected: this.injected,
@@ -529,6 +575,8 @@ export class HookSession extends EventEmitter {
}
}
this.startInitialConnectionWatch();
if (this.client?.isClosed) {
this.tearDownClient();
}
@@ -627,29 +675,30 @@ export class HookSession extends EventEmitter {
}
const client = this.client;
const watch = this.initialConnectionWatch;
const timeoutMs = watch
? Math.max(1, INITIAL_CONNECTION_TIMEOUT_MS - (Date.now() - watch.startedAt))
: INITIAL_CONNECTION_TIMEOUT_MS;
try {
await client.connectAll({ recv: true });
await this.connectWithTimeout(client, timeoutMs);
if (this.disposed || this.client !== client) {
return;
}
if (this.runtimeFailure) {
throw new Error(this.runtimeFailure);
}
this.connected = true;
const loginState = client.getLoginState();
// handleLoginState owns the connected+loggedIn → 'online' (+ login
// emit) transition; defer to it so the status is set once. Otherwise
// we're connected-but-not-logged-in → 'loaded'.
if (loginState.loggedIn) {
this.handleLoginState(loginState);
} else {
this.applyStatus();
// The native hook only PUSHES a loginState frame on the login edge;
// if QQ logged in before/around connect (Docker auto-login) that edge
// is missed and we'd wait forever. Keep re-detecting until logged in.
runWithoutRequestContext(() => this.startLoginReconcile());
}
this.hasConnected = true;
this.stopInitialConnectionWatch();
this.initialConnectionError = '';
this._error = '';
// Identity validation owns readiness and whether to keep checking.
// A reported login alone does not establish a usable account.
this.handleLoginState(client.getLoginState());
this.log.info('pipe connected: PID=%d', this.pid);
this.log.trace(() => [
@@ -659,11 +708,27 @@ export class HookSession extends EventEmitter {
Date.now() - startedAt,
]);
} catch (error) {
if (this.disposed || this.client !== client) {
return;
}
this._error = errorMessage(error);
const wasLoggedIn = this.loggedIn;
// Drop the client so the next attempt builds a fresh socket pair.
// A failed connect was never logged in → 'connecting' (or 'available').
this.tearDownClient(true);
this.applyStatus(false, this._error);
if (watch && Date.now() - watch.startedAt >= INITIAL_CONNECTION_TIMEOUT_MS) {
this.expireInitialConnection(watch, 'handshake');
}
this.applyStatus(wasLoggedIn, this._error);
// Login can arrive on one channel while the other is still
// handshaking. Revoke that binding if the full connection fails.
if (wasLoggedIn) {
this.emit('disconnected', true);
}
this.log.trace(() => [
'hook_session_connect_terminal pid=%d outcome=failed reason=connect_failed error=%j state=%s elapsedMs=%d',
this.pid,
@@ -675,6 +740,94 @@ export class HookSession extends EventEmitter {
});
}
private startInitialConnectionWatch(): void {
if (
this.disposed ||
this.hasConnected ||
this.initialConnectionWatch ||
this.initialConnectionError
) {
return;
}
const watch: InitialConnectionWatch = {
startedAt: Date.now(),
timer: setTimeout(() => {
void this.serialize(async () => this.expireInitialConnection(watch)).catch(
(error) =>
this.log.error(
'initial connection timeout transition failed: PID=%d err=%s',
this.pid,
errorMessage(error),
),
);
}, INITIAL_CONNECTION_TIMEOUT_MS),
};
watch.timer.unref();
this.initialConnectionWatch = watch;
this.log.debug(
'initial connection started: PID=%d timeoutMs=%d',
this.pid,
INITIAL_CONNECTION_TIMEOUT_MS,
);
}
private stopInitialConnectionWatch(): void {
if (this.initialConnectionWatch) {
clearTimeout(this.initialConnectionWatch.timer);
this.initialConnectionWatch = null;
}
}
private expireInitialConnection(
watch: InitialConnectionWatch,
phase: 'waiting_channel' | 'handshake' = 'waiting_channel',
): void {
if (this.disposed || this.connected || this.initialConnectionWatch !== watch) {
return;
}
const previousError = this._error;
this.stopInitialConnectionWatch();
this.initialConnectionError =
'首次连接超时(60 秒):组件已加载,但通信通道尚未就绪,可重试连接或卸载组件';
this.log.error(
'initial connection timed out: PID=%d phase=%s timeoutMs=%d elapsedMs=%d previousError=%j',
this.pid,
phase,
INITIAL_CONNECTION_TIMEOUT_MS,
Date.now() - watch.startedAt,
previousError,
);
this.applyStatus();
}
private async connectWithTimeout(client: QqHookClient, timeoutMs: number): Promise<void> {
let cancel!: () => void;
let timer!: ReturnType<typeof setTimeout>;
const deadline = new Promise<never>((_, reject) => {
cancel = () => reject(new Error('Connection attempt cancelled'));
timer = setTimeout(
() => reject(new Error(`Connection handshake timed out after ${timeoutMs} ms`)),
timeoutMs,
);
timer.unref();
});
this.cancelConnectAttempt = cancel;
try {
// A stalled handshake must release the serialized operation queue so
// timeout handling and unload can run. Late completion has no effects.
await Promise.race([client.connectAll({ recv: true }), deadline]);
} finally {
clearTimeout(timer);
if (this.cancelConnectAttempt === cancel) {
this.cancelConnectAttempt = null;
}
}
}
private bindClient(client: QqHookClient): void {
client.on('runtimeError', (error) => {
if (this.client !== client || this.disposed) {
@@ -683,6 +836,7 @@ export class HookSession extends EventEmitter {
const wasLoggedIn = this.loggedIn;
this.runtimeFailure = errorMessage(error);
this.stopInitialConnectionWatch();
this.loggedIn = false;
this.stopLoginReconcile();
this.resetReceiveWatch();
@@ -697,7 +851,7 @@ export class HookSession extends EventEmitter {
client.on('loginState', (state) => this.handleLoginState(state));
client.on('error', (error) => {
const msg = errorMessage(error);
this._error = this.runtimeFailure || msg;
this._error = this.runtimeFailure || this.initialConnectionError || msg;
this.log.warn('pipe error: PID=%d err=%s', this.pid, msg);
});
client.on('close', () => {
@@ -728,6 +882,7 @@ export class HookSession extends EventEmitter {
}
private tearDownClient(preserveRuntimeFailure = false): void {
this.cancelConnectAttempt?.();
this.stopLoginReconcile();
this.resetReceiveWatch();
const client = this.client;
@@ -752,19 +907,32 @@ export class HookSession extends EventEmitter {
this.bound = false;
this.connected = false;
this.loggedIn = false;
this.invalidLoginStateReported = false;
this._outboundHealthy = true;
this.resetLoginHint();
}
private handleLoginState(state: QqHookLoginState): void {
if (this.runtimeFailure) {
if (this.disposed || this.runtimeFailure) {
return;
}
const wasLoggedIn = this.loggedIn;
const previousUin = this._uin;
this._uin = state.uin || state.uinNumber.toString();
this.loggedIn = state.loggedIn && isRealUin(this._uin);
const uin = state.uin || state.uinNumber.toString();
const validIdentity = isRealUin(uin);
const invalidLoginState = state.loggedIn && !validIdentity;
if (invalidLoginState && !this.invalidLoginStateReported) {
this.log.warn(
'Login readiness rejected: PID=%d reason=invalid_account_identity',
this.pid,
);
}
this.invalidLoginStateReported = invalidLoginState;
this._uin = validIdentity ? uin : '0';
this.loggedIn = state.loggedIn && validIdentity;
// Login readiness has now been confirmed, so identity probing is done.
if (this.loggedIn) {
@@ -779,19 +947,30 @@ export class HookSession extends EventEmitter {
} else {
this.resetReceiveWatch();
this._outboundHealthy = true;
if (wasLoggedIn) {
this.resetLoginHint();
}
}
// Only the connected/logged-in states are ours to set here; when fully
// down we leave the status the teardown path already settled.
// Load-bearing invariant: `loggedIn ⇒ connected` (login can only be
// observed on a live client, and teardown clears `loggedIn` before
// `connected`), so statusFor lands 'online' here rather than the
// disconnected/connecting branch.
// Login may arrive while another channel is still handshaking; the
// connection attempt revokes that binding if it fails to complete.
if (this.connected || this.loggedIn) {
this.applyStatus(wasLoggedIn, this.loggedIn ? '' : this._error);
}
if (!this.loggedIn || !this.sender) {
if (!this.loggedIn) {
if (wasLoggedIn) {
this.emit('disconnected', true);
}
runWithoutRequestContext(() => this.startLoginReconcile());
return;
}
if (!this.sender) {
return;
}
@@ -838,17 +1017,23 @@ export class HookSession extends EventEmitter {
// reconciliation, but never synthesize online state from the detection.
private startLoginReconcile(): void {
if (this.loginReconcileTimer || this.disposed || this.runtimeFailure) {
if (
this.loginReconcileTimer ||
this.disposed ||
this.runtimeFailure ||
!this.connected ||
this.loggedIn
) {
return;
}
this.log.info('awaiting login: PID=%d', this.pid);
void this.detectLoginOnce(); // immediate — catch already-logged-in fast
this.loginReconcileTimer = setInterval(
() => void this.detectLoginOnce(),
LOGIN_RECONCILE_INTERVAL_MS,
);
this.loginReconcileTimer.unref();
void this.detectLoginOnce();
}
private stopLoginReconcile(): void {
@@ -866,6 +1051,7 @@ export class HookSession extends EventEmitter {
}
const client = this.client;
const identityEpoch = this.loginIdentityEpoch;
if (this.disposed || !client || !this.connected || this.loggedIn || this.runtimeFailure) {
this.stopLoginReconcile();
@@ -884,6 +1070,17 @@ export class HookSession extends EventEmitter {
try {
uin = await this.detectLoginUin(this.pid);
} catch (error) {
if (
this.client !== client ||
this.loginIdentityEpoch !== identityEpoch ||
this.disposed ||
!this.connected ||
this.loggedIn ||
this.runtimeFailure
) {
return;
}
const message = errorMessage(error);
if (this.lastDetectFailure !== message) {
@@ -898,9 +1095,10 @@ export class HookSession extends EventEmitter {
return; // best-effort; the interval retries
}
// A reconnect owns a new client; an older read cannot supply its identity.
// A connection or readiness change invalidates earlier identity work.
if (
this.client !== client ||
this.loginIdentityEpoch !== identityEpoch ||
this.disposed ||
!this.connected ||
this.loggedIn ||
@@ -944,6 +1142,7 @@ export class HookSession extends EventEmitter {
if (
this.client !== client ||
this.loginIdentityEpoch !== identityEpoch ||
this.disposed ||
!this.connected ||
this.loggedIn ||
@@ -956,7 +1155,14 @@ export class HookSession extends EventEmitter {
this.nextLoginIdentityObservationAt =
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
} catch (error) {
if (this.client !== client || this.disposed || this.runtimeFailure) {
if (
this.client !== client ||
this.loginIdentityEpoch !== identityEpoch ||
this.disposed ||
!this.connected ||
this.loggedIn ||
this.runtimeFailure
) {
return;
}
@@ -989,6 +1195,7 @@ export class HookSession extends EventEmitter {
}
private resetLoginHint(): void {
this.loginIdentityEpoch++;
this.acceptedLoginHintUin = '';
this.loginHintAttemptUin = '';
this.loginHintAttempts = 0;
+23 -3
View File
@@ -545,6 +545,7 @@ class FrameReader {
}
export class QqHookClient extends EventEmitter {
private readonly connectingSockets = new Set<net.Socket>();
readonly pid: number;
readonly runtimeDir: string;
readonly defaultAckTimeoutMs: number;
@@ -975,6 +976,12 @@ export class QqHookClient extends EventEmitter {
this.rejectRecvPending(new Error('qq_hook client closed'));
this.rejectLoginWaiters(new Error('qq_hook client closed'));
for (const socket of this.connectingSockets) {
socket.destroy();
}
this.connectingSockets.clear();
if (this.controlSocket) {
this.controlSocket.destroy();
this.controlSocket = null;
@@ -1194,10 +1201,19 @@ export class QqHookClient extends EventEmitter {
): Promise<net.Socket> {
return new Promise((resolve, reject) => {
const socket = net.createConnection(pipeName);
this.connectingSockets.add(socket);
const reader = new FrameReader(onFrame);
const onInitialError = (error: Error) => reject(error);
socket.once('error', onInitialError);
socket.once('connect', () => {
const onInitialClose = () => {
this.connectingSockets.delete(socket);
socket.off('connect', onConnect);
reject(new Error(`${kind} pipe closed before connecting`));
};
const onConnect = () => {
this.connectingSockets.delete(socket);
socket.off('close', onInitialClose);
socket.off('error', onInitialError);
socket.on('data', (chunk) => {
try {
@@ -1217,7 +1233,11 @@ export class QqHookClient extends EventEmitter {
});
});
resolve(socket);
});
};
socket.once('error', onInitialError);
socket.once('close', onInitialClose);
socket.once('connect', onConnect);
});
}
@@ -152,6 +152,43 @@ describe('HookManager.onSessionsChanged', () => {
ctx.manager.dispose();
});
it('publishes an initial timeout and automatically recovers when the channel arrives late', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
const ctx = makeManager({ processes: [4242] });
try {
await ctx.manager.loadProcess(4242);
ctx.onSessionsChanged.mockClear();
await vi.advanceTimersByTimeAsync(60_000);
expect(ctx.onSessionsChanged).toHaveBeenCalled();
expect(await ctx.manager.listProcesses()).toEqual([
expect.objectContaining({
pid: 4242,
status: 'error',
injected: true,
error: expect.stringContaining('首次连接超时'),
}),
]);
ctx.onSessionsChanged.mockClear();
ctx.setLivePipes([4242]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
expect(await ctx.manager.listProcesses()).toEqual([
expect.objectContaining({
pid: 4242,
status: 'loaded',
connected: true,
error: '',
}),
]);
} finally {
ctx.manager.dispose();
vi.useRealTimers();
}
});
it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => {
const ctx = makeManager({ processes: [] });
ctx.onSessionsChanged.mockImplementation(() => {
+619 -1
View File
@@ -1,4 +1,4 @@
import { afterEach, describe, it, expect, vi } from 'vitest';
import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookSession } from '../src/hook-session';
import type { ManualMapHandle } from '../src/injector';
@@ -112,6 +112,7 @@ function makeSession(
detectLoginUin?: (pid: number) => Promise<string | null>;
nativeReadyOnIdentityHint?: boolean;
identityHintFailures?: number;
connectClient?: (client: FakeClient) => Promise<void>;
} = {},
) {
const pid = opts.pid ?? 1234;
@@ -137,6 +138,11 @@ function makeSession(
c.nativeReadyOnIdentityHint = opts.nativeReadyOnIdentityHint ?? false;
c.identityHintFailures = opts.identityHintFailures ?? 0;
if (opts.connectClient) {
c.connectAll = () => opts.connectClient!(c);
}
clients.push(c);
// Cast: FakeClient mirrors only the surface HookSession touches.
return c as unknown as QqHookClient;
@@ -599,6 +605,322 @@ describe('HookSession — load', () => {
});
});
describe('HookSession — initial connection deadline', () => {
const timeoutMs = 60_000;
const sessions: HookSession[] = [];
function setup(opts: Parameters<typeof makeSession>[0] = {}) {
const ctx = makeSession(opts);
sessions.push(ctx.session);
return ctx;
}
beforeEach(() => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
});
afterEach(() => {
for (const session of sessions.splice(0)) {
session.dispose();
}
vi.useRealTimers();
});
it('reports a missing channel without losing the loaded component or clearing the error on refresh', async () => {
const { session } = setup();
const changed = vi.fn();
session.on('status-changed', changed);
await expect(session.load()).resolves.toMatchObject({ status: 'connecting' });
await vi.advanceTimersByTimeAsync(timeoutMs - 1);
expect(session.status).toBe('connecting');
await vi.advanceTimersByTimeAsync(1);
expect(session.toInfo()).toMatchObject({
status: 'error',
injected: true,
connected: false,
error: expect.stringContaining('首次连接超时'),
});
const error = session.error;
expect(changed).toHaveBeenLastCalledWith('error', error);
session.onPipeDown();
await expect(session.refresh()).resolves.toMatchObject({ status: 'error', error });
});
it('unloads with the original handle after a timeout, including a failed unload retry', async () => {
const { session, injector } = setup();
await session.load();
await vi.advanceTimersByTimeAsync(timeoutMs);
expect(session.status).toBe('error');
injector.unload.mockRejectedValueOnce(new Error('unload rejected'));
await expect(session.unload()).resolves.toMatchObject({
status: 'error',
injected: true,
error: 'unload rejected',
});
await expect(session.unload()).resolves.toMatchObject({
status: 'available',
injected: false,
error: '',
});
expect(injector.unload).toHaveBeenNthCalledWith(1, session.pid, DUMMY_HANDLE);
expect(injector.unload).toHaveBeenNthCalledWith(2, session.pid, DUMMY_HANDLE);
await vi.advanceTimersByTimeAsync(timeoutMs);
expect(session.status).toBe('available');
});
it('retries the connection after timeout without loading the component twice', async () => {
const { session, injector, setPipeLive } = setup();
await session.load();
await vi.advanceTimersByTimeAsync(timeoutMs);
expect(session.status).toBe('error');
await expect(session.load()).resolves.toMatchObject({
status: 'connecting',
injected: true,
error: '',
});
await vi.advanceTimersByTimeAsync(timeoutMs - 1);
expect(session.status).toBe('connecting');
setPipeLive(true);
session.onPipeUp();
await flush();
expect(session.toInfo()).toMatchObject({ status: 'loaded', error: '', loggedIn: false });
expect(injector.inject).toHaveBeenCalledOnce();
await vi.advanceTimersByTimeAsync(timeoutMs * 2);
expect(session.status).toBe('loaded');
});
it('can time out again after an explicit retry', async () => {
const { session, injector } = setup();
await session.load();
await vi.advanceTimersByTimeAsync(timeoutMs);
await session.load();
await vi.advanceTimersByTimeAsync(timeoutMs);
expect(session.status).toBe('error');
expect(session.error).toContain('首次连接超时');
expect(injector.inject).toHaveBeenCalledOnce();
});
it('accepts a late channel without a manual retry and retains the timeout across failed handshakes', async () => {
let failConnect = true;
const { session, injector, setPipeLive } = setup({
connectClient: async () => {
if (failConnect) {
throw new Error('connect failed');
}
},
});
await session.load();
await vi.advanceTimersByTimeAsync(timeoutMs);
const error = session.error;
expect(error).toContain('首次连接超时');
setPipeLive(true);
session.onPipeUp();
await flush();
expect(session.toInfo()).toMatchObject({ status: 'error', error });
failConnect = false;
session.onPipeUp();
await flush();
expect(session.toInfo()).toMatchObject({ status: 'loaded', error: '', connected: true });
expect(injector.inject).toHaveBeenCalledOnce();
});
it('bounds a stalled handshake by the remaining initial budget and permits unload before it finishes', async () => {
let finishConnect!: () => void;
const { session, currentClient, injector, setPipeLive } = setup({
connectClient: () =>
new Promise<void>((resolve) => {
finishConnect = resolve;
}),
});
const login = vi.fn();
const disconnected = vi.fn();
session.on('login', login);
session.on('disconnected', disconnected);
await session.load();
await vi.advanceTimersByTimeAsync(timeoutMs - 1000);
setPipeLive(true);
session.onPipeUp();
await flush();
currentClient().fireLogin('10001');
// Login and packets can arrive together before connectAll settles.
// Preserve their ordering, but revoke this binding if the handshake fails.
expect(login).toHaveBeenCalledOnce();
await vi.advanceTimersByTimeAsync(1000);
expect(session.toInfo()).toMatchObject({
status: 'error',
connected: false,
loggedIn: false,
});
expect(session.error).toContain('首次连接超时');
expect(currentClient().isClosed).toBe(true);
expect(disconnected).toHaveBeenCalledExactlyOnceWith(true);
setPipeLive(false);
await expect(session.unload()).resolves.toMatchObject({
status: 'available',
injected: false,
});
expect(injector.unload).toHaveBeenCalledExactlyOnceWith(session.pid, DUMMY_HANDLE);
finishConnect();
await flush();
expect(session.toInfo()).toMatchObject({
status: 'available',
connected: false,
loggedIn: false,
});
expect(login).toHaveBeenCalledOnce();
});
it('coalesces watcher retries so they cannot queue ahead of unload after a stalled handshake', async () => {
const { session, injector, clients } = setup({
connectClient: () => new Promise<void>(() => {}),
});
await session.load();
session.onPipeUp();
await flush();
for (let tick = 0; tick < 40; tick++) {
session.onPipeUp();
}
await vi.advanceTimersByTimeAsync(timeoutMs);
let result: Awaited<ReturnType<HookSession['unload']>> | undefined;
const unloading = session.unload().then((info) => {
result = info;
});
await flush();
expect(result).toMatchObject({ status: 'available', injected: false });
expect(clients).toHaveLength(1);
expect(injector.unload).toHaveBeenCalledExactlyOnceWith(session.pid, DUMMY_HANDLE);
await unloading;
});
it('starts the deadline after loading completes and repeated load calls do not postpone it', async () => {
const { session, injector } = setup();
let finishLoading!: (value: {
method: 'loadModuleManual';
handle: ManualMapHandle;
}) => void;
injector.inject.mockReturnValueOnce(
new Promise((resolve) => {
finishLoading = resolve;
}),
);
const loading = session.load();
await flush();
await vi.advanceTimersByTimeAsync(timeoutMs * 2);
expect(session.status).toBe('loading');
finishLoading({ method: 'loadModuleManual', handle: DUMMY_HANDLE });
await loading;
await vi.advanceTimersByTimeAsync(timeoutMs - 1);
await session.load();
expect(session.status).toBe('connecting');
await vi.advanceTimersByTimeAsync(1);
expect(session.status).toBe('error');
expect(injector.inject).toHaveBeenCalledOnce();
});
it('unloads immediately if a late connection attempt is still handshaking after timeout', async () => {
const { session, currentClient, injector } = setup({
connectClient: () => new Promise<void>(() => {}),
});
await session.load();
await vi.advanceTimersByTimeAsync(timeoutMs);
session.onPipeUp();
await flush();
let result: Awaited<ReturnType<HookSession['unload']>> | undefined;
const unloading = session.unload().then((info) => {
result = info;
});
await flush();
expect(result).toMatchObject({ status: 'available', injected: false });
expect(currentClient().isClosed).toBe(true);
expect(injector.unload).toHaveBeenCalledExactlyOnceWith(session.pid, DUMMY_HANDLE);
expect(vi.getTimerCount()).toBe(0);
await unloading;
});
it('cancels the deadline on unload and gives a new load a full budget', async () => {
const { session, injector } = setup();
await session.load();
await vi.advanceTimersByTimeAsync(timeoutMs - 1);
await session.unload();
await session.load();
await vi.advanceTimersByTimeAsync(1);
expect(session.status).toBe('connecting');
await vi.advanceTimersByTimeAsync(timeoutMs - 1);
expect(session.status).toBe('error');
expect(injector.inject).toHaveBeenCalledTimes(2);
});
it.each(['dispose', 'process-gone'] as const)(
'cancels a pending deadline on %s',
async (event) => {
const { session } = setup();
const changed = vi.fn();
await session.load();
session.on('status-changed', changed);
if (event === 'dispose') {
session.dispose();
} else {
session.notifyProcessGone();
await flush();
}
changed.mockClear();
await vi.advanceTimersByTimeAsync(timeoutMs * 2);
expect(changed).not.toHaveBeenCalled();
expect(session.error).toBe('');
expect(vi.getTimerCount()).toBe(0);
},
);
it('does not let a disposed connection finish or retain its timer', async () => {
let finishConnect!: () => void;
const { session, currentClient } = setup({
pipeLive: true,
connectClient: () =>
new Promise<void>((resolve) => {
finishConnect = resolve;
}),
});
await session.load();
session.onPipeUp();
await flush();
session.dispose();
await flush();
expect(currentClient().isClosed).toBe(true);
expect(vi.getTimerCount()).toBe(0);
finishConnect();
await flush();
expect(session.toInfo()).toMatchObject({ connected: false, loggedIn: false });
});
it('does not use the initial deadline as a login or later disconnection timeout', async () => {
const { session, setPipeLive } = setup({ pipeLive: true });
session.onPipeUp();
await flush();
await vi.advanceTimersByTimeAsync(timeoutMs * 2);
expect(session.toInfo()).toMatchObject({ status: 'loaded', loggedIn: false, error: '' });
setPipeLive(false);
session.onPipeDown();
await flush();
await vi.advanceTimersByTimeAsync(timeoutMs * 2);
expect(session.toInfo()).toMatchObject({ status: 'connecting', error: '' });
});
});
describe('HookSession — pipe up/down → connect lifecycle', () => {
it('onPipeUp after load: client connects → status loaded', async () => {
const ctx = makeSession({ pipeLive: true });
@@ -1157,6 +1479,302 @@ describe('HookSession — packet forwarding', () => {
});
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
it.each([
{ uin: '1700000000000', uinNumber: 1700000000000n },
{ uin: 'not-an-account', uinNumber: 0n },
{ uin: '0', uinNumber: 0n },
{ uin: '', uinNumber: 1700000000000n },
])(
'reconciles a rejected login identity received during connection: $uin',
async (identity) => {
vi.useFakeTimers();
setLogLevel('warn');
const entries: LogEntry[] = [];
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const detectLoginUin = vi.fn(async () => '10001');
const onPacket = vi.fn<PacketSink>();
const state = { loggedIn: true, ...identity };
const ctx = makeSession({
pipeLive: true,
detectLoginUin,
onPacket,
connectClient: async (client) => client.reconcileLoginState(state),
});
const login = vi.fn();
ctx.session.on('login', login);
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
expect(ctx.session.toInfo()).toMatchObject({
connected: true,
loggedIn: false,
status: 'loaded',
uin: '0',
});
expect(login).not.toHaveBeenCalled();
const packet = {
seq: 1,
error: 0,
cmd: 'Test.Message',
uin: '10001',
body: Buffer.alloc(0),
};
ctx.currentClient().firePacket(packet);
expect(onPacket).not.toHaveBeenCalled();
ctx.currentClient().reconcileLoginState(state);
await vi.advanceTimersByTimeAsync(9000);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
expect(
entries
.filter((entry) => entry.scope === 'HookSession' && entry.level === 'warn')
.map((entry) => entry.message),
).toEqual(['Login readiness rejected: PID=1234 reason=invalid_account_identity']);
ctx.currentClient().fireLogin('10001');
ctx.currentClient().firePacket(packet);
expect(login).toHaveBeenCalledOnce();
expect(onPacket).toHaveBeenCalledOnce();
expect(ctx.session.toInfo()).toMatchObject({
loggedIn: true,
status: 'online',
uin: '10001',
});
const detections = detectLoginUin.mock.calls.length;
await vi.advanceTimersByTimeAsync(30_000);
expect(detectLoginUin).toHaveBeenCalledTimes(detections);
} finally {
ctx.session.dispose();
unsubscribe();
vi.useRealTimers();
}
},
);
it('revokes a ready account and starts a fresh identity check when login readiness is lost', async () => {
vi.useFakeTimers();
const ctx = makeSession({ pipeLive: true, detectLoginUin: async () => '10001' });
const login = vi.fn();
const disconnected = vi.fn();
ctx.session.on('login', login);
ctx.session.on('disconnected', disconnected);
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
ctx.currentClient().fireLogin('10001');
expect(login).toHaveBeenCalledOnce();
ctx.currentClient().fireLogin('1700000000000');
ctx.currentClient().fireLogin('1700000000001');
await vi.advanceTimersByTimeAsync(0);
expect(disconnected).toHaveBeenCalledExactlyOnceWith(true);
expect(ctx.session.toInfo()).toMatchObject({
status: 'loaded',
loggedIn: false,
uin: '0',
});
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']);
expect(login).toHaveBeenCalledOnce();
ctx.currentClient().fireLogin('10001');
expect(login).toHaveBeenCalledTimes(2);
expect(ctx.session.status).toBe('online');
} finally {
ctx.session.dispose();
vi.useRealTimers();
}
});
it('does not probe a rejected login identity before a stalled connection times out', async () => {
vi.useFakeTimers();
const handshake = Promise.withResolvers<void>();
const detectLoginUin = vi.fn(async () => '10001');
const ctx = makeSession({ detectLoginUin, connectClient: () => handshake.promise });
const login = vi.fn();
ctx.session.on('login', login);
try {
await ctx.session.load();
ctx.setPipeLive(true);
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
const previous = ctx.currentClient();
previous.fireLogin('1700000000000');
await vi.advanceTimersByTimeAsync(60_000);
expect(ctx.session.toInfo()).toMatchObject({
status: 'error',
connected: false,
loggedIn: false,
});
expect(detectLoginUin).not.toHaveBeenCalled();
expect(previous.isClosed).toBe(true);
expect(vi.getTimerCount()).toBe(0);
previous.fireLogin('10001');
handshake.resolve();
await vi.advanceTimersByTimeAsync(0);
expect(login).not.toHaveBeenCalled();
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(ctx.currentClient()).not.toBe(previous);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
expect(ctx.session.toInfo()).toMatchObject({
status: 'loaded',
connected: true,
loggedIn: false,
});
} finally {
handshake.resolve();
ctx.session.dispose();
vi.useRealTimers();
}
});
it('discards an identity acknowledgement from before login readiness was lost', async () => {
vi.useFakeTimers();
const hint = Promise.withResolvers<void>();
const ctx = makeSession({
pipeLive: true,
detectLoginUin: async () => '10001',
connectClient: async (client) => {
vi.spyOn(client, 'reconcileLoginIdentity').mockImplementationOnce(async (uin) => {
client.loginIdentityHints.push(uin);
await hint.promise;
});
},
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
ctx.currentClient().fireLogin('10001');
ctx.currentClient().fireLogin('1700000000000');
hint.resolve();
await vi.advanceTimersByTimeAsync(3000);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']);
expect(ctx.session.toInfo()).toMatchObject({ status: 'loaded', loggedIn: false });
} finally {
hint.resolve();
ctx.session.dispose();
vi.useRealTimers();
}
});
it('discards an account observation from before login readiness was lost', async () => {
vi.useFakeTimers();
const observation = Promise.withResolvers<string | null>();
const detectLoginUin = vi.fn<() => Promise<string | null>>().mockResolvedValue('20002');
detectLoginUin.mockReturnValueOnce(observation.promise);
const ctx = makeSession({ pipeLive: true, detectLoginUin });
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
ctx.currentClient().fireLogin('10001');
ctx.currentClient().fireLogin('1700000000000');
observation.resolve('10001');
await vi.advanceTimersByTimeAsync(0);
expect(ctx.currentClient().loginIdentityHints).toEqual([]);
await vi.advanceTimersByTimeAsync(3000);
expect(ctx.currentClient().loginIdentityHints).toEqual(['20002']);
} finally {
observation.resolve(null);
ctx.session.dispose();
vi.useRealTimers();
}
});
it.each(['observation', 'hint'] as const)(
'ignores a late %s failure after login readiness is confirmed',
async (phase) => {
vi.useFakeTimers();
setLogLevel('trace');
const entries: LogEntry[] = [];
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const pending = Promise.withResolvers<void>();
const detectLoginUin = vi.fn(async () => {
if (phase === 'observation') {
await pending.promise;
}
return '10001';
});
const ctx = makeSession({
pipeLive: true,
detectLoginUin,
connectClient: async (client) => {
if (phase === 'hint') {
vi.spyOn(client, 'reconcileLoginIdentity').mockImplementationOnce(
async (uin) => {
client.loginIdentityHints.push(uin);
await pending.promise;
},
);
}
},
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(detectLoginUin).toHaveBeenCalledOnce();
expect(ctx.currentClient().loginIdentityHints).toEqual(
phase === 'hint' ? ['10001'] : [],
);
ctx.currentClient().fireLogin('10001');
entries.length = 0;
pending.reject(new Error('expired identity request'));
await vi.advanceTimersByTimeAsync(30_000);
expect(
entries.some((entry) => entry.message.includes('expired identity request')),
).toBe(false);
expect(detectLoginUin).toHaveBeenCalledOnce();
expect(ctx.session.toInfo()).toMatchObject({
status: 'online',
loggedIn: true,
uin: '10001',
});
} finally {
pending.resolve();
ctx.session.dispose();
unsubscribe();
vi.useRealTimers();
}
},
);
it('clears the login check timer when identity detection disposes the session synchronously', async () => {
vi.useFakeTimers();
const detectLoginUin = vi.fn<() => Promise<string | null>>();
const ctx = makeSession({ pipeLive: true, detectLoginUin });
detectLoginUin.mockImplementation(async () => {
ctx.session.dispose();
return null;
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(ctx.session.isDisposed).toBe(true);
expect(vi.getTimerCount()).toBe(0);
} finally {
ctx.session.dispose();
vi.useRealTimers();
}
});
it('discards an identity read started before a pipe reconnect', async () => {
const detection = Promise.withResolvers<string | null>();
const ctx = makeSession({ pipeLive: true, detectLoginUin: () => detection.promise });
@@ -13,6 +13,7 @@ import {
} from '@snowluma/common/logger';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CLIENT_MESSAGE_RECEIPT_CMD } from '@snowluma/common/protocol-types';
import { HookSession } from '../src/hook-session';
import {
HEADER_SIZE,
listLiveLinuxPipePids,
@@ -122,6 +123,73 @@ function traceMessages(entries: LogEntry[]): string[] {
.map((entry) => entry.message);
}
describe('initial connection timeout cleanup', () => {
it.each(['socket', 'control-hello', 'recv-hello'] as const)(
'closes a stalled %s connection and allows unloading',
async (phase) => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
const sockets: net.Socket[] = [];
const connection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
const socket = new Duplex({
read() {},
write(_chunk, _encoding, callback) {
callback();
},
}) as net.Socket;
sockets.push(socket);
const control = sockets.length === 1;
if (phase !== 'socket') {
queueMicrotask(() => {
socket.emit('connect');
if (control && phase === 'recv-hello') {
queueMicrotask(() =>
socket.emit('data', pipeFrame({ op: PipeOp.hello })),
);
}
});
}
return socket;
}) as typeof net.createConnection);
const handle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const unload = vi.fn(async () => {});
const session = new HookSession(778905, {
injector: {
inject: async () => ({ method: 'loadModuleManual', handle }),
unload,
},
makeClient: (pid) => new QqHookClient(pid),
pipeWatcher: { isPipeLive: () => false },
detectLoginUin: async () => null,
});
try {
await session.load();
session.onPipeUp();
await new Promise<void>((resolve) => setImmediate(resolve));
expect(sockets).toHaveLength(phase === 'recv-hello' ? 2 : 1);
await vi.advanceTimersByTimeAsync(60_000);
expect(session.toInfo()).toMatchObject({ status: 'error', injected: true });
expect(session.error).toContain('首次连接超时');
expect(sockets.every((socket) => socket.destroyed)).toBe(true);
await expect(session.unload()).resolves.toMatchObject({ status: 'available' });
expect(unload).toHaveBeenCalledExactlyOnceWith(session.pid, handle);
} finally {
session.dispose();
for (const socket of sockets) {
socket.destroy();
}
connection.mockRestore();
vi.useRealTimers();
}
},
);
});
describe('runtime initialization failures', () => {
const failureFrame = pipeFrame({
op: PipeOp.error,
+40
View File
@@ -0,0 +1,40 @@
// pnpm --filter @snowluma/common exec vitest bench --run bench/logger.bench.ts
import { bench, describe, vi } from 'vitest';
vi.stubEnv('SNOWLUMA_LOG_LEVEL', 'trace');
vi.stubEnv('SNOWLUMA_LOG_FILE', '0');
vi.stubEnv('SNOWLUMA_LOG_FILE_LEVEL', 'debug');
vi.stubEnv('SNOWLUMA_TRACE_BUFFER', '5000');
const { createLogger, getLogSnapshot, getRecentLogs, setLogLevel } = await import('../src/logger');
const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true);
const log = createLogger('Benchmark');
for (let i = 0; i < 5000; i += 1) {
log.trace('trace %d', i);
if (i % 5 === 0) {
log.info('normal %d', i);
}
}
stdout.mockRestore();
describe('6,000 retained records', () => {
bench('recent 30', () => {
getRecentLogs(30);
});
bench('recent 300', () => {
getRecentLogs(300);
});
bench('complete export', () => {
getLogSnapshot();
});
});
setLogLevel('info');
describe('file-only debug records with disk disabled', () => {
bench('format and route debug', () => {
log.debug('packet command=%s bytes=%d', 'Example.Service', 1024);
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "2.3.0",
"version": "2.4.2",
"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).",
+33 -18
View File
@@ -82,33 +82,48 @@ function skipEscSequence(line: string, start: number): number {
* invisible payload into persisted or downloaded logs.
*/
export function sanitizeLogLine(line: string): string {
let plain = '';
const parts: string[] = [];
let start = 0;
for (let i = 0; i < line.length;) {
const code = line.charCodeAt(i);
let next: number;
if (code === ESC) {
i = skipEscSequence(line, i + 1);
continue;
}
if (code === C1_CSI) {
i = skipCsi(line, i + 1);
continue;
}
if (code === C1_OSC || C1_STRING_STARTERS.has(code)) {
i = skipControlString(line, i + 1, code === C1_OSC);
continue;
}
if ((code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f)) {
next = skipEscSequence(line, i + 1);
} else if (code === C1_CSI) {
next = skipCsi(line, i + 1);
} else if (code === C1_OSC || C1_STRING_STARTERS.has(code)) {
next = skipControlString(line, i + 1, code === C1_OSC);
} else if (
(code < 0x20 && code !== 0x09 && code !== 0x0a) ||
(code >= 0x7f && code <= 0x9f)
) {
next = i + 1;
} else {
i += 1;
continue;
}
plain += line[i];
i += 1;
parts.push(line.slice(start, i));
start = next;
i = next;
}
if (start === 0) {
return line;
}
// Join contiguous spans once. Appending each character creates a retained
// V8 cons-string node per character in the in-memory log rings.
parts.push(line.slice(start));
const plain = parts.join('');
// A single visible span can remain a slice of the original input after join.
// Copy when that would retain more discarded text than visible text. Splitting
// into UTF-16 code units preserves unpaired surrogates and works in browsers.
if (plain.length > 0 && plain.length < line.length / 2) {
return plain.split('').join('');
}
return plain;
+43 -27
View File
@@ -97,20 +97,13 @@ class RingBuffer<T> {
this.start = (this.start + 1) % this.cap;
} // full → overwrite oldest
}
/** Most recent `n` items, oldest→newest. */
recent(n: number): T[] {
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
const out: T[] = new Array<T>(take);
const first = this.start + (this.count - take);
for (let i = 0; i < take; i += 1) {
out[i] = this.buf[(first + i) % this.cap]!;
/** Read from newest to oldest without copying the retained buffer. */
newest(offset: number): T | undefined {
if (offset >= this.count) {
return undefined;
}
return out;
}
toArray(): T[] {
return this.recent(this.count);
return this.buf[(this.start + this.count - 1 - offset) % this.cap];
}
get size(): number {
return this.count;
@@ -282,18 +275,22 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
const formattedMessage = format(...realArgs);
const message = level === 'trace' ? formattedMessage : redactLogMessage(formattedMessage);
const line = render(level, options, message, reqId);
const entry: LogEntry = {
id: nextLogId++,
time: new Date().toISOString(),
level,
scope: options.scope,
...(options.uin !== undefined ? { uin: options.uin } : {}),
...(reqId !== undefined ? { req: reqId } : {}),
message,
line: sanitizeLogLine(line),
};
const id = nextLogId++;
if (passesConsole) {
// File-only records are sanitized by the transport and need no memory
// entry, ISO timestamp, or second sanitized copy of the rendered line.
const entry: LogEntry = {
id,
time: new Date().toISOString(),
level,
scope: options.scope,
...(options.uin !== undefined ? { uin: options.uin } : {}),
...(reqId !== undefined ? { req: reqId } : {}),
message,
line: sanitizeLogLine(line),
};
// Trace gets its own ring so its volume never evicts the normal log buffer.
(level === 'trace' ? traceRing : logRing).push(entry);
@@ -337,10 +334,28 @@ export function closeLogger(): Promise<void> {
return getFileTransport().close();
}
function mergeLogRings(): LogEntry[] {
return traceRing.size > 0
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
: logRing.toArray();
function mergeLogRings(limit = logRing.size + traceRing.size): LogEntry[] {
const take = Math.min(limit, logRing.size + traceRing.size);
const entries = new Array<LogEntry>(take);
let normalOffset = 0;
let traceOffset = 0;
// Both rings already follow increasing IDs. Merge backwards so a small
// WebUI request visits only the requested tail, even with a large TRACE ring.
for (let i = take - 1; i >= 0; i -= 1) {
const normal = logRing.newest(normalOffset);
const trace = traceRing.newest(traceOffset);
if (normal && (!trace || normal.id > trace.id)) {
entries[i] = normal;
normalOffset += 1;
} else {
entries[i] = trace!;
traceOffset += 1;
}
}
return entries;
}
export function getLogSnapshot(): LogEntry[] {
@@ -349,7 +364,8 @@ export function getLogSnapshot(): LogEntry[] {
export function getRecentLogs(limit = 300): LogEntry[] {
const n = Math.max(1, Math.trunc(limit));
return mergeLogRings().slice(-n);
// Array.slice(-NaN) previously returned the full snapshot.
return mergeLogRings(Number.isNaN(n) ? undefined : n);
}
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
+68 -5
View File
@@ -1,7 +1,7 @@
/** TTL caching and request deduplication to limit repeated upstream requests. */
export interface SingleFlightCacheOptions<K, V> {
/** Freshness window in ms. A cached entry older than this is reloaded. */
/** Freshness window in ms. Expired values are released even while idle. */
ttlMs: number;
/** Load the value for a key. Rejections propagate and are never cached. */
load: (key: K) => Promise<V>;
@@ -22,6 +22,8 @@ export class SingleFlightCache<K, V> {
private readonly now: () => number;
private readonly fresh = new Map<K, { at: number; value: V }>();
private readonly inflight = new Map<K, Promise<V>>();
private expiryTimer: ReturnType<typeof setTimeout> | undefined;
private disposed = false;
constructor(opts: SingleFlightCacheOptions<K, V>) {
this.ttlMs = opts.ttlMs;
@@ -30,6 +32,11 @@ export class SingleFlightCache<K, V> {
this.now = opts.now ?? Date.now;
}
/** Number of retained values; pending loads are not counted. */
get size(): number {
return this.fresh.size;
}
/**
* Get the value for `key`.
*
@@ -41,10 +48,17 @@ export class SingleFlightCache<K, V> {
* rather than starting a second one.
*/
get(key: K, opts: { force?: boolean } = {}): Promise<V> {
if (!opts.force) {
const hit = this.fresh.get(key);
if (this.disposed) {
return Promise.reject(new Error('SingleFlightCache is disposed'));
}
if (hit && this.now() - hit.at < this.ttlMs) {
const hit = this.fresh.get(key);
if (hit) {
if (this.now() - hit.at >= this.ttlMs) {
this.fresh.delete(key);
this.cancelExpiryIfEmpty();
} else if (!opts.force) {
return Promise.resolve(hit.value);
}
}
@@ -58,8 +72,11 @@ export class SingleFlightCache<K, V> {
const load = async (): Promise<V> => {
const value = await this.load(key);
if (this.inflight.get(key) === task && this.shouldCache(value)) {
if (this.inflight.get(key) === task && this.ttlMs > 0 && this.shouldCache(value)) {
// Keep insertion order aligned with expiry, including refreshes.
this.fresh.delete(key);
this.fresh.set(key, { at: this.now(), value });
this.scheduleExpiry();
}
return value;
@@ -78,12 +95,58 @@ export class SingleFlightCache<K, V> {
invalidate(key: K): void {
this.fresh.delete(key);
this.inflight.delete(key);
this.cancelExpiryIfEmpty();
}
/** Detach all entries and pending loads without aborting existing callers. */
clear(): void {
this.fresh.clear();
this.inflight.clear();
this.cancelExpiryIfEmpty();
}
/** Release this owner's cache permanently; pending callers still settle. */
dispose(): void {
this.disposed = true;
this.clear();
}
private cancelExpiryIfEmpty(): void {
if (this.fresh.size === 0 && this.expiryTimer !== undefined) {
clearTimeout(this.expiryTimer);
this.expiryTimer = undefined;
}
}
private scheduleExpiry(): void {
if (this.expiryTimer !== undefined || !Number.isFinite(this.ttlMs)) {
return;
}
const oldest = this.fresh.values().next().value;
if (!oldest) {
return;
}
// One unref'ed timer per cache, not one closure/timer per cached roster.
// Clamp long TTLs to Node's timer range rather than overflowing to 1ms.
const delay = Math.max(1, Math.min(2 ** 31 - 1, oldest.at + this.ttlMs - this.now()));
this.expiryTimer = setTimeout(() => {
this.expiryTimer = undefined;
const now = this.now();
for (const [key, entry] of this.fresh) {
if (now - entry.at < this.ttlMs) {
break;
}
this.fresh.delete(key);
}
this.scheduleExpiry();
}, delay);
this.expiryTimer.unref();
}
}
@@ -1,4 +1,5 @@
import { describe, expect, it } from 'vitest';
import { execFileSync } from 'node:child_process';
import { sanitizeLogLine } from '../src/log-sanitize';
describe('sanitizeLogLine', () => {
@@ -23,4 +24,64 @@ describe('sanitizeLogLine', () => {
it('does not leak unterminated terminal strings', () => {
expect(sanitizeLogLine('visible\x1b]8;;https://example.com')).toBe('visible');
});
it('preserves long Unicode records and adjacent visible spans', () => {
const body = '消息 🌌 e\u0301\tpacket=0011aabb\n'.repeat(1000);
expect(sanitizeLogLine(body)).toBe(body);
expect(sanitizeLogLine(`\x1b[32m${body}\x1b[0m\x00tail\x1b`)).toBe(`${body}tail`);
});
it.each(['\x1bP', '\x1bX', '\x1b^', '\x1b_', '\u0090', '\u0098', '\u009e', '\u009f'])(
'removes %j control strings between visible spans',
(opener) => {
expect(sanitizeLogLine(`before${opener}private\u009cafter`)).toBe('beforeafter');
expect(sanitizeLogLine(`before${opener}private\x1b\\after`)).toBe('beforeafter');
expect(sanitizeLogLine(`before${opener}private`)).toBe('before');
},
);
it('handles consecutive controls and records consisting only of controls', () => {
expect(sanitizeLogLine('\x00\x1b[31m\u009b0m\r\u007f')).toBe('');
expect(sanitizeLogLine('a\x00\x1b[31m\u009b0m\r\u007fb')).toBe('ab');
expect(sanitizeLogLine('')).toBe('');
});
it('preserves every visible UTF-16 code unit when removing a large hidden payload', () => {
const visible = 'visible 🌌 e\u0301\ud800x\udc00';
expect(sanitizeLogLine(`${visible}\x1b]${'hidden'.repeat(1000)}`)).toBe(visible);
});
it('does not retain discarded control-string payloads through a short visible span', () => {
const moduleUrl = new URL('../src/log-sanitize.ts', import.meta.url).href;
const output = execFileSync(
process.execPath,
[
'--expose-gc',
'--input-type=module',
'-e',
`
import { setImmediate } from 'node:timers/promises';
import { sanitizeLogLine } from ${JSON.stringify(moduleUrl)};
async function used() {
await setImmediate();
global.gc();
global.gc();
return process.memoryUsage().heapUsed;
}
function record(i) {
return sanitizeLogLine('visible record ' + i + '\\x1b]' + 'x'.repeat(1024 * 1024));
}
const before = await used();
const records = Array.from({ length: 16 }, (_, i) => record(i));
const retained = (await used()) - before;
console.log(JSON.stringify({ retained, records }));
`,
],
{ encoding: 'utf8', timeout: 10_000 },
);
const result = JSON.parse(output);
expect(result.records).toEqual(Array.from({ length: 16 }, (_, i) => `visible record ${i}`));
// Leave ample GC/runtime overhead while rejecting retention of the 16 MiB input.
expect(result.retained).toBeLessThan(4 * 1024 * 1024);
});
});
@@ -0,0 +1,99 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
const { fileWrite } = vi.hoisted(() => ({ fileWrite: vi.fn() }));
vi.mock('../src/log-file-transport', () => ({
getFileTransport: () => ({ write: fileWrite, close: async () => {} }),
}));
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
vi.resetModules();
fileWrite.mockClear();
});
async function setup() {
vi.stubEnv('SNOWLUMA_LOG_LEVEL', 'trace');
vi.stubEnv('SNOWLUMA_LOG_FILE_LEVEL', 'error');
vi.stubEnv('SNOWLUMA_TRACE_BUFFER', '100');
vi.spyOn(process.stdout, 'write').mockReturnValue(true);
vi.spyOn(process.stderr, 'write').mockReturnValue(true);
const logger = await import('../src/logger');
return { ...logger, log: logger.createLogger('Snapshot') };
}
describe('retained log snapshots', () => {
it('returns empty snapshots before any record has been emitted', async () => {
const logger = await setup();
expect(logger.getRecentLogs()).toEqual([]);
expect(logger.getLogSnapshot()).toEqual([]);
});
it('merges wrapped rings in emission order and returns only the requested tail', async () => {
const logger = await setup();
const emitted: import('../src/logger').LogEntry[] = [];
const unsubscribe = logger.subscribeLogs((entry) => emitted.push(entry));
for (let i = 0; i < 1100; i += 1) {
logger.log.info('normal %d', i);
logger.log.trace('trace %d', i);
}
unsubscribe();
const normal = emitted.filter((entry) => entry.level !== 'trace').slice(-1000);
const trace = emitted.filter((entry) => entry.level === 'trace').slice(-100);
const expected = [...normal, ...trace].sort((a, b) => a.id - b.id);
expect(logger.getLogSnapshot()).toEqual(expected);
for (const limit of [1, 2, 30, 300, 1000, 1100, 2000, 0, -1, 2.9, NaN, Infinity]) {
expect(logger.getRecentLogs(limit)).toEqual(
expected.slice(-Math.max(1, Math.trunc(limit))),
);
}
expect(logger.getRecentLogs()).toEqual(expected.slice(-300));
const snapshot = logger.getRecentLogs(5);
snapshot.pop();
expect(logger.getRecentLogs(5)).toEqual(expected.slice(-5));
});
it.each(['info', 'trace'] as const)(
'reads a tail when only the %s ring has records',
async (level) => {
const logger = await setup();
logger.log[level]('first');
logger.log[level]('second');
expect(logger.getRecentLogs(1).map((entry) => entry.message)).toEqual(['second']);
expect(logger.getLogSnapshot().map((entry) => entry.message)).toEqual([
'first',
'second',
]);
},
);
it('preserves ID gaps and file routing without publishing file-only entries', async () => {
const logger = await setup();
vi.stubEnv('SNOWLUMA_LOG_FILE_LEVEL', 'debug');
vi.resetModules();
const fresh = await import('../src/logger');
fresh.setLogLevel('info');
const entries: import('../src/logger').LogEntry[] = [];
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
const log = fresh.createLogger('FileOnly').child({ uin: 10001 });
log.info('before');
fresh.runWithRequestId(42, () => log.debug('password=secret file-only\x07'));
log.info('after');
unsubscribe();
expect(entries.map((entry) => entry.message)).toEqual(['before', 'after']);
expect(entries[1]!.id).toBe(entries[0]!.id + 2);
expect(fresh.getLogSnapshot()).toEqual(entries);
expect(fileWrite).toHaveBeenCalledWith(
expect.stringMatching(/\[req#42\] password=\*\*\* file-only/),
10001,
);
expect(process.stdout.write).toHaveBeenCalledTimes(2);
expect(logger.getLogSnapshot()).toEqual([]);
});
});
@@ -1,4 +1,4 @@
import { describe, it, expect, vi } from 'vitest';
import { afterEach, describe, it, expect, vi } from 'vitest';
import { createSingleFlightCache } from '../src/single-flight-cache';
/** A promise whose resolve/reject is exposed, for driving single-flight races. */
@@ -13,6 +13,129 @@ function deferred<T>() {
}
describe('SingleFlightCache', () => {
afterEach(() => {
vi.useRealTimers();
});
it('disposes retained values and rejects new reads without restarting loads or timers', async () => {
vi.useFakeTimers();
const load = vi.fn(async (key: string) => ({ key }));
const cache = createSingleFlightCache({ ttlMs: 300_000, load });
await cache.get('first');
await cache.get('second');
expect(vi.getTimerCount()).toBe(1);
cache.dispose();
cache.dispose();
cache.clear();
expect(cache.size).toBe(0);
expect(vi.getTimerCount()).toBe(0);
await expect(cache.get('first')).rejects.toThrow('disposed');
await expect(cache.get('new', { force: true })).rejects.toThrow('disposed');
expect(load).toHaveBeenCalledTimes(2);
});
it.each(['resolve', 'reject'] as const)(
'preserves a pending %s after disposal without retaining the result',
async (outcome) => {
vi.useFakeTimers();
const pending = deferred<string>();
const cache = createSingleFlightCache({ ttlMs: 300_000, load: () => pending.promise });
const first = cache.get('key');
expect(cache.get('key')).toBe(first);
cache.dispose();
if (outcome === 'resolve') {
pending.resolve('late value');
await expect(first).resolves.toBe('late value');
} else {
pending.reject(new Error('late failure'));
await expect(first).rejects.toThrow('late failure');
}
expect(cache.size).toBe(0);
expect(vi.getTimerCount()).toBe(0);
},
);
it('releases expired values while idle without expiring newer values early', async () => {
vi.useFakeTimers();
const load = vi.fn(async (key: string) => ({ key }));
const cache = createSingleFlightCache({ ttlMs: 1000, load });
await cache.get('old');
await vi.advanceTimersByTimeAsync(500);
const newer = await cache.get('new');
expect(cache.size).toBe(2);
await vi.advanceTimersByTimeAsync(500);
expect(cache.size).toBe(1);
expect(await cache.get('new')).toBe(newer);
expect(load).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(500);
expect(cache.size).toBe(0);
expect(vi.getTimerCount()).toBe(0);
});
it('keeps a refreshed entry until its new deadline and expires other keys', async () => {
vi.useFakeTimers();
const cache = createSingleFlightCache({ ttlMs: 1000, load: async (key: string) => key });
await cache.get('refreshed');
await cache.get('old');
await vi.advanceTimersByTimeAsync(500);
await cache.get('refreshed', { force: true });
await vi.advanceTimersByTimeAsync(500);
expect(cache.size).toBe(1);
await vi.advanceTimersByTimeAsync(500);
expect(cache.size).toBe(0);
});
it.each(['invalidate', 'clear'] as const)(
'%s cancels idle cleanup when the last value is removed',
async (operation) => {
vi.useFakeTimers();
const cache = createSingleFlightCache({ ttlMs: 1000, load: async () => 'value' });
await cache.get('key');
expect(vi.getTimerCount()).toBe(1);
cache[operation]('key');
expect(cache.size).toBe(0);
expect(vi.getTimerCount()).toBe(0);
await cache.get('key');
await vi.advanceTimersByTimeAsync(1000);
expect(cache.size).toBe(0);
},
);
it('does not let expiration detach a pending refresh', async () => {
vi.useFakeTimers();
const pending = deferred<string>();
const load = vi.fn().mockResolvedValueOnce('old').mockReturnValue(pending.promise);
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
await cache.get('key');
const refresh = cache.get('key', { force: true });
await vi.advanceTimersByTimeAsync(1000);
expect(cache.size).toBe(0);
expect(cache.get('key')).toBe(refresh);
pending.resolve('new');
await expect(refresh).resolves.toBe('new');
expect(cache.size).toBe(1);
expect(load).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(1000);
expect(cache.size).toBe(0);
});
it('does not retain values when caching is disabled by a zero TTL', async () => {
vi.useFakeTimers();
const cache = createSingleFlightCache({ ttlMs: 0, load: async () => 'value' });
await expect(cache.get('key')).resolves.toBe('value');
expect(cache.size).toBe(0);
expect(vi.getTimerCount()).toBe(0);
});
it.each(['invalidate', 'clear'] as const)(
'%s detaches pending loads from the cache',
async (operation) => {
+2 -3
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "2.3.0",
"version": "2.4.2",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -53,8 +53,7 @@
"tar": "^7.5.22"
},
"devDependencies": {
"@hono/node-server": "^1.19.15",
"@rollup/plugin-node-resolve": "^16.0.3",
"@hono/node-server": "^2.1.4",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"hono": "^4.13.11",
+145 -63
View File
@@ -1,4 +1,5 @@
import { GroupInviteTracker } from '@snowluma/protocol/group-invite-tracker';
import { groupRequestSubType } from '@snowluma/protocol/qq-info';
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
import {
FetchFriendListPage,
@@ -11,7 +12,8 @@ import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/conta
import {
FetchGroupRequests,
FetchGroupRequestsByUid,
groupRequestOperationType,
groupRequestNotifyType,
type DecodedGroupRequest,
} from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
import {
FetchRobotUinRanges,
@@ -43,6 +45,7 @@ import type {
FriendInfo,
GroupMemberInfo,
GroupRequestInfo,
PublicProfileFields,
QQGroupInfo,
UserProfileInfo,
} from '@snowluma/protocol/qq-info';
@@ -77,22 +80,53 @@ export function isRobotUin(uin: number, ranges: readonly RobotUinRange[]): boole
);
}
function normalizeGroupRequestSequence(
rawSequence: bigint | number | undefined,
function groupRequestMetadata(
raw: Pick<
DecodedGroupRequest,
'sequence' | 'state' | 'eventType' | 'comment' | 'operateTransInfo'
>,
groupId: number,
): number {
const sequence = Number(rawSequence ?? 0);
filtered: boolean,
) {
const sequence = Number(raw.sequence ?? 0);
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
throw new Error(
`invalid group-request sequence: group=${groupId} sequence=${String(rawSequence ?? 0)}`,
`invalid group-request sequence: group=${groupId} sequence=${String(raw.sequence ?? 0)}`,
);
}
return sequence;
const eventType = raw.eventType ?? 0;
const notifyType = groupRequestNotifyType(eventType);
if (notifyType === undefined) {
log.warn(
'unsupported group-request wire type: group=%d sequence=%d type=%d',
groupId,
sequence,
eventType,
);
}
return {
sequence,
state: raw.state ?? 0,
eventType,
notifyType,
comment: raw.comment ?? '',
filtered,
operateTransInfo: raw.operateTransInfo?.length ? raw.operateTransInfo : undefined,
};
}
const MEMBER_LIST_TTL_MS = 60_000;
const FRIEND_PROFILE_TTL_MS = 5 * 60_000;
const FRIEND_PROFILE_CONCURRENCY = 4;
export interface FriendListOptions {
/** Explicitly query profiles; ordinary roster refreshes never fan out. */
withProfile?: boolean;
}
export class ContactsApi {
/**
@@ -111,9 +145,24 @@ export class ContactsApi {
});
private robotUinRangesPromise_: Promise<RobotUinRangeSnapshot> | null = null;
readonly groupInvites = new GroupInviteTracker();
private friendRosterGeneration = 0;
private rememberedFriendRosterGeneration = 0;
private activeProfiles = 0;
private readonly profileWaiters: (() => void)[] = [];
private readonly friendProfiles: SingleFlightCache<number, PublicProfileFields> =
createSingleFlightCache({
ttlMs: FRIEND_PROFILE_TTL_MS,
load: (uin) => this.loadFriendProfile(uin),
});
constructor(private readonly ctx: BridgeContext) {}
dispose(): void {
// Late roster responses must not start new profile loads after shutdown.
this.memberListCache.dispose();
this.friendProfiles.dispose();
}
private fetchRobotUinRanges(groupId: number): Promise<RobotUinRangeSnapshot> {
if (this.robotUinRangesPromise_) {
return this.robotUinRangesPromise_;
@@ -176,7 +225,73 @@ export class ContactsApi {
return SendTuwenArk.invoke(this.ctx, params);
}
private async fetchFriendRoster(): Promise<FriendRoster> {
private async loadFriendProfile(uin: number): Promise<PublicProfileFields> {
if (this.activeProfiles >= FRIEND_PROFILE_CONCURRENCY) {
await new Promise<void>((resolve) => this.profileWaiters.push(resolve));
} else {
this.activeProfiles++;
}
try {
const profile = await this.fetchUserProfile(uin);
return profile.profile ?? {};
} catch (cause) {
log.warn(
'friend profile query failed: user=%d error=%s',
uin,
cause instanceof Error ? cause.message : String(cause),
);
throw new Error(`friend profile query failed for ${uin}`, { cause });
} finally {
const next = this.profileWaiters.shift();
if (next) {
next();
} else {
this.activeProfiles--;
}
}
}
private async enrichFriendProfiles(entries: FriendListPageEntry[]): Promise<void> {
const started = Date.now();
for (let offset = 0; offset < entries.length; offset += FRIEND_PROFILE_CONCURRENCY) {
const batch = entries.slice(offset, offset + FRIEND_PROFILE_CONCURRENCY);
const results = await Promise.allSettled(
batch.map(async ({ friend }) => {
const extra = await this.friendProfiles.get(friend.uin);
friend.profile = { ...structuredClone(extra), ...friend.profile };
}),
);
const errors = results.filter(
(result): result is PromiseRejectedResult => result.status === 'rejected',
);
if (errors.length > 0) {
log.warn(
'friend profile enrichment failed: batch=%d failures=%d elapsedMs=%d',
offset,
errors.length,
Date.now() - started,
);
throw new AggregateError(
errors.map((result) => result.reason),
'friend profile enrichment failed',
);
}
}
log.debug(
'friend profiles loaded: friends=%d elapsedMs=%d',
entries.length,
Date.now() - started,
);
}
private async fetchFriendRoster(options: FriendListOptions = {}): Promise<FriendRoster> {
const generation = ++this.friendRosterGeneration;
const entries: FriendListPageEntry[] = [];
const categories = new Map<number, FriendListPageCategory>();
const seenCookies = new Set<string>();
@@ -206,18 +321,25 @@ export class ContactsApi {
cookie = next;
}
const friends = entries.map((entry) => entry.friend);
this.ctx.identity.rememberFriends(friends);
if (options.withProfile) {
await this.enrichFriendProfiles(entries);
}
if (generation > this.rememberedFriendRosterGeneration) {
this.ctx.identity.rememberFriends(entries.map((entry) => entry.friend));
this.rememberedFriendRosterGeneration = generation;
}
return { entries, categories: [...categories.values()] };
}
async fetchFriendList(): Promise<FriendInfo[]> {
const roster = await this.fetchFriendRoster();
async fetchFriendList(options: FriendListOptions = {}): Promise<FriendInfo[]> {
const roster = await this.fetchFriendRoster(options);
return roster.entries.map((entry) => entry.friend);
}
async fetchFriendCategories(): Promise<FriendCategoryInfo[]> {
const roster = await this.fetchFriendRoster();
async fetchFriendCategories(options: FriendListOptions = {}): Promise<FriendCategoryInfo[]> {
const roster = await this.fetchFriendRoster(options);
const buckets = new Map(
roster.categories.map((category) => [category.categoryId, [] as FriendInfo[]]),
);
@@ -459,18 +581,6 @@ export class ContactsApi {
this.ctx.identity.findUidByUin(operatorUin, groupId) ||
this.ctx.identity.findUidByUin(operatorUin) ||
'';
const notifyType = raw.eventType ?? 0;
const operationType = groupRequestOperationType(notifyType);
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
if (operationType === null) {
log.warn(
'unsupported group-request notification type: group=%d sequence=%s type=%d',
groupId,
String(raw.sequence ?? 0n),
notifyType,
);
}
requests.push({
groupId,
@@ -496,16 +606,7 @@ export class ContactsApi {
this.ctx.identity.findUinByUid(operatorUid) ||
0,
operatorName: raw.operatorUser?.name ?? '',
sequence,
state: raw.state ?? 0,
notifyType,
eventType: operationType ?? 0,
comment: raw.comment ?? '',
filtered,
operateTransInfo:
raw.operateTransInfo && raw.operateTransInfo.length > 0
? raw.operateTransInfo
: undefined,
...groupRequestMetadata(raw, groupId, filtered),
});
}
@@ -529,18 +630,6 @@ export class ContactsApi {
const targetUid = raw.target?.uid ?? '';
const invitorUid = raw.invitor?.uid ?? '';
const operatorUid = raw.operatorUser?.uid ?? '';
const notifyType = raw.eventType ?? 0;
const operationType = groupRequestOperationType(notifyType);
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
if (operationType === null) {
log.warn(
'unsupported group-request notification type: group=%d sequence=%s type=%d',
groupId,
String(raw.sequence ?? 0n),
notifyType,
);
}
requests.push({
groupId,
@@ -563,16 +652,7 @@ export class ContactsApi {
this.ctx.identity.findUinByUid(operatorUid) ??
0,
operatorName: raw.operatorUser?.name ?? '',
sequence,
state: raw.state ?? 0,
notifyType,
eventType: operationType ?? 0,
comment: raw.comment ?? '',
filtered,
operateTransInfo:
raw.operateTransInfo && raw.operateTransInfo.length > 0
? raw.operateTransInfo
: undefined,
...groupRequestMetadata(raw, groupId, filtered),
});
}
@@ -601,15 +681,17 @@ export class ContactsApi {
return (
[...main.value, ...filtered.value].find((request) => {
if (request.groupId !== groupId || request.state !== 1) {
if (
request.groupId !== groupId ||
request.state !== 1 ||
groupRequestSubType(request) !== subType
) {
return false;
}
return subType === 'add'
? request.eventType === 1 && request.targetUid === uid
: (request.eventType === 2 || request.eventType === 22) &&
request.invitorUid === uid &&
request.targetUid === invitedUid;
? request.targetUid === uid
: request.invitorUid === uid && request.targetUid === invitedUid;
}) ?? null
);
}
+18 -2
View File
@@ -406,6 +406,7 @@ export class ForwardApi {
name: string,
groupId?: number,
userId?: number,
allowTemporary = true,
): Promise<MessageElementOf<'file'>> {
if (groupId !== undefined) {
const uploaded = await this.ctx.apis.groupFile.upload(
@@ -415,6 +416,7 @@ export class ForwardApi {
'/',
true,
false,
{ allowTemporary },
);
if (!uploaded.fileId) {
@@ -482,6 +484,7 @@ export class ForwardApi {
element: MessageElement,
groupId?: number,
userId?: number,
allowTemporary = true,
): Promise<MessageElement> {
if (element.type !== 'file') {
return element;
@@ -495,6 +498,7 @@ export class ForwardApi {
fileNameForUpload(element),
groupId,
userId,
allowTemporary,
);
return {
...stripFileSource(element),
@@ -506,6 +510,14 @@ export class ForwardApi {
const cached = this.ctx.recallUploadedFile(element.fileId);
if (isCachedFileUsableInTarget(cached, groupId, userId)) {
if (groupId !== undefined && cached?.busId === 104 && !allowTemporary) {
throw new MessageElementValidationError(
'UNSENDABLE_TYPE',
'temporary group files require only file or image segments in the same forward node',
'file',
);
}
return element;
}
@@ -515,6 +527,7 @@ export class ForwardApi {
fileNameForUpload(element, cached),
groupId,
userId,
allowTemporary,
);
return {
...stripFileSource(element),
@@ -532,9 +545,12 @@ export class ForwardApi {
): Promise<ForwardNodePayload[]> {
return Promise.all(
nodes.map(async (node) => {
const allowTemporary = node.elements.every(
(element) => element.type === 'file' || element.type === 'image',
);
const elements = await Promise.all(
node.elements.map((element) =>
this.prepareForwardFileElement(element, groupId, userId),
this.prepareForwardFileElement(element, groupId, userId, allowTemporary),
),
);
return cloneNodeWithElements(node, elements);
@@ -890,7 +906,7 @@ export class ForwardApi {
}
for (const [groupId, groupNodes] of byGroup) {
let byUin: Map<number, { nickname: string; card: string }>;
let byUin: Map<number, { nickname: string; card?: string }>;
try {
const members = await this.ctx.apis.contacts.fetchGroupMemberList(groupId);
+86 -27
View File
@@ -76,6 +76,16 @@ export interface UploadFileResult {
fileHash?: string | null;
}
export interface GroupFileUploadResult {
fileId: string;
busId: number;
}
export interface GroupFileUploadOptions {
/** False when the enclosing message contains content a temporary file cannot carry. */
allowTemporary?: boolean;
}
// Re-export so callers don't have to dig into apis/shared.
export type { MediaIndexNode } from './shared';
@@ -136,6 +146,7 @@ async function assertUnchanged(
function buildGroupFileUploadExt(
senderUin: number,
groupId: number,
busId: number,
fileName: string,
fileSize: number,
md5: Uint8Array,
@@ -150,7 +161,7 @@ function buildGroupFileUploadExt(
unknown2: 1,
entry: {
busiBuff: {
busId: 102,
busId,
senderUin: BigInt(senderUin),
receiverUin: BigInt(groupId),
groupCode: BigInt(groupId),
@@ -255,12 +266,23 @@ export class GroupFileApi {
// ─────────────── publish (group file → chat) ───────────────
publish(groupId: number, fileId: string): Promise<void> {
publish(groupId: number, fileId: string, busId?: number): Promise<void> {
if (!fileId) {
throw new Error('publish requires fileId');
}
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
return PublishGroupFile.invoke(this.ctx, {
groupId,
fileId,
busId: busId ?? this.cachedBusId(groupId, fileId),
});
}
private cachedBusId(groupId: number, fileId: string): number {
const cached = this.ctx.recallUploadedFile(fileId);
return cached?.scope === 'group' && cached.groupId === groupId
? (cached.busId ?? 102)
: 102;
}
trans(groupId: number, fileId: string): Promise<TransGroupFileResult> {
@@ -290,7 +312,8 @@ export class GroupFileApi {
folderId = '/',
uploadFile = true,
publishFile = uploadFile,
): Promise<UploadFileResult> {
options: GroupFileUploadOptions = {},
): Promise<GroupFileUploadResult> {
const bridge = this.ctx;
// Group/private files may legitimately be up to 4 GiB on QQ's wire, so
// override the default 1 GiB cap with the protocol ceiling. Stage onto a
@@ -307,14 +330,36 @@ export class GroupFileApi {
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
const hashes = await hashFileStreaming(staged.filePath);
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
const params: UploadGroupFileRequest.Params = {
groupId,
fileName,
folderId: normalizeDirectory(folderId),
fileSize: staged.fileSize,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
});
busId: 102,
};
let upload = await UploadGroupFileRequest.invoke(this.ctx, params);
// These are the storage-limit responses for which QQ switches to
// temporary storage. Never retry transport, permission or arbitrary
// service errors, and never retry the temporary request itself.
if (upload.retCode === -403 || upload.retCode === -9801 || upload.retCode === -98090) {
if (options.allowTemporary === false) {
throw new Error(
`temporary group files require only file or image segments; remove text and other content before retrying (group file upload code=${upload.retCode})`,
);
}
log.warn(
'Group %d permanent file storage rejected upload (code=%d); retrying as a temporary file',
groupId,
upload.retCode,
);
params.busId = 104;
upload = await UploadGroupFileRequest.invoke(this.ctx, params);
}
ensureRetCodeZero(
'group file upload',
upload.retCode,
@@ -322,6 +367,18 @@ export class GroupFileApi {
upload.clientWording,
);
const busId = upload.busId || params.busId;
if (busId !== 102 && busId !== 104) {
throw new Error(`group file upload returned unsupported storage type: ${busId}`);
}
if (busId === 104 && options.allowTemporary === false) {
throw new Error(
'temporary group files require only file or image segments; remove text and other content before retrying',
);
}
const fileId =
typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
@@ -329,23 +386,6 @@ export class GroupFileApi {
throw new Error('group file upload response missing file_id');
}
// Remember the upload so a later `send_group_msg` carrying just the
// file_id can route via `publish` without forcing the OneBot caller
// to thread fileName/size/md5 separately. For groups the wire
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
// mainly for log-line correctness; the c2c counterpart in
// `uploadPrivate` is where the cache is actually load-bearing.
this.ctx.rememberUploadedFile({
fileId,
scope: 'group',
groupId,
fileName,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
rememberedAt: Date.now(),
});
if (!upload.boolFileExist && uploadFile) {
const senderUin = toInt(this.ctx.identity.uin);
@@ -366,6 +406,7 @@ export class GroupFileApi {
const ext = buildGroupFileUploadExt(
senderUin,
groupId,
busId,
fileName,
staged.fileSize,
hashes.md5,
@@ -386,6 +427,20 @@ export class GroupFileApi {
await uploadHighwayHttp(bridge, session, 71, chunkSource, hashes.md5, ext);
}
// Retain the storage type for later file_id publication and download.
// A failed byte transfer must not leave a usable-looking cache entry.
this.ctx.rememberUploadedFile({
fileId,
scope: 'group',
groupId,
busId,
fileName,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
rememberedAt: Date.now(),
});
// Stage 3: file is on the server, now publish it as a chat message.
//
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
@@ -398,7 +453,7 @@ export class GroupFileApi {
// tests can mock at the same Api boundary.
if (publishFile) {
try {
await this.publish(groupId, fileId);
await this.publish(groupId, fileId, busId);
} catch (err) {
// Keep the completed upload identifiable, but a requested chat
// publication must not be reported as a successful send.
@@ -409,7 +464,7 @@ export class GroupFileApi {
}
}
return { fileId };
return { fileId, busId };
} finally {
await staged.cleanup();
}
@@ -711,8 +766,12 @@ export class GroupFileApi {
// ─────────────── url fetch (group / private files) ───────────────
async getUrl(groupId: number, fileId: string, busId = 102): Promise<string> {
return GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId });
async getUrl(groupId: number, fileId: string, busId?: number): Promise<string> {
return GetGroupFileUrl.invoke(this.ctx, {
groupId,
fileId,
busId: busId ?? this.cachedBusId(groupId, fileId),
});
}
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {
+7
View File
@@ -27,6 +27,8 @@ import {
import {
getQzonePublicCapabilities,
getQzoneHomeFeeds,
getQzoneFeedDetail,
type QzoneFeedDetail,
getQzoneShareArk,
type QzoneShareArk,
getQzonePublicFeeds,
@@ -81,6 +83,11 @@ export class QzoneApi {
return getQzoneHomeFeeds(cookies, this.ctx.identity.uin, targetUin?.toString(), cursor);
}
async getFeedDetail(tid: string): Promise<QzoneFeedDetail> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneFeedDetail(cookies, tid);
}
async getShareArk(feed: JsonObject): Promise<QzoneShareArk> {
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneShareArk(cookies, feed);
+3 -17
View File
@@ -17,6 +17,8 @@ import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
import { buildApiHub, type ApiHub } from './apis';
import { AiVoiceChatType, type AiVoiceCategory, type StrangerStatus } from './apis/extras';
import type { BridgeInterface, RosterWarmupResult } from './bridge-interface';
import type { UploadedFileMeta } from './bridge-context';
export type { UploadedFileMeta } from './bridge-context';
const log = createLogger('Bridge');
const runtimeLog = createLogger('Bridge.Runtime');
@@ -102,6 +104,7 @@ export class Bridge implements BridgeInterface {
this.disposePromise_ = (async () => {
try {
await Promise.allSettled(this.pendingPackets_);
this.apis.contacts.dispose();
await this.identity.close();
} finally {
this.events.clear();
@@ -593,23 +596,6 @@ export interface SendMessageReceipt {
timestamp: number;
}
export interface UploadedFileMeta {
fileId: string;
scope: 'group' | 'private';
/** Group id if scope='group', else `undefined`. */
groupId?: number;
/** Friend uin if scope='private', else `undefined`. */
userId?: number;
fileName: string;
fileSize: number;
fileMd5: Uint8Array;
fileSha1: Uint8Array;
/** Server-issued hash returned alongside the upload (private only). */
fileHash?: string;
/** Insert time — used to evict the oldest entry when the cache fills. */
rememberedAt: number;
}
export interface DownloadRKeyInfo {
rkey: string;
ttlSeconds: number;
+7 -7
View File
@@ -44,7 +44,7 @@ export type SidebarStyle = 'follow' | 'panel' | 'accent';
export type BackgroundType = 'none' | 'solid' | 'gradient' | 'image';
export type Density = 'cozy' | 'compact';
export type TimeFormat = '12h' | '24h';
/** Full color scheme. 'default' keeps the sky theme (driven by `mode`); the
/** Full color scheme. 'default' keeps the lavender theme (driven by `mode`); the
* Catppuccin flavors are complete palettes that also fix light/dark. */
export type Palette =
| 'default'
@@ -85,7 +85,7 @@ export interface UiAppearance {
accentCustom: string;
accentScope: AccentScope;
darkIntensity: DarkIntensity;
/** Full color scheme; 'default' = the built-in sky theme. */
/** Full color scheme; 'default' = the built-in lavender theme. */
palette: Palette;
sidebarStyle: SidebarStyle;
background: UiBackground;
@@ -203,12 +203,12 @@ export interface UiConfig {
}
// ─── Defaults ────────────────────────────────────────────────────────────
// Mirror the pre-existing ThemeContext defaults so an upgrade is a no-op
// visually until the operator changes something.
// Keep these defaults aligned with ThemeContext. Saved appearance choices
// are normalized independently and remain the operator's preference.
const DEFAULT_BACKGROUND: UiBackground = {
type: 'none',
color: '#0ea5e9',
color: '#b99ae6',
gradient: 'none',
imageOpacity: 0.15,
imageBlur: 0,
@@ -220,8 +220,8 @@ const DEFAULT_BACKGROUND: UiBackground = {
const DEFAULT_APPEARANCE: UiAppearance = {
mode: 'system',
accentMode: 'preset',
accentPreset: 'sky',
accentCustom: '#38bdf8',
accentPreset: 'lavender',
accentCustom: '#8561bd',
accentScope: 'global',
darkIntensity: 'soft',
palette: 'default',
+14 -10
View File
@@ -67,8 +67,8 @@ function friend(
type: 1,
layer1: {
properties: [
{ code: 20002, value: nickname },
{ code: 103, value: remark },
{ code: 20002, value: Buffer.from(nickname) },
{ code: 103, value: Buffer.from(remark) },
],
},
},
@@ -397,7 +397,7 @@ describe('apis/contacts / group requests', () => {
requests: [
{
sequence: 1_785_525_232_784_291n,
eventType: 7,
eventType: 1,
state: 1,
group: { groupUin: 1_095_186_374, groupName: 'group' },
target: { uin: 1_234_567_890, name: 'requester' },
@@ -439,7 +439,7 @@ describe('apis/contacts / group requests', () => {
requests: [
{
sequence: 42n,
eventType: 7,
eventType: 1,
state: 1,
group: { groupUin: 999, groupName: 'group' },
target: { uid: 'target_uid', name: 'requester' },
@@ -462,6 +462,8 @@ describe('apis/contacts / group requests', () => {
targetUin: 1_234_567_890,
invitorUid: 'inviter_uid',
operatorUid: 'operator_uid',
notifyType: 7,
eventType: 1,
filtered: true,
}),
]);
@@ -478,8 +480,8 @@ describe('apis/contacts / categorized friend roster', () => {
]);
await expect(api.fetchFriendList()).resolves.toEqual([
{ uin: 10001, uid: 'u1', nickname: 'Default', remark: '' },
{ uin: 10002, uid: 'u2', nickname: 'Alice', remark: 'A' },
{ uin: 10001, uid: 'u1', nickname: 'Default', remark: '', categoryId: 0 },
{ uin: 10002, uid: 'u2', nickname: 'Alice', remark: 'A', categoryId: 7 },
]);
expect(sendRawPacket).toHaveBeenCalledTimes(2);
});
@@ -508,14 +510,16 @@ describe('apis/contacts / categorized friend roster', () => {
categoryName: '我的好友',
memberCount: 1,
sortId: 0,
friends: [{ uin: 10001, uid: 'u1', nickname: 'Default', remark: '' }],
friends: [
{ uin: 10001, uid: 'u1', nickname: 'Default', remark: '', categoryId: 0 },
],
},
{
categoryId: 7,
categoryName: 'Work',
memberCount: 1,
sortId: 1,
friends: [{ uin: 10002, uid: 'u2', nickname: 'Alice', remark: 'A' }],
friends: [{ uin: 10002, uid: 'u2', nickname: 'Alice', remark: 'A', categoryId: 7 }],
},
{
categoryId: 9,
@@ -533,8 +537,8 @@ describe('apis/contacts / categorized friend roster', () => {
expect(secondRequest.body?.cookie).toEqual(cookie);
expect(rememberFriends).toHaveBeenCalledOnce();
expect(rememberFriends).toHaveBeenCalledWith([
{ uin: 10001, uid: 'u1', nickname: 'Default', remark: '' },
{ uin: 10002, uid: 'u2', nickname: 'Alice', remark: 'A' },
{ uin: 10001, uid: 'u1', nickname: 'Default', remark: '', categoryId: 0 },
{ uin: 10002, uid: 'u2', nickname: 'Alice', remark: 'A', categoryId: 7 },
]);
});
@@ -73,6 +73,64 @@ function decodeLongMsgRequest(rawBytes: Uint8Array): LongMsgResult {
}
describe('actions/forward — file segment inside forward node', () => {
it('rejects cached temporary files mixed with text before building a forward payload', async () => {
buildSendElemsMock.mockClear();
const bridge = mockBridge({
recallUploadedFile: vi.fn(() => ({ scope: 'group', groupId: 12345, busId: 104 })),
});
await expect(
new ForwardApi(bridge as any).upload(
[
{
userUin: 10001,
nickname: 'alice',
elements: [
{ type: 'text', text: 'caption' },
{ type: 'file', fileId: 'temp' },
],
},
],
12345,
),
).rejects.toThrow(/temporary group files.*only file or image/i);
expect(buildSendElemsMock).not.toHaveBeenCalled();
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('disallows temporary fallback when a forward node mixes a new file with text', async () => {
buildSendElemsMock.mockClear();
const bridge = mockBridge();
bridge.apis.groupFile.upload.mockRejectedValueOnce(
new Error('temporary group files require only file or image segments'),
);
await expect(
new ForwardApi(bridge as any).upload(
[
{
userUin: 10001,
nickname: 'alice',
elements: [
{ type: 'text', text: 'caption' },
{ type: 'file', url: 'base64://AQID', fileName: 'note.txt' },
],
},
],
12345,
),
).rejects.toThrow(/temporary group files/);
expect(bridge.apis.groupFile.upload).toHaveBeenCalledWith(
12345,
'base64://AQID',
'note.txt',
'/',
true,
false,
{ allowTemporary: false },
);
expect(buildSendElemsMock).not.toHaveBeenCalled();
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('rejects a recursive window shake before identity resolution or upload', async () => {
buildSendElemsMock.mockClear();
const resolveUserUid = vi.fn();
@@ -288,7 +346,9 @@ describe('actions/forward — file segment inside forward node', () => {
12345,
);
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false);
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false, {
allowTemporary: true,
});
expect(publish).not.toHaveBeenCalled();
const [elements] = buildSendElemsMock.mock.calls[0]!;
expect(elements).toEqual([
@@ -513,6 +573,7 @@ describe('actions/forward — file segment inside forward node', () => {
'/',
true,
false,
{ allowTemporary: true },
);
const [elements] = buildSendElemsMock.mock.calls[0]!;
expect(elements).toEqual([
@@ -28,7 +28,7 @@ function message(...elems: Elem[]): PushMsgBody {
responseHead: {
fromUin: 20002,
fromUid: 'sender-uid',
grp: { groupUin: 12345, memberCard: 'alice' },
grp: { groupUin: 12345, memberCard: Buffer.from('alice') },
},
contentHead: { msgType: 82, sequence: 10, timestamp: 1700000000 },
body: { richText: { elems } },
@@ -163,7 +163,7 @@ describe('get_forward_msg / cache lifetime', () => {
it('keeps an inner result attached to its outer result after sender enrichment', async () => {
const nameless = message({ text: { str: 'unnamed sender' } });
nameless.responseHead!.grp!.memberCard = '';
nameless.responseHead!.grp!.memberCard = new Uint8Array();
const downloads = new Map([
['enrich-outer', nestedResult('enrich-inner', 'enrich-key', nameless)],
]);
@@ -220,7 +220,7 @@ describe('get_forward_msg / cache lifetime', () => {
it('does not resurrect evicted nested results when enrichment finishes late', async () => {
const nameless = message({ text: { str: 'late sender' } });
nameless.responseHead!.grp!.memberCard = '';
nameless.responseHead!.grp!.memberCard = new Uint8Array();
const downloads = new Map([
['late-outer', nestedResult('late-inner', 'late-key', nameless)],
]);
@@ -43,7 +43,7 @@ function message(...elems: Elem[]): PushMsgBody {
responseHead: {
fromUin: 20002,
fromUid: 'sender-uid',
grp: { groupUin: 12345, memberCard: 'alice' },
grp: { groupUin: 12345, memberCard: Buffer.from('alice') },
},
contentHead: { msgType: 82, sequence: 10, timestamp: 1700000000 },
body: { richText: { elems } },
@@ -71,7 +71,7 @@ function setup(id: string) {
responseHead: {
fromUin: 20002,
fromUid: 'sender-uid',
grp: { groupUin: 12345, memberCard: 'alice' },
grp: { groupUin: 12345, memberCard: Buffer.from('alice') },
},
contentHead: { msgType: 82, sequence: 10, timestamp: 1700000000 },
body: {
+1 -1
View File
@@ -190,7 +190,7 @@ describe('actions/forward', () => {
responseHead: {
fromUin: 1787882683,
fromUid: 'u_x',
grp: { groupUin: 284840486, memberCard: '墨梓柒' },
grp: { groupUin: 284840486, memberCard: Buffer.from('墨梓柒') },
},
contentHead: { msgType: 82, sequence: 1, timestamp: 100 }, // 82 = PkgType.GroupMessage
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
@@ -0,0 +1,277 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
OidbBase,
OidbFriend,
OidbSvcTrpcTcp0xFD4_1Response,
} from '@snowluma/proto-defs/oidb';
import type {
OidbUserInfoRequest,
OidbUserInfoResponse,
} from '@snowluma/proto-defs/oidb-actions/base';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { Bridge } from '../../src/bridge/bridge';
function deferred() {
let resolve!: () => void;
let reject!: (reason: Error) => void;
const promise = new Promise<void>((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
const bridges: Bridge[] = [];
afterEach(async () => {
await Promise.all(bridges.splice(0).map((bridge) => bridge.dispose()));
vi.restoreAllMocks();
vi.useRealTimers();
});
function friend(uin: number, name = 'Roster'): OidbFriend {
return {
uin,
uid: `u_${uin}`,
customGroup: 7,
additional: [
{
type: 1,
layer1: {
properties: [
{ code: 20002, value: Buffer.from(name) },
{ code: 102, value: Buffer.from('') },
],
},
},
],
};
}
function setup(roster: () => OidbFriend[], load: (uin: number) => Promise<void> = async () => {}) {
const bridge = new Bridge(IdentityService.memory('90001'));
bridges.push(bridge);
const profileCalls: number[] = [];
let active = 0;
let peak = 0;
const send = vi.spyOn(bridge, 'sendRawPacket').mockImplementation(async (cmd, payload) => {
let responseData: Uint8Array;
if (cmd === 'OidbSvcTrpcTcp.0xfd4_1') {
const friends = roster();
responseData = protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>({
body: {
friends,
categories: [
{ categoryId: 7, categoryName: 'Friends', memberCount: friends.length },
],
},
});
} else if (cmd === 'OidbSvcTrpcTcp.0xfe1_2') {
const uin = protobuf_decode<OidbBase<OidbUserInfoRequest>>(payload).body!.uin!;
profileCalls.push(uin);
peak = Math.max(peak, ++active);
try {
await load(uin);
} finally {
active--;
}
responseData = protobuf_encode<OidbBase<OidbUserInfoResponse>>({
body: {
body: {
uin,
uid: `u_${uin}`,
properties: {
bytesProperties: [
{ code: 102, value: Buffer.from('Profile sign') },
{ code: 20020, value: Buffer.from('City') },
],
numberProperties: [
{ number1: 20037, number2: 0 },
{ number1: 41756, number2: 0 },
],
},
},
},
});
} else {
throw new Error(`unexpected request ${cmd}`);
}
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(responseData),
};
});
return {
bridge,
api: bridge.apis.contacts,
send,
profileCalls,
peak: () => peak,
active: () => active,
};
}
describe('explicit friend profile enrichment', () => {
it('releases profile cache timers when its Bridge is disposed', async () => {
vi.useFakeTimers();
const { api, bridge, profileCalls } = setup(() => [friend(10001)]);
await api.fetchFriendList({ withProfile: true });
expect(profileCalls).toEqual([10001]);
expect(vi.getTimerCount()).toBe(1);
await bridge.dispose();
expect(vi.getTimerCount()).toBe(0);
});
it('does not start profile cache loads when a roster response arrives after disposal', async () => {
vi.useFakeTimers();
const { api, bridge, send, profileCalls } = setup(() => [friend(10001)]);
const response = await send.getMockImplementation()!(
'OidbSvcTrpcTcp.0xfd4_1',
new Uint8Array(),
);
let resolve!: (value: typeof response) => void;
send.mockReturnValueOnce(
new Promise((yes) => {
resolve = yes;
}),
);
const pending = api.fetchFriendList({ withProfile: true });
const checked = expect(pending).rejects.toThrow('friend profile enrichment failed');
await bridge.dispose();
resolve(response);
await checked;
expect(profileCalls).toEqual([]);
expect(vi.getTimerCount()).toBe(0);
});
it('does not fan out on a cold 160-friend ordinary or categorized list', async () => {
const { api, profileCalls, send } = setup(() =>
Array.from({ length: 160 }, (_, i) => friend(10000 + i)),
);
expect(await api.fetchFriendList()).toHaveLength(160);
expect((await api.fetchFriendCategories())[0]?.friends).toHaveLength(160);
expect(profileCalls).toEqual([]);
expect(send).toHaveBeenCalledTimes(2);
});
it('shares the cache across list forms, preserves roster values and isolates accounts', async () => {
let now = Date.now();
vi.spyOn(Date, 'now').mockImplementation(() => now);
const one = setup(() => [friend(10001)]);
const first = await one.api.fetchFriendList({ withProfile: true });
expect(first[0]).toMatchObject({
nickname: 'Roster',
profile: { sign: '', age: 0, vipFlag: false, city: 'City' },
});
first[0]!.profile!.city = 'caller mutation';
const grouped = await one.api.fetchFriendCategories({ withProfile: true });
expect(grouped[0]?.friends[0]?.profile?.city).toBe('City');
expect(one.profileCalls).toEqual([10001]);
const two = setup(() => [friend(10001)]);
await two.api.fetchFriendList({ withProfile: true });
expect(two.profileCalls).toEqual([10001]);
now += 300_001;
await one.api.fetchFriendList({ withProfile: true });
expect(one.profileCalls).toEqual([10001, 10001]);
});
it('deduplicates overlapping lists and caps total concurrent queries at four', async () => {
const gates = new Map<number, ReturnType<typeof deferred>>();
let page = 0;
const { api, profileCalls, peak } = setup(
() => (page++ === 0 ? [1, 2, 3, 4] : [3, 4, 5, 6]).map((id) => friend(10000 + id)),
(uin) => {
const gate = deferred();
gates.set(uin, gate);
return gate.promise;
},
);
const first = api.fetchFriendList({ withProfile: true });
const second = api.fetchFriendCategories({ withProfile: true });
await vi.waitFor(() => expect(profileCalls).toHaveLength(4));
for (const gate of gates.values()) {
gate.resolve();
}
await vi.waitFor(() => expect(profileCalls).toHaveLength(6));
for (const gate of gates.values()) {
gate.resolve();
}
await Promise.all([first, second]);
expect(new Set(profileCalls).size).toBe(6);
expect(peak()).toBe(4);
});
it('drains a failed batch, surfaces the failure and retries only on a later request', async () => {
const gates = new Map<number, ReturnType<typeof deferred>>();
let blocking = true;
const { api, bridge, profileCalls, active } = setup(
() => [1, 2, 3, 4, 5].map((id) => friend(10000 + id)),
(uin) => {
if (!blocking) {
return Promise.resolve();
}
const gate = deferred();
gates.set(uin, gate);
return gate.promise;
},
);
let finished = false;
const result = api.fetchFriendList({ withProfile: true });
const checked = expect(result).rejects.toThrow('friend profile enrichment failed');
void result.then(
() => {
finished = true;
},
() => {
finished = true;
},
);
await vi.waitFor(() => expect(profileCalls).toHaveLength(4));
gates.get(10001)!.reject(new Error('synthetic timeout'));
await Promise.resolve();
expect(finished).toBe(false);
for (const [uin, gate] of gates) {
if (uin !== 10001) {
gate.resolve();
}
}
await checked;
expect(active()).toBe(0);
expect(profileCalls).toHaveLength(4);
expect(bridge.identity.friends).toEqual([]);
blocking = false;
await api.fetchFriendList({ withProfile: true });
expect(profileCalls).toEqual([10001, 10002, 10003, 10004, 10001, 10005]);
});
it('does not let a slow enriched snapshot replace a newer ordinary roster', async () => {
const gate = deferred();
let page = 0;
const { api, bridge, profileCalls } = setup(
() => [friend(10001, page++ === 0 ? 'Old' : 'New')],
() => gate.promise,
);
const old = api.fetchFriendList({ withProfile: true });
await vi.waitFor(() => expect(profileCalls).toHaveLength(1));
await api.fetchFriendList();
gate.resolve();
expect((await old)[0]?.nickname).toBe('Old');
expect(bridge.identity.findFriend(10001)?.nickname).toBe('New');
});
});
+182 -3
View File
@@ -1,10 +1,12 @@
import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
import type {
OidbGroupFileCountViewResp,
OidbGroupFileReq,
OidbGroupFileResp,
OidbGroupFileUploadResp,
OidbGroupFileViewResp,
OidbGroupFileFolderResp,
OidbGroupSendFileReq,
@@ -70,6 +72,10 @@ function packResponse(body: Uint8Array) {
};
}
function uploadResponse(upload: OidbGroupFileUploadResp) {
return packResponse(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: { upload } }));
}
let STAGED_FILE: string;
describe('apis/group-file', () => {
@@ -138,7 +144,7 @@ describe('apis/group-file', () => {
const api = new GroupFileApi(bridge as any);
vi.spyOn(api, 'publish').mockResolvedValue();
const out = await api.upload(12345, '/path/file.bin');
expect(out).toEqual({ fileId: 'fid-xyz' });
expect(out).toEqual({ fileId: 'fid-xyz', busId: 102 });
expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
});
@@ -224,8 +230,180 @@ describe('apis/group-file', () => {
await expect(
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
).rejects.toThrow(/code=999/);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
});
it.each([-403, -9801, -98090])(
'retries capacity error %s as a temporary group file',
async (retCode) => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(
uploadResponse({ retCode, retMsg: 'permanent storage full' }),
)
.mockResolvedValueOnce(
uploadResponse({ fileId: 'temporary-file', busId: 104, boolFileExist: true }),
);
const api = new GroupFileApi(bridge as any);
const result = await api.upload(12345, '/path/file.bin', 'doc.bin', '/folder');
expect(result).toMatchObject({ fileId: 'temporary-file', busId: 104 });
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
const requests = bridge.sendRawPacket.mock.calls
.slice(0, 2)
.map(([, bytes]) => protobuf_decode<OidbBase<OidbGroupFileReq>>(bytes).body?.file);
expect(requests[0]).toMatchObject({ busId: 102, targetDirectory: '/folder' });
expect(requests[1]).toEqual({ ...requests[0], busId: 104 });
const publish = protobuf_decode<OidbBase<OidbGroupSendFileReq>>(
bridge.sendRawPacket.mock.calls[2]![1],
);
expect(publish.body?.body?.info).toMatchObject({
fileId: 'temporary-file',
busiType: 104,
});
expect(bridge.rememberUploadedFile).toHaveBeenCalledWith(
expect.objectContaining({ busId: 104, groupId: 12345 }),
);
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
},
);
it('carries the server-selected storage type through bytes, publication and cached reuse', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(
uploadResponse({
fileId: 'temporary-file',
busId: 104,
uploadIp: '127.0.0.1',
uploadPort: 8080,
fileKey: new Uint8Array([7]),
checkKey: new Uint8Array([8]),
}),
);
bridge.recallUploadedFile.mockImplementation(
() => bridge.rememberUploadedFile.mock.calls.at(-1)?.[0],
);
const api = new GroupFileApi(bridge as any);
await api.upload(12345, '/path/file.bin');
const ext = protobuf_decode<FileUploadExt>(
vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]![5],
);
expect(ext.entry?.busiBuff?.busId).toBe(104);
await api.publish(12345, 'temporary-file');
for (const [, bytes] of bridge.sendRawPacket.mock.calls.slice(1)) {
expect(
protobuf_decode<OidbBase<OidbGroupSendFileReq>>(bytes).body?.body?.info?.busiType,
).toBe(104);
}
});
it('stops after a failed temporary attempt and releases the staged file', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(uploadResponse({ retCode: -403 }))
.mockResolvedValueOnce(
uploadResponse({ retCode: -9801, retMsg: 'temporary storage rejected' }),
);
await expect(
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
).rejects.toThrow(/code=-9801/);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
const staged = await vi.mocked(stageMod.stageSourceToDisk).mock.results.at(-1)!.value;
expect(staged.cleanup).toHaveBeenCalledOnce();
});
it('retains temporary mode when the successful retry omits its storage type', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(uploadResponse({ retCode: -403 }))
.mockResolvedValueOnce(uploadResponse({ fileId: 'temp', boolFileExist: true }));
const api = new GroupFileApi(bridge as any);
const publish = vi.spyOn(api, 'publish').mockResolvedValue();
await expect(api.upload(12345, '/path/file.bin')).resolves.toEqual({
fileId: 'temp',
busId: 104,
});
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'temp', 104);
});
it('rejects an unknown server storage type before bytes or publication', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(
uploadResponse({ fileId: 'bad', busId: 777, boolFileExist: true }),
);
await expect(
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
).rejects.toThrow(/unsupported storage type: 777/);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
});
it.each([
{ scope: 'group', groupId: 12345, expected: 104 },
{ scope: 'group', groupId: 54321, expected: 102 },
{ scope: 'private', groupId: undefined, expected: 102 },
] as const)(
'scopes cached storage to the target group for download and reuse (%j)',
async ({ scope, groupId, expected }) => {
const bridge = mockBridge();
bridge.recallUploadedFile.mockReturnValue({
fileId: 'temp',
scope,
groupId,
busId: 104,
});
bridge.sendRawPacket.mockResolvedValueOnce(
packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
download: {
downloadDns: 'download.example.com',
downloadUrl: new Uint8Array([1]),
},
},
}),
),
);
const api = new GroupFileApi(bridge as any);
await api.getUrl(12345, 'temp');
await api.publish(12345, 'temp');
const requests = bridge.sendRawPacket.mock.calls;
expect(
protobuf_decode<OidbBase<OidbGroupFileReq>>(requests[0]![1]).body?.download?.busId,
).toBe(expected);
expect(
protobuf_decode<OidbBase<OidbGroupSendFileReq>>(requests[1]![1]).body?.body?.info
?.busiType,
).toBe(expected);
},
);
it.each([{ retCode: -403 }, { fileId: 'temp', busId: 104, boolFileExist: true }])(
'rejects a disallowed temporary upload before transferring bytes or publishing (%j)',
async (response) => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(uploadResponse(response));
await expect(
new GroupFileApi(bridge as any).upload(
12345,
'/path/file.bin',
'',
'/',
true,
false,
{ allowTemporary: false },
),
).rejects.toThrow(/temporary group files.*only file or image/i);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
},
);
it('upload publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => {
// Reproduces the bug report: OIDB upload + highway PUT alone only
// stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB
@@ -341,11 +519,12 @@ describe('apis/group-file', () => {
const upload = api.upload(12345, 'base64://AQID', 'confirmed.txt');
if (confirmed) {
await expect(upload).resolves.toEqual({ fileId: 'fid-confirm' });
expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm');
await expect(upload).resolves.toEqual({ fileId: 'fid-confirm', busId: 102 });
expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm', 102);
} else {
await expect(upload).rejects.toBe(failure);
expect(publishSpy).not.toHaveBeenCalled();
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
}
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
@@ -101,6 +101,31 @@ const cases = [
describe('apis/qzone public', () => {
afterEach(() => vi.restoreAllMocks());
it('reads a post by tid using current-account credentials', async () => {
const { api, getCookies } = makeApi();
const tid = '1127000000f1536501000000';
const detail = { feed, attach_info: 'comments-next' };
const request = vi.spyOn(qzonePublic, 'getQzoneFeedDetail').mockResolvedValue(detail);
expect(await api.getFeedDetail(tid)).toBe(detail);
expect(getCookies).toHaveBeenCalledExactlyOnceWith('qzone.qq.com');
expect(request).toHaveBeenCalledExactlyOnceWith(cookies, tid);
});
it('propagates feed detail and cookie failures without replay', async () => {
const { api, getCookies } = makeApi();
const request = vi
.spyOn(qzonePublic, 'getQzoneFeedDetail')
.mockRejectedValue(new Error('denied'));
await expect(api.getFeedDetail('1127000000f1536501000000')).rejects.toThrow('denied');
getCookies.mockRejectedValueOnce(new Error('cookie failure'));
await expect(api.getFeedDetail('1127000000f1536501000000')).rejects.toThrow(
'cookie failure',
);
expect(request).toHaveBeenCalledOnce();
});
it('generates a share card with the account cookies and preserves its notice', async () => {
const { api, getCookies } = makeApi();
const card = { ark: '{}', requires_confirmation: true, notice: '所有人可见' };
@@ -0,0 +1,81 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
import { FetchRobotUinRanges } from '@snowluma/protocol/oidb-services/contacts/fetch-robot-uin-ranges';
import { Bridge } from '../src/bridge/bridge';
afterEach(() => {
vi.restoreAllMocks();
vi.useRealTimers();
});
describe('Bridge contact cache lifecycle', () => {
it('keeps contact lookups available to packets already draining during shutdown', async () => {
vi.useFakeTimers();
const bridge = new Bridge(IdentityService.memory('10001'));
vi.spyOn(FetchRobotUinRanges, 'invoke').mockResolvedValue({ version: 1, ranges: [] });
const load = vi
.spyOn(FetchGroupMemberListPage, 'invoke')
.mockResolvedValue({ members: [], token: '' });
await bridge.apis.contacts.fetchGroupMemberList(42);
let memberRead: Promise<unknown> | undefined;
bridge.registerCmd('test.contact-cache', () => {
memberRead = bridge.apis.contacts.fetchGroupMemberList(42);
return [];
});
const packet = bridge.onPacket({
pid: 1,
uin: '10001',
serviceCmd: 'test.contact-cache',
seqId: 1,
retCode: 0,
fromClient: false,
body: new Uint8Array(),
});
const closing = bridge.dispose();
await packet;
await expect(memberRead).resolves.toEqual([]);
await closing;
expect(load).toHaveBeenCalledOnce();
expect(vi.getTimerCount()).toBe(0);
});
it.each([false, true])(
'releases member caches before identity closes, close failure=%s',
async (fails) => {
vi.useFakeTimers();
const identity = IdentityService.memory('10001');
const bridge = new Bridge(identity);
vi.spyOn(FetchRobotUinRanges, 'invoke').mockResolvedValue({ version: 1, ranges: [] });
const load = vi
.spyOn(FetchGroupMemberListPage, 'invoke')
.mockResolvedValue({ members: [], token: '' });
await bridge.apis.contacts.fetchGroupMemberList(42);
await bridge.apis.contacts.fetchGroupMemberList(42);
expect(load).toHaveBeenCalledOnce();
expect(vi.getTimerCount()).toBe(1);
const originalClose = identity.close.bind(identity);
vi.spyOn(identity, 'close').mockImplementation(async () => {
expect(vi.getTimerCount()).toBe(0);
await originalClose();
if (fails) {
throw new Error('identity close failed');
}
});
const closing = bridge.dispose();
expect(bridge.dispose()).toBe(closing);
if (fails) {
await expect(closing).rejects.toThrow('identity close failed');
} else {
await closing;
}
await expect(bridge.apis.contacts.fetchGroupMemberList(42)).rejects.toThrow('disposed');
expect(load).toHaveBeenCalledOnce();
expect(vi.getTimerCount()).toBe(0);
},
);
});
+22 -1
View File
@@ -30,7 +30,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
}));
import { type bytes, type pb, protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { MsgInfo } from '@snowluma/proto-defs/element';
import type { GroupFileExtra, MsgInfo } from '@snowluma/proto-defs/element';
import { buildSendElems, encodePrivateRichText } from '@snowluma/protocol/element-builder';
import { uploadPtt } from '@snowluma/protocol/highway/ptt-upload';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
@@ -374,6 +374,27 @@ describe('element-builder / all-message validation preflight', () => {
});
describe('element-builder / file element is no longer carried in elems[]', () => {
it.each([12345, 54321])(
'preserves temporary storage only in a matching group forward (%s)',
async (cachedGroupId) => {
const bridge = {
recallUploadedFile: vi.fn(() => ({
scope: 'group',
groupId: cachedGroupId,
busId: 104,
fileName: 'doc.pdf',
fileSize: 3,
})),
} as any;
const [elem] = await buildSendElems([{ type: 'file', fileId: 'temp' }], {
bridge,
groupId: 12345,
forwardFake: true,
});
const extra = protobuf_decode<GroupFileExtra>(elem!.transElem!.elemValue!.subarray(3));
expect(extra.inner?.info?.busId).toBe(cachedGroupId === 12345 ? 104 : 102);
},
);
// Regression for the `result=79` class: previously the element-builder
// emitted a `transElem(elemType=24, ...)` for `{type:'file'}` segments
// and the QQ-NT server rejected the outgoing PbSendMsg with that wire
@@ -82,8 +82,12 @@ class FakeSocket extends EventEmitter {
headers: string[] = [];
frames: Buffer[] = [];
closeBeforeResponse = false;
idleBeforeResponse = false;
stallWrites = false;
responseDelayMs = 0;
connectFailure?: Error | 'timeout';
private connectTimer?: ReturnType<typeof setTimeout>;
private responseTimer?: ReturnType<typeof setTimeout>;
private buf = Buffer.alloc(0);
constructor(
private readonly responseFrame: Buffer,
@@ -105,6 +109,10 @@ class FakeSocket extends EventEmitter {
}
write(data: unknown, cb?: (err?: Error) => void): boolean {
if (this.stallWrites) {
return false;
}
if (this.destroyed || !this.writable) {
const err = new Error('write after socket end');
@@ -148,11 +156,16 @@ class FakeSocket extends EventEmitter {
this.buf = this.buf.subarray(total);
this.posts += 1;
const thisPost = this.posts;
setImmediate(() => {
const respond = () => {
if (this.destroyed) {
return;
}
if (this.idleBeforeResponse) {
return;
}
if (thisPost === this.failOnPost) {
this.writable = false;
this.readableEnded = true;
@@ -199,12 +212,19 @@ class FakeSocket extends EventEmitter {
this.emit('end');
this.emit('close');
}
});
};
if (this.responseDelayMs > 0) {
this.responseTimer = setTimeout(respond, this.responseDelayMs);
} else {
setImmediate(respond);
}
}
}
destroy() {
clearTimeout(this.connectTimer);
clearTimeout(this.responseTimer);
this.destroyed = true;
this.writable = false;
}
@@ -239,8 +259,8 @@ function highwayTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Highway');
}
function makeBridge(): BridgeContext {
return { identity: { uin: '10001' } as unknown } as unknown as BridgeContext;
function makeBridge(uin = '10001'): BridgeContext {
return { identity: { uin } as unknown } as unknown as BridgeContext;
}
function makeSession(): HighwaySession {
@@ -459,6 +479,7 @@ describe('Highway connection selection', () => {
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllEnvs();
setLogLevel(previousLogLevel);
});
@@ -472,6 +493,201 @@ describe('Highway connection selection', () => {
};
}
it.each([1003, 1004])(
'reaches the fourth candidate after three idle peers for command %i (#637)',
async (commandId) => {
vi.useFakeTimers();
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS', '100');
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '5000');
installFactory(() => {
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
socket.idleBeforeResponse =
createConnectionMock.mock.lastCall?.[0].host !== '192.0.2.4';
return socket;
});
const session = {
...makeSession(),
servers: Array.from({ length: 4 }, (_, i) => ({
host: `192.0.2.${i + 1}`,
port: 443,
})),
};
const source = new RecordingChunkSource(80);
const completed = expect(
uploadHighwayHttp(
makeBridge(),
session,
commandId,
source,
new Uint8Array(16),
new Uint8Array(),
),
).resolves.toBeUndefined();
await Promise.all([completed, vi.runAllTimersAsync()]);
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual(
session.servers,
);
expect(source.reads).toEqual([{ offset: 0, length: 80 }]);
expect(source.closeCount).toBe(1);
expect((createdSockets as FakeSocket[]).every((socket) => socket.destroyed)).toBe(true);
},
);
it('uses recent successful host and port only for the same account and upload type', async () => {
vi.useFakeTimers();
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS', '100');
const session = {
...makeSession(),
servers: [
{ host: '192.0.2.1', port: 14000 },
{ host: '192.0.2.1', port: 80 },
],
};
const bridge = makeBridge();
const send = async (owner: BridgeContext, commandId = 1004, candidates = session) => {
installFactory(() => {
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
socket.idleBeforeResponse = createConnectionMock.mock.lastCall?.[0].port === 14000;
return socket;
});
await Promise.all([
expect(
uploadHighwayHttp(
owner,
candidates,
commandId,
new RecordingChunkSource(80),
new Uint8Array(16),
new Uint8Array(),
),
).resolves.toBeUndefined(),
vi.runAllTimersAsync(),
]);
return createConnectionMock.mock.calls.map(([options]) => options);
};
expect(await send(bridge)).toEqual(session.servers);
expect(await send(bridge)).toEqual([session.servers[1]]);
expect(await send(makeBridge('10002'))).toEqual(session.servers);
expect(await send(bridge, 1003)).toEqual(session.servers);
const replacement = { ...session, servers: [{ host: '192.0.2.2', port: 80 }] };
expect(await send(bridge, 1004, replacement)).toEqual(replacement.servers);
await vi.advanceTimersByTimeAsync(5 * 60_000);
expect(await send(bridge)).toEqual(session.servers);
});
it.each(['response', 'write', 'retry'])(
'stops a pending %s at the shared upload deadline and releases resources',
async (phase) => {
vi.useFakeTimers();
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '150');
vi.stubEnv(
'SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS',
phase === 'retry' ? '50' : '1000',
);
installFactory(() => {
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
socket.idleBeforeResponse = true;
socket.stallWrites = phase === 'write';
return socket;
});
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const source = new RecordingChunkSource(80);
const start = Date.now();
try {
const failed = expect(
uploadHighwayHttp(
makeBridge(),
sessionWithCandidates(),
1004,
source,
new Uint8Array(16),
new Uint8Array(),
),
).rejects.toThrow('timed out after 150ms');
await Promise.all([failed, vi.runAllTimersAsync()]);
expect(Date.now() - start).toBe(150);
expect(createConnectionMock).toHaveBeenCalledTimes(1);
expect(source.closeCount).toBe(1);
expect(
(createdSockets as FakeSocket[]).every(
(socket) =>
socket.destroyed &&
socket.listenerCount('data') === 0 &&
socket.listenerCount('close') === 0,
),
).toBe(true);
const terminal = highwayTrace(entries).filter((entry) =>
entry.message.startsWith('highway_put_terminal '),
);
expect(terminal).toHaveLength(1);
expect(terminal[0]!.message).toContain('reason=upload_timeout');
expect(vi.getTimerCount()).toBe(0);
if (phase === 'retry') {
expect(
entries.some(
(entry) =>
entry.message.includes('phase=read_response') &&
entry.message.includes('received=0B'),
),
).toBe(true);
}
} finally {
unsubscribe();
}
},
);
it('does not renew the total deadline when a chunk succeeds', async () => {
vi.useFakeTimers();
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '250');
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS', '200');
installFactory(() => {
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
socket.responseDelayMs = 100;
return socket;
});
const source = new RecordingChunkSource(2 * HIGHWAY_BLOCK_SIZE + 80);
const start = Date.now();
const failed = expect(
uploadHighwayHttp(
makeBridge(),
makeSession(),
1004,
source,
new Uint8Array(16),
new Uint8Array(),
),
).rejects.toThrow('acknowledgedBytes=2097152/2097232');
await Promise.all([failed, vi.runAllTimersAsync()]);
expect(Date.now() - start).toBe(250);
expect(source.closeCount).toBe(1);
expect(vi.getTimerCount()).toBe(0);
});
it('rejects invalid timeout configuration before connecting and closes the source', async () => {
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '0');
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'));
const source = new RecordingChunkSource(80);
await expect(
uploadHighwayHttp(
makeBridge(),
makeSession(),
1004,
source,
new Uint8Array(16),
new Uint8Array(),
),
).rejects.toThrow('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS');
expect(createConnectionMock).not.toHaveBeenCalled();
expect(source.closeCount).toBe(1);
});
it.each(['timeout', 'ECONNREFUSED', 'ENETUNREACH'])(
'switches on %s and uploads over the successful connection',
async (failure) => {
@@ -515,8 +731,9 @@ describe('Highway connection selection', () => {
},
);
it('bounds initial selection to ten seconds without repeating exhausted candidates', async () => {
it('bounds initial selection by the configured total deadline without repeating candidates', async () => {
vi.useFakeTimers();
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '10000');
installFactory(() => {
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
socket.connectFailure = 'timeout';
@@ -544,7 +761,7 @@ describe('Highway connection selection', () => {
new Uint8Array(16),
new Uint8Array(),
);
const failed = expect(upload).rejects.toThrow(/connection failed.*TCP connect timeout/);
const failed = expect(upload).rejects.toThrow('timed out after 10000ms');
await vi.runAllTimersAsync();
await failed;
expect(Date.now() - start).toBe(10000);
@@ -561,7 +778,7 @@ describe('Highway connection selection', () => {
entry.message.startsWith('highway_put_terminal '),
);
expect(terminals).toHaveLength(1);
expect(terminals[0]!.message).toContain('reason=connect_exhausted');
expect(terminals[0]!.message).toContain('reason=upload_timeout');
expect(terminals[0]!.message).toContain('connections=0');
} finally {
unsubscribe();
@@ -177,6 +177,8 @@ beforeEach(() => {
});
afterEach(() => {
setLogLevel(level);
vi.unstubAllEnvs();
vi.useRealTimers();
for (const socket of sockets) {
socket.destroy();
@@ -184,6 +186,64 @@ afterEach(() => {
});
describe('bounded parallel highway uploads', () => {
it('does not let trickled response bytes extend the whole-file deadline', async () => {
vi.useFakeTimers();
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '100');
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS', '30');
onRequest = ({ socket }) => {
const timer = setInterval(() => socket.emit('data', Buffer.from('x')), 10);
socket.once('close', () => clearInterval(timer));
};
const source = new Source(80);
const start = Date.now();
const failed = expect(upload(source, 1)).rejects.toThrow('timed out after 100ms');
await Promise.all([failed, vi.runAllTimersAsync()]);
expect(Date.now() - start).toBe(100);
expect(source.closes).toBe(1);
expect(active.size).toBe(0);
expect(vi.getTimerCount()).toBe(0);
});
it('drains a pending source read after the deadline without sending its bytes', async () => {
vi.useFakeTimers();
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '50');
const source = new Source(80);
let reading = false;
const read = source.read.bind(source);
source.read = async (offset, length) => {
reading = true;
await new Promise<void>((resolve) => setTimeout(resolve, 100));
reading = false;
return read(offset, length);
};
const close = vi.spyOn(source, 'close').mockImplementation(async () => {
expect(reading).toBe(false);
});
const failed = expect(upload(source, 1)).rejects.toThrow('timed out after 50ms');
await Promise.all([failed, vi.runAllTimersAsync()]);
expect(connect).not.toHaveBeenCalled();
expect(close).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
});
it('aborts all parallel requests at one whole-file deadline', async () => {
vi.useFakeTimers();
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '1000');
const source = new Source(6 * BLOCK);
const start = Date.now();
const failed = expect(upload(source, 3)).rejects.toThrow('timed out after 1000ms');
await Promise.all([failed, vi.runAllTimersAsync()]);
expect(Date.now() - start).toBe(1000);
expect(requests).toHaveLength(3);
expect(sockets.every((socket) => socket.destroyed)).toBe(true);
expect(active.size).toBe(0);
expect(source.closes).toBe(1);
expect(vi.getTimerCount()).toBe(0);
});
it.each([2, 3, 4])(
'uses %i connections, accepts out-of-order acknowledgements and sends the tail last',
async (concurrency) => {
@@ -6,7 +6,9 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('@snowluma/protocol/highway/pipeline', () => ({
runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })),
runNtv2Upload: vi.fn(async () => ({
msgInfo: { msgInfoBody: [{ index: { fileUuid: 'uploaded-image' } }], extBizInfo: {} },
})),
finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0xca, 0xfe])),
hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)),
}));
@@ -141,6 +141,73 @@ describe('IdentityService', () => {
}
});
it('retains legacy member identities and refreshes only damaged cards across restarts', async () => {
const dbPath = tempDbPath('legacy-card');
const member = makeMember(33333, 'u_member', 'placeholder');
const other = makeMember(44444, 'u_other', 'ordinary');
const seed = new IdentityService(SELF_UIN, dbPath);
seed.rememberGroups([makeGroup()]);
seed.rememberGroupMembers(GROUP_ID, [member, other]);
await seed.close();
// Persisted bytes from #646 after the old text normalization stripped the envelope prefix.
const damaged = Buffer.concat([
Buffer.from('1209', 'hex'),
Buffer.from('三字名'),
Buffer.from('0a090a0724c3bfc48011221000', 'hex'),
]);
const sql = new DatabaseSync(dbPath);
try {
sql.prepare('UPDATE group_members SET card = CAST(? AS TEXT) WHERE uin = ?').run(
damaged,
member.uin,
);
} finally {
sql.close();
}
const stale = new IdentityService(SELF_UIN, dbPath);
try {
await stale.initialization;
const cached = stale.findGroupMember(GROUP_ID, member.uin)!;
expect(cached).toMatchObject({ card: undefined, uid: member.uid, isRobot: false });
expect(stale.findGroupMember(GROUP_ID, other.uin)?.card).toBe('ordinary');
stale.updateGroupMember(GROUP_ID, { ...cached, role: 'admin' });
} finally {
await stale.close();
}
const refreshed = new IdentityService(SELF_UIN, dbPath);
try {
await refreshed.initialization;
expect(refreshed.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
card: undefined,
role: 'admin',
});
refreshed.rememberGroupMembers(GROUP_ID, [
{ ...member, role: 'admin', card: ' 三字名 ' },
other,
]);
} finally {
await refreshed.close();
}
const restored = new IdentityService(SELF_UIN, dbPath);
try {
await restored.initialization;
expect(restored.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
card: ' 三字名 ',
role: 'admin',
});
expect(restored.findGroupMember(GROUP_ID, other.uin)?.card).toBe('ordinary');
} finally {
await restored.close();
}
});
it('persists group member robot classification across restarts', async () => {
const dbPath = tempDbPath('persist-robot');
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { Hono } from 'hono';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { registerStaticFrontend } from '../src/webui/static-frontend';
@@ -44,4 +44,35 @@ describe('runtime target document delivery', () => {
expect((await app.request(url)).status).toBe(404);
}
});
it('does not serve a protected static path through a second percent decode', async () => {
mkdirSync(path.join(root, 'admin'));
writeFileSync(path.join(root, 'admin', 'private.txt'), 'protected fixture');
const app = new Hono();
app.use('/admin/*', async (c) => c.text('unauthorized', 401));
registerStaticFrontend(app, root, null);
for (const url of ['/admin/private.txt', '/%61dmin/private.txt']) {
const response = await app.request(url);
expect(response.status).toBe(401);
expect(await response.text()).toBe('unauthorized');
}
// The router sees /%61dmin; decoding again would reach /admin
// after the middleware for that prefix has already been skipped.
const response = await app.request('/%%36%31dmin/private.txt');
expect(await response.text()).toBe(html);
});
it.each(['hello world.js', '图标.js'])(
'still serves ordinarily encoded asset names: %s',
async (filename) => {
writeFileSync(path.join(root, filename), 'window.encodedAsset = true;');
const app = new Hono();
registerStaticFrontend(app, root, null);
const response = await app.request(`/${encodeURIComponent(filename)}`);
expect(response.status).toBe(200);
expect(await response.text()).toBe('window.encodedAsset = true;');
},
);
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "2.3.0",
"version": "2.4.2",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
+661 -56
View File
@@ -6173,7 +6173,7 @@
"name": "get_friend_list",
"aliases": [],
"summary": "获取好友列表",
"returns": "好友列表数组,每项含 QQ 号、昵称与备注。",
"returns": "好友列表,包含账号、昵称、备注及回包已有的公开资料;with_profile=true 时主动补查,失败会报错。未返回的资料省略,零、空字符串和 false 保留。",
"returnsSchema": {
"type": "array",
"items": {
@@ -6190,6 +6190,171 @@
"remark": {
"type": "string",
"description": "好友备注"
},
"category_id": {
"type": "integer",
"description": "好友分组编号,有来源时返回"
},
"long_nick": {
"type": "string",
"description": "个性签名"
},
"sex": {
"type": "string",
"enum": [
"male",
"female",
"unknown"
],
"description": "性别"
},
"age": {
"type": "integer",
"description": "年龄"
},
"level": {
"type": "integer",
"description": "QQ 等级"
},
"birthday_year": {
"type": "integer",
"description": "生日年份,未公开时省略"
},
"birthday_month": {
"type": "integer",
"description": "生日月份(1-12)"
},
"birthday_day": {
"type": "integer",
"description": "生日日期(1-31)"
},
"phone_num": {
"type": "string",
"description": "资料卡公开的电话号码"
},
"email": {
"type": "string",
"description": "资料卡公开的邮箱"
},
"country": {
"type": "string",
"description": "国家"
},
"province": {
"type": "string",
"description": "省份"
},
"city": {
"type": "string",
"description": "城市"
},
"college": {
"type": "string",
"description": "学校"
},
"is_qq_vip": {
"type": "boolean",
"description": "普通会员状态"
},
"is_vip": {
"type": "boolean",
"description": "超级会员状态,兼容已有接口"
},
"is_years_vip": {
"type": "boolean",
"description": "年费会员状态"
},
"vip_level": {
"type": "integer",
"description": "会员等级"
},
"privilege_icons": {
"type": "object",
"description": "业务图标;未返回该资料时省略整个字段,空列表表示没有该类图标",
"properties": {
"jump_url": {
"type": "string",
"description": "业务列表跳转地址"
},
"open": {
"type": "array",
"description": "已开通业务",
"items": {
"type": "object",
"properties": {
"type": {
"type": "integer",
"description": "业务类型"
},
"level": {
"type": "integer",
"description": "业务等级"
},
"flag": {
"type": "integer",
"description": "服务端业务标志"
},
"is_big": {
"type": "integer",
"description": "服务端大图标标志"
},
"jump_url": {
"type": "string",
"description": "业务跳转地址"
},
"icon_url": {
"type": "string",
"description": "普通图标地址"
},
"deluxe_icon_url": {
"type": "string",
"description": "高级图标地址,可与普通图标同时存在"
}
}
}
},
"closed": {
"type": "array",
"description": "未开通业务",
"items": {
"type": "object",
"properties": {
"type": {
"type": "integer",
"description": "业务类型"
},
"level": {
"type": "integer",
"description": "业务等级"
},
"flag": {
"type": "integer",
"description": "服务端业务标志"
},
"is_big": {
"type": "integer",
"description": "服务端大图标标志"
},
"jump_url": {
"type": "string",
"description": "业务跳转地址"
},
"icon_url": {
"type": "string",
"description": "普通图标地址"
},
"deluxe_icon_url": {
"type": "string",
"description": "高级图标地址,可与普通图标同时存在"
}
}
}
}
},
"required": [
"open",
"closed"
]
}
},
"required": [
@@ -6206,11 +6371,28 @@
}
],
"readOnly": true,
"params": [],
"params": [
{
"name": "with_profile",
"type": "bool",
"required": false,
"schema": {
"type": "boolean"
},
"default": false,
"desc": "主动补查好友公开资料,按账号缓存五分钟;大列表可能耗时较长"
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {},
"properties": {
"with_profile": {
"type": "boolean",
"description": "主动补查好友公开资料,按账号缓存五分钟;大列表可能耗时较长",
"default": false
}
},
"additionalProperties": true
},
"category": "好友"
@@ -6339,6 +6521,10 @@
}
},
"additionalProperties": true
},
"auto_reply": {
"const": true,
"description": "仅当 QQ 标记该私聊消息为自动回复时提供"
}
},
"additionalProperties": true
@@ -6440,7 +6626,7 @@
"name": "get_friends_with_category",
"aliases": [],
"summary": "获取分组好友列表",
"returns": "好友分组数组;每组包含 categoryId、categoryName、categoryMbCount 和 buddyList。",
"returns": "好友分组数组;buddyList 与 get_friend_list 使用相同资料字段。默认只使用列表回包,with_profile=true 主动补查,失败会报错;未返回的资料省略。",
"returnsSchema": {
"type": "array",
"description": "带分组的好友列表",
@@ -6467,15 +6653,180 @@
"properties": {
"user_id": {
"type": "integer",
"description": "QQ 号"
"description": "好友 QQ 号"
},
"nickname": {
"type": "string",
"description": "昵称"
"description": "好友昵称"
},
"remark": {
"type": "string",
"description": "好友备注"
},
"category_id": {
"type": "integer",
"description": "好友分组编号,有来源时返回"
},
"long_nick": {
"type": "string",
"description": "个性签名"
},
"sex": {
"type": "string",
"enum": [
"male",
"female",
"unknown"
],
"description": "性别"
},
"age": {
"type": "integer",
"description": "年龄"
},
"level": {
"type": "integer",
"description": "QQ 等级"
},
"birthday_year": {
"type": "integer",
"description": "生日年份,未公开时省略"
},
"birthday_month": {
"type": "integer",
"description": "生日月份(1-12)"
},
"birthday_day": {
"type": "integer",
"description": "生日日期(1-31)"
},
"phone_num": {
"type": "string",
"description": "资料卡公开的电话号码"
},
"email": {
"type": "string",
"description": "资料卡公开的邮箱"
},
"country": {
"type": "string",
"description": "国家"
},
"province": {
"type": "string",
"description": "省份"
},
"city": {
"type": "string",
"description": "城市"
},
"college": {
"type": "string",
"description": "学校"
},
"is_qq_vip": {
"type": "boolean",
"description": "普通会员状态"
},
"is_vip": {
"type": "boolean",
"description": "超级会员状态,兼容已有接口"
},
"is_years_vip": {
"type": "boolean",
"description": "年费会员状态"
},
"vip_level": {
"type": "integer",
"description": "会员等级"
},
"privilege_icons": {
"type": "object",
"description": "业务图标;未返回该资料时省略整个字段,空列表表示没有该类图标",
"properties": {
"jump_url": {
"type": "string",
"description": "业务列表跳转地址"
},
"open": {
"type": "array",
"description": "已开通业务",
"items": {
"type": "object",
"properties": {
"type": {
"type": "integer",
"description": "业务类型"
},
"level": {
"type": "integer",
"description": "业务等级"
},
"flag": {
"type": "integer",
"description": "服务端业务标志"
},
"is_big": {
"type": "integer",
"description": "服务端大图标标志"
},
"jump_url": {
"type": "string",
"description": "业务跳转地址"
},
"icon_url": {
"type": "string",
"description": "普通图标地址"
},
"deluxe_icon_url": {
"type": "string",
"description": "高级图标地址,可与普通图标同时存在"
}
}
}
},
"closed": {
"type": "array",
"description": "未开通业务",
"items": {
"type": "object",
"properties": {
"type": {
"type": "integer",
"description": "业务类型"
},
"level": {
"type": "integer",
"description": "业务等级"
},
"flag": {
"type": "integer",
"description": "服务端业务标志"
},
"is_big": {
"type": "integer",
"description": "服务端大图标标志"
},
"jump_url": {
"type": "string",
"description": "业务跳转地址"
},
"icon_url": {
"type": "string",
"description": "普通图标地址"
},
"deluxe_icon_url": {
"type": "string",
"description": "高级图标地址,可与普通图标同时存在"
}
}
}
}
},
"required": [
"open",
"closed"
]
}
},
"required": [
@@ -6501,11 +6852,28 @@
}
],
"readOnly": true,
"params": [],
"params": [
{
"name": "with_profile",
"type": "bool",
"required": false,
"schema": {
"type": "boolean"
},
"default": false,
"desc": "主动补查好友公开资料,按账号缓存五分钟;大列表可能耗时较长"
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {},
"properties": {
"with_profile": {
"type": "boolean",
"description": "主动补查好友公开资料,按账号缓存五分钟;大列表可能耗时较长",
"default": false
}
},
"additionalProperties": true
},
"category": "扩展"
@@ -9635,7 +10003,7 @@
"name": "get_group_system_msg",
"aliases": [],
"summary": "获取群系统消息",
"returns": "群系统消息数组,可按群号或未处理状态过滤。",
"returns": "群系统消息数组,分别提供入群者、邀请人和处理者,可按群号或未处理状态过滤。身份为 0 时须查看状态;未知不代表不存在邀请人。",
"returnsSchema": {
"type": "array",
"items": {
@@ -9655,20 +10023,60 @@
},
"requester_uin": {
"type": "integer",
"description": "申请人 QQ 号"
"description": "请求发起人 QQ 号;邀请登录账号入群时表示邀请人"
},
"requester_nick": {
"type": "string",
"description": "申请人昵称"
"description": "请求发起人昵称"
},
"target_uin": {
"type": "integer",
"description": "申请或被邀请入群者 QQ 号,未知时为 0"
},
"target_nick": {
"type": "string",
"description": "入群者昵称"
},
"target_status": {
"type": "string",
"enum": [
"known",
"unknown"
],
"description": "入群者 QQ 号是否已知"
},
"invitor_uin": {
"type": "integer",
"description": "邀请人 QQ 号,无邀请时为 0"
"description": "邀请人 QQ 号,未知时为 0;不能据此认定没有邀请人"
},
"invitor_nick": {
"type": "string",
"description": "邀请人昵称"
},
"invitor_status": {
"type": "string",
"enum": [
"known",
"unknown"
],
"description": "邀请人 QQ 号是否已知;缺失信息为 unknown"
},
"operator_uin": {
"type": "integer",
"description": "处理该申请的操作者 QQ 号,未知时为 0"
},
"operator_nick": {
"type": "string",
"description": "处理者昵称"
},
"operator_status": {
"type": "string",
"enum": [
"known",
"unknown"
],
"description": "处理者 QQ 号是否已知;已知不代表审批通过"
},
"message": {
"type": "string",
"description": "验证留言"
@@ -9688,8 +10096,15 @@
"request_id",
"requester_uin",
"requester_nick",
"target_uin",
"target_nick",
"target_status",
"invitor_uin",
"invitor_nick",
"invitor_status",
"operator_uin",
"operator_nick",
"operator_status",
"message",
"checked",
"flag"
@@ -10346,6 +10761,10 @@
}
},
"additionalProperties": true
},
"auto_reply": {
"const": true,
"description": "仅当 QQ 标记该私聊消息为自动回复时提供"
}
},
"additionalProperties": true
@@ -11241,6 +11660,76 @@
},
"category": "群相册"
},
{
"name": "get_qzone_feed_detail",
"aliases": [],
"summary": "按说说 tid 读取完整空间动态,可用于生成分享卡片",
"returns": "完整动态及上游详情字段。feed 保留图片、视频、分享信息和未知字段,可直接用于 get_qzone_share_ark;attach_info 保留上游评论游标,不自动翻页。",
"returnsSchema": {
"type": "object",
"additionalProperties": true,
"properties": {
"feed": {
"type": "object",
"additionalProperties": true,
"description": "去除上游包装后的完整动态,可原样传给 get_qzone_share_ark"
},
"attach_info": {
"type": [
"string",
"null"
],
"description": "上游评论续页游标,未提供时为 null;不保证评论及回复完整"
}
},
"required": [
"feed",
"attach_info"
]
},
"examples": [
{
"summary": "按说说编号获取完整动态",
"params": {
"tid": "1127000000f1536501000000"
},
"notes": "将示例 tid 替换为 get_qzone_msg_list 或 send_qzone_msg 返回的 24 位十六进制说说编号。把结果的 feed 原样传给 get_qzone_share_ark;读取和分享均受空间权限限制。"
}
],
"readOnly": true,
"params": [
{
"name": "tid",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1,
"maxLength": 24
},
"desc": "24 位十六进制说说编号"
}
],
"invariants": [
"tid must be a 24-character hexadecimal post ID"
],
"inputSchema": {
"type": "object",
"properties": {
"tid": {
"type": "string",
"minLength": 1,
"maxLength": 24,
"description": "24 位十六进制说说编号"
}
},
"required": [
"tid"
],
"additionalProperties": true
},
"category": "空间"
},
{
"name": "get_qzone_feeds",
"aliases": [],
@@ -12385,7 +12874,7 @@
}
}
},
"notes": "feed 原样取自 get_qzone_home_feeds 或 get_qzone_public_feeds。分享链接可能允许未登录者访问并包含作者 QQ 号;如 requires_confirmation=true,发送前展示 notice 并取得确认。将 ark 原文作为 JSON 消息发送,不要修改卡片内容。"
"notes": "feed 原样取自 get_qzone_feed_detail 的 feed,或 get_qzone_home_feeds / get_qzone_public_feeds 的 feeds 条目。分享链接可能允许未登录者访问并包含作者 QQ 号;如 requires_confirmation=true,发送前展示 notice 并取得确认。将 ark 原文作为 JSON 消息发送,不要修改卡片内容。"
}
],
"readOnly": false,
@@ -12398,7 +12887,7 @@
"type": "object",
"additionalProperties": true
},
"desc": "主页或推荐列表返回的完整动态,保留所有原始字段"
"desc": "主页、详情或推荐列表返回的完整动态,保留所有原始字段"
}
],
"invariants": [],
@@ -12408,7 +12897,7 @@
"feed": {
"type": "object",
"additionalProperties": true,
"description": "主页或推荐列表返回的完整动态,保留所有原始字段"
"description": "主页、详情或推荐列表返回的完整动态,保留所有原始字段"
}
},
"required": [
@@ -12807,6 +13296,162 @@
"returnsSchema": {
"type": "object",
"properties": {
"long_nick": {
"type": "string",
"description": "个性签名"
},
"sex": {
"type": "string",
"description": "性别(male/female/unknown)"
},
"age": {
"type": "integer",
"description": "年龄"
},
"level": {
"type": "integer",
"description": "QQ 等级,同 qq_level(仅查到资料时返回)"
},
"birthday_year": {
"type": "integer",
"description": "生日年份,兼容 NapCat;未公开或不可用时省略"
},
"birthday_month": {
"type": "integer",
"description": "生日月份(1-12),兼容 NapCat;不可用时省略"
},
"birthday_day": {
"type": "integer",
"description": "生日日期(1-31),兼容 NapCat;不可用时省略"
},
"phone_num": {
"type": "string",
"description": "资料卡公开的电话号码"
},
"email": {
"type": "string",
"description": "资料卡公开的邮箱"
},
"country": {
"type": "string",
"description": "国家"
},
"province": {
"type": "string",
"description": "省份"
},
"city": {
"type": "string",
"description": "城市"
},
"college": {
"type": "string",
"description": "学校"
},
"is_qq_vip": {
"type": "boolean",
"description": "普通会员状态"
},
"is_vip": {
"type": "boolean",
"description": "超级会员状态,兼容 NapCat;不可用时省略"
},
"is_years_vip": {
"type": "boolean",
"description": "年费会员状态,不可用时省略"
},
"vip_level": {
"type": "integer",
"description": "会员等级,不可用时省略"
},
"privilege_icons": {
"type": "object",
"description": "业务图标;未返回该资料时省略整个字段,空列表表示没有该类图标",
"properties": {
"jump_url": {
"type": "string",
"description": "业务列表跳转地址"
},
"open": {
"type": "array",
"description": "已开通业务",
"items": {
"type": "object",
"properties": {
"type": {
"type": "integer",
"description": "业务类型"
},
"level": {
"type": "integer",
"description": "业务等级"
},
"flag": {
"type": "integer",
"description": "服务端业务标志"
},
"is_big": {
"type": "integer",
"description": "服务端大图标标志"
},
"jump_url": {
"type": "string",
"description": "业务跳转地址"
},
"icon_url": {
"type": "string",
"description": "普通图标地址"
},
"deluxe_icon_url": {
"type": "string",
"description": "高级图标地址,可与普通图标同时存在"
}
}
}
},
"closed": {
"type": "array",
"description": "未开通业务",
"items": {
"type": "object",
"properties": {
"type": {
"type": "integer",
"description": "业务类型"
},
"level": {
"type": "integer",
"description": "业务等级"
},
"flag": {
"type": "integer",
"description": "服务端业务标志"
},
"is_big": {
"type": "integer",
"description": "服务端大图标标志"
},
"jump_url": {
"type": "string",
"description": "业务跳转地址"
},
"icon_url": {
"type": "string",
"description": "普通图标地址"
},
"deluxe_icon_url": {
"type": "string",
"description": "高级图标地址,可与普通图标同时存在"
}
}
}
}
},
"required": [
"open",
"closed"
]
},
"user_id": {
"type": "integer",
"description": "QQ 号"
@@ -12827,18 +13472,6 @@
"type": "string",
"description": "好友备注;非好友或未设置时为空字符串"
},
"sex": {
"type": "string",
"description": "性别(male/female/unknown)"
},
"age": {
"type": "integer",
"description": "年龄"
},
"long_nick": {
"type": "string",
"description": "个性签名"
},
"qq_level": {
"type": "integer",
"description": "QQ 等级(仅查到资料时返回)"
@@ -12851,34 +13484,6 @@
"type": "integer",
"description": "注册时间戳(秒),不可用时省略"
},
"birthday_year": {
"type": "integer",
"description": "生日年份,兼容 NapCat;未公开或不可用时省略"
},
"birthday_month": {
"type": "integer",
"description": "生日月份(1-12),兼容 NapCat;不可用时省略"
},
"birthday_day": {
"type": "integer",
"description": "生日日期(1-31),兼容 NapCat;不可用时省略"
},
"is_vip": {
"type": "boolean",
"description": "超级会员状态,兼容 NapCat;不可用时省略"
},
"is_years_vip": {
"type": "boolean",
"description": "年费会员状态,不可用时省略"
},
"vip_level": {
"type": "integer",
"description": "会员等级,不可用时省略"
},
"level": {
"type": "integer",
"description": "QQ 等级,同 qq_level(仅查到资料时返回)"
},
"status": {
"type": "integer",
"description": "在线状态码"
@@ -20953,7 +21558,7 @@
},
{
"category": "空间",
"count": 28
"count": 29
},
{
"category": "系统表情",
+661 -56
View File
@@ -6176,7 +6176,7 @@ export const ACTIONS: CatalogAction[] = [
"name": "get_friend_list",
"aliases": [],
"summary": "获取好友列表",
"returns": "好友列表数组,每项含 QQ 号、昵称与备注。",
"returns": "好友列表,包含账号、昵称、备注及回包已有的公开资料;with_profile=true 时主动补查,失败会报错。未返回的资料省略,零、空字符串和 false 保留。",
"returnsSchema": {
"type": "array",
"items": {
@@ -6193,6 +6193,171 @@ export const ACTIONS: CatalogAction[] = [
"remark": {
"type": "string",
"description": "好友备注"
},
"category_id": {
"type": "integer",
"description": "好友分组编号,有来源时返回"
},
"long_nick": {
"type": "string",
"description": "个性签名"
},
"sex": {
"type": "string",
"enum": [
"male",
"female",
"unknown"
],
"description": "性别"
},
"age": {
"type": "integer",
"description": "年龄"
},
"level": {
"type": "integer",
"description": "QQ 等级"
},
"birthday_year": {
"type": "integer",
"description": "生日年份,未公开时省略"
},
"birthday_month": {
"type": "integer",
"description": "生日月份(1-12)"
},
"birthday_day": {
"type": "integer",
"description": "生日日期(1-31)"
},
"phone_num": {
"type": "string",
"description": "资料卡公开的电话号码"
},
"email": {
"type": "string",
"description": "资料卡公开的邮箱"
},
"country": {
"type": "string",
"description": "国家"
},
"province": {
"type": "string",
"description": "省份"
},
"city": {
"type": "string",
"description": "城市"
},
"college": {
"type": "string",
"description": "学校"
},
"is_qq_vip": {
"type": "boolean",
"description": "普通会员状态"
},
"is_vip": {
"type": "boolean",
"description": "超级会员状态,兼容已有接口"
},
"is_years_vip": {
"type": "boolean",
"description": "年费会员状态"
},
"vip_level": {
"type": "integer",
"description": "会员等级"
},
"privilege_icons": {
"type": "object",
"description": "业务图标;未返回该资料时省略整个字段,空列表表示没有该类图标",
"properties": {
"jump_url": {
"type": "string",
"description": "业务列表跳转地址"
},
"open": {
"type": "array",
"description": "已开通业务",
"items": {
"type": "object",
"properties": {
"type": {
"type": "integer",
"description": "业务类型"
},
"level": {
"type": "integer",
"description": "业务等级"
},
"flag": {
"type": "integer",
"description": "服务端业务标志"
},
"is_big": {
"type": "integer",
"description": "服务端大图标标志"
},
"jump_url": {
"type": "string",
"description": "业务跳转地址"
},
"icon_url": {
"type": "string",
"description": "普通图标地址"
},
"deluxe_icon_url": {
"type": "string",
"description": "高级图标地址,可与普通图标同时存在"
}
}
}
},
"closed": {
"type": "array",
"description": "未开通业务",
"items": {
"type": "object",
"properties": {
"type": {
"type": "integer",
"description": "业务类型"
},
"level": {
"type": "integer",
"description": "业务等级"
},
"flag": {
"type": "integer",
"description": "服务端业务标志"
},
"is_big": {
"type": "integer",
"description": "服务端大图标标志"
},
"jump_url": {
"type": "string",
"description": "业务跳转地址"
},
"icon_url": {
"type": "string",
"description": "普通图标地址"
},
"deluxe_icon_url": {
"type": "string",
"description": "高级图标地址,可与普通图标同时存在"
}
}
}
}
},
"required": [
"open",
"closed"
]
}
},
"required": [
@@ -6209,11 +6374,28 @@ export const ACTIONS: CatalogAction[] = [
}
],
"readOnly": true,
"params": [],
"params": [
{
"name": "with_profile",
"type": "bool",
"required": false,
"schema": {
"type": "boolean"
},
"default": false,
"desc": "主动补查好友公开资料,按账号缓存五分钟;大列表可能耗时较长"
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {},
"properties": {
"with_profile": {
"type": "boolean",
"description": "主动补查好友公开资料,按账号缓存五分钟;大列表可能耗时较长",
"default": false
}
},
"additionalProperties": true
},
"category": "好友"
@@ -6342,6 +6524,10 @@ export const ACTIONS: CatalogAction[] = [
}
},
"additionalProperties": true
},
"auto_reply": {
"const": true,
"description": "仅当 QQ 标记该私聊消息为自动回复时提供"
}
},
"additionalProperties": true
@@ -6443,7 +6629,7 @@ export const ACTIONS: CatalogAction[] = [
"name": "get_friends_with_category",
"aliases": [],
"summary": "获取分组好友列表",
"returns": "好友分组数组;每组包含 categoryId、categoryName、categoryMbCount 和 buddyList。",
"returns": "好友分组数组;buddyList 与 get_friend_list 使用相同资料字段。默认只使用列表回包,with_profile=true 主动补查,失败会报错;未返回的资料省略。",
"returnsSchema": {
"type": "array",
"description": "带分组的好友列表",
@@ -6470,15 +6656,180 @@ export const ACTIONS: CatalogAction[] = [
"properties": {
"user_id": {
"type": "integer",
"description": "QQ 号"
"description": "好友 QQ 号"
},
"nickname": {
"type": "string",
"description": "昵称"
"description": "好友昵称"
},
"remark": {
"type": "string",
"description": "好友备注"
},
"category_id": {
"type": "integer",
"description": "好友分组编号,有来源时返回"
},
"long_nick": {
"type": "string",
"description": "个性签名"
},
"sex": {
"type": "string",
"enum": [
"male",
"female",
"unknown"
],
"description": "性别"
},
"age": {
"type": "integer",
"description": "年龄"
},
"level": {
"type": "integer",
"description": "QQ 等级"
},
"birthday_year": {
"type": "integer",
"description": "生日年份,未公开时省略"
},
"birthday_month": {
"type": "integer",
"description": "生日月份(1-12)"
},
"birthday_day": {
"type": "integer",
"description": "生日日期(1-31)"
},
"phone_num": {
"type": "string",
"description": "资料卡公开的电话号码"
},
"email": {
"type": "string",
"description": "资料卡公开的邮箱"
},
"country": {
"type": "string",
"description": "国家"
},
"province": {
"type": "string",
"description": "省份"
},
"city": {
"type": "string",
"description": "城市"
},
"college": {
"type": "string",
"description": "学校"
},
"is_qq_vip": {
"type": "boolean",
"description": "普通会员状态"
},
"is_vip": {
"type": "boolean",
"description": "超级会员状态,兼容已有接口"
},
"is_years_vip": {
"type": "boolean",
"description": "年费会员状态"
},
"vip_level": {
"type": "integer",
"description": "会员等级"
},
"privilege_icons": {
"type": "object",
"description": "业务图标;未返回该资料时省略整个字段,空列表表示没有该类图标",
"properties": {
"jump_url": {
"type": "string",
"description": "业务列表跳转地址"
},
"open": {
"type": "array",
"description": "已开通业务",
"items": {
"type": "object",
"properties": {
"type": {
"type": "integer",
"description": "业务类型"
},
"level": {
"type": "integer",
"description": "业务等级"
},
"flag": {
"type": "integer",
"description": "服务端业务标志"
},
"is_big": {
"type": "integer",
"description": "服务端大图标标志"
},
"jump_url": {
"type": "string",
"description": "业务跳转地址"
},
"icon_url": {
"type": "string",
"description": "普通图标地址"
},
"deluxe_icon_url": {
"type": "string",
"description": "高级图标地址,可与普通图标同时存在"
}
}
}
},
"closed": {
"type": "array",
"description": "未开通业务",
"items": {
"type": "object",
"properties": {
"type": {
"type": "integer",
"description": "业务类型"
},
"level": {
"type": "integer",
"description": "业务等级"
},
"flag": {
"type": "integer",
"description": "服务端业务标志"
},
"is_big": {
"type": "integer",
"description": "服务端大图标标志"
},
"jump_url": {
"type": "string",
"description": "业务跳转地址"
},
"icon_url": {
"type": "string",
"description": "普通图标地址"
},
"deluxe_icon_url": {
"type": "string",
"description": "高级图标地址,可与普通图标同时存在"
}
}
}
}
},
"required": [
"open",
"closed"
]
}
},
"required": [
@@ -6504,11 +6855,28 @@ export const ACTIONS: CatalogAction[] = [
}
],
"readOnly": true,
"params": [],
"params": [
{
"name": "with_profile",
"type": "bool",
"required": false,
"schema": {
"type": "boolean"
},
"default": false,
"desc": "主动补查好友公开资料,按账号缓存五分钟;大列表可能耗时较长"
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {},
"properties": {
"with_profile": {
"type": "boolean",
"description": "主动补查好友公开资料,按账号缓存五分钟;大列表可能耗时较长",
"default": false
}
},
"additionalProperties": true
},
"category": "扩展"
@@ -9638,7 +10006,7 @@ export const ACTIONS: CatalogAction[] = [
"name": "get_group_system_msg",
"aliases": [],
"summary": "获取群系统消息",
"returns": "群系统消息数组,可按群号或未处理状态过滤。",
"returns": "群系统消息数组,分别提供入群者、邀请人和处理者,可按群号或未处理状态过滤。身份为 0 时须查看状态;未知不代表不存在邀请人。",
"returnsSchema": {
"type": "array",
"items": {
@@ -9658,20 +10026,60 @@ export const ACTIONS: CatalogAction[] = [
},
"requester_uin": {
"type": "integer",
"description": "申请人 QQ 号"
"description": "请求发起人 QQ 号;邀请登录账号入群时表示邀请人"
},
"requester_nick": {
"type": "string",
"description": "申请人昵称"
"description": "请求发起人昵称"
},
"target_uin": {
"type": "integer",
"description": "申请或被邀请入群者 QQ 号,未知时为 0"
},
"target_nick": {
"type": "string",
"description": "入群者昵称"
},
"target_status": {
"type": "string",
"enum": [
"known",
"unknown"
],
"description": "入群者 QQ 号是否已知"
},
"invitor_uin": {
"type": "integer",
"description": "邀请人 QQ 号,无邀请时为 0"
"description": "邀请人 QQ 号,未知时为 0;不能据此认定没有邀请人"
},
"invitor_nick": {
"type": "string",
"description": "邀请人昵称"
},
"invitor_status": {
"type": "string",
"enum": [
"known",
"unknown"
],
"description": "邀请人 QQ 号是否已知;缺失信息为 unknown"
},
"operator_uin": {
"type": "integer",
"description": "处理该申请的操作者 QQ 号,未知时为 0"
},
"operator_nick": {
"type": "string",
"description": "处理者昵称"
},
"operator_status": {
"type": "string",
"enum": [
"known",
"unknown"
],
"description": "处理者 QQ 号是否已知;已知不代表审批通过"
},
"message": {
"type": "string",
"description": "验证留言"
@@ -9691,8 +10099,15 @@ export const ACTIONS: CatalogAction[] = [
"request_id",
"requester_uin",
"requester_nick",
"target_uin",
"target_nick",
"target_status",
"invitor_uin",
"invitor_nick",
"invitor_status",
"operator_uin",
"operator_nick",
"operator_status",
"message",
"checked",
"flag"
@@ -10349,6 +10764,10 @@ export const ACTIONS: CatalogAction[] = [
}
},
"additionalProperties": true
},
"auto_reply": {
"const": true,
"description": "仅当 QQ 标记该私聊消息为自动回复时提供"
}
},
"additionalProperties": true
@@ -11244,6 +11663,76 @@ export const ACTIONS: CatalogAction[] = [
},
"category": "群相册"
},
{
"name": "get_qzone_feed_detail",
"aliases": [],
"summary": "按说说 tid 读取完整空间动态,可用于生成分享卡片",
"returns": "完整动态及上游详情字段。feed 保留图片、视频、分享信息和未知字段,可直接用于 get_qzone_share_ark;attach_info 保留上游评论游标,不自动翻页。",
"returnsSchema": {
"type": "object",
"additionalProperties": true,
"properties": {
"feed": {
"type": "object",
"additionalProperties": true,
"description": "去除上游包装后的完整动态,可原样传给 get_qzone_share_ark"
},
"attach_info": {
"type": [
"string",
"null"
],
"description": "上游评论续页游标,未提供时为 null;不保证评论及回复完整"
}
},
"required": [
"feed",
"attach_info"
]
},
"examples": [
{
"summary": "按说说编号获取完整动态",
"params": {
"tid": "1127000000f1536501000000"
},
"notes": "将示例 tid 替换为 get_qzone_msg_list 或 send_qzone_msg 返回的 24 位十六进制说说编号。把结果的 feed 原样传给 get_qzone_share_ark;读取和分享均受空间权限限制。"
}
],
"readOnly": true,
"params": [
{
"name": "tid",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1,
"maxLength": 24
},
"desc": "24 位十六进制说说编号"
}
],
"invariants": [
"tid must be a 24-character hexadecimal post ID"
],
"inputSchema": {
"type": "object",
"properties": {
"tid": {
"type": "string",
"minLength": 1,
"maxLength": 24,
"description": "24 位十六进制说说编号"
}
},
"required": [
"tid"
],
"additionalProperties": true
},
"category": "空间"
},
{
"name": "get_qzone_feeds",
"aliases": [],
@@ -12388,7 +12877,7 @@ export const ACTIONS: CatalogAction[] = [
}
}
},
"notes": "feed 原样取自 get_qzone_home_feeds 或 get_qzone_public_feeds。分享链接可能允许未登录者访问并包含作者 QQ 号;如 requires_confirmation=true,发送前展示 notice 并取得确认。将 ark 原文作为 JSON 消息发送,不要修改卡片内容。"
"notes": "feed 原样取自 get_qzone_feed_detail 的 feed,或 get_qzone_home_feeds / get_qzone_public_feeds 的 feeds 条目。分享链接可能允许未登录者访问并包含作者 QQ 号;如 requires_confirmation=true,发送前展示 notice 并取得确认。将 ark 原文作为 JSON 消息发送,不要修改卡片内容。"
}
],
"readOnly": false,
@@ -12401,7 +12890,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "object",
"additionalProperties": true
},
"desc": "主页或推荐列表返回的完整动态,保留所有原始字段"
"desc": "主页、详情或推荐列表返回的完整动态,保留所有原始字段"
}
],
"invariants": [],
@@ -12411,7 +12900,7 @@ export const ACTIONS: CatalogAction[] = [
"feed": {
"type": "object",
"additionalProperties": true,
"description": "主页或推荐列表返回的完整动态,保留所有原始字段"
"description": "主页、详情或推荐列表返回的完整动态,保留所有原始字段"
}
},
"required": [
@@ -12810,6 +13299,162 @@ export const ACTIONS: CatalogAction[] = [
"returnsSchema": {
"type": "object",
"properties": {
"long_nick": {
"type": "string",
"description": "个性签名"
},
"sex": {
"type": "string",
"description": "性别(male/female/unknown)"
},
"age": {
"type": "integer",
"description": "年龄"
},
"level": {
"type": "integer",
"description": "QQ 等级,同 qq_level(仅查到资料时返回)"
},
"birthday_year": {
"type": "integer",
"description": "生日年份,兼容 NapCat;未公开或不可用时省略"
},
"birthday_month": {
"type": "integer",
"description": "生日月份(1-12),兼容 NapCat;不可用时省略"
},
"birthday_day": {
"type": "integer",
"description": "生日日期(1-31),兼容 NapCat;不可用时省略"
},
"phone_num": {
"type": "string",
"description": "资料卡公开的电话号码"
},
"email": {
"type": "string",
"description": "资料卡公开的邮箱"
},
"country": {
"type": "string",
"description": "国家"
},
"province": {
"type": "string",
"description": "省份"
},
"city": {
"type": "string",
"description": "城市"
},
"college": {
"type": "string",
"description": "学校"
},
"is_qq_vip": {
"type": "boolean",
"description": "普通会员状态"
},
"is_vip": {
"type": "boolean",
"description": "超级会员状态,兼容 NapCat;不可用时省略"
},
"is_years_vip": {
"type": "boolean",
"description": "年费会员状态,不可用时省略"
},
"vip_level": {
"type": "integer",
"description": "会员等级,不可用时省略"
},
"privilege_icons": {
"type": "object",
"description": "业务图标;未返回该资料时省略整个字段,空列表表示没有该类图标",
"properties": {
"jump_url": {
"type": "string",
"description": "业务列表跳转地址"
},
"open": {
"type": "array",
"description": "已开通业务",
"items": {
"type": "object",
"properties": {
"type": {
"type": "integer",
"description": "业务类型"
},
"level": {
"type": "integer",
"description": "业务等级"
},
"flag": {
"type": "integer",
"description": "服务端业务标志"
},
"is_big": {
"type": "integer",
"description": "服务端大图标标志"
},
"jump_url": {
"type": "string",
"description": "业务跳转地址"
},
"icon_url": {
"type": "string",
"description": "普通图标地址"
},
"deluxe_icon_url": {
"type": "string",
"description": "高级图标地址,可与普通图标同时存在"
}
}
}
},
"closed": {
"type": "array",
"description": "未开通业务",
"items": {
"type": "object",
"properties": {
"type": {
"type": "integer",
"description": "业务类型"
},
"level": {
"type": "integer",
"description": "业务等级"
},
"flag": {
"type": "integer",
"description": "服务端业务标志"
},
"is_big": {
"type": "integer",
"description": "服务端大图标标志"
},
"jump_url": {
"type": "string",
"description": "业务跳转地址"
},
"icon_url": {
"type": "string",
"description": "普通图标地址"
},
"deluxe_icon_url": {
"type": "string",
"description": "高级图标地址,可与普通图标同时存在"
}
}
}
}
},
"required": [
"open",
"closed"
]
},
"user_id": {
"type": "integer",
"description": "QQ 号"
@@ -12830,18 +13475,6 @@ export const ACTIONS: CatalogAction[] = [
"type": "string",
"description": "好友备注;非好友或未设置时为空字符串"
},
"sex": {
"type": "string",
"description": "性别(male/female/unknown)"
},
"age": {
"type": "integer",
"description": "年龄"
},
"long_nick": {
"type": "string",
"description": "个性签名"
},
"qq_level": {
"type": "integer",
"description": "QQ 等级(仅查到资料时返回)"
@@ -12854,34 +13487,6 @@ export const ACTIONS: CatalogAction[] = [
"type": "integer",
"description": "注册时间戳(秒),不可用时省略"
},
"birthday_year": {
"type": "integer",
"description": "生日年份,兼容 NapCat;未公开或不可用时省略"
},
"birthday_month": {
"type": "integer",
"description": "生日月份(1-12),兼容 NapCat;不可用时省略"
},
"birthday_day": {
"type": "integer",
"description": "生日日期(1-31),兼容 NapCat;不可用时省略"
},
"is_vip": {
"type": "boolean",
"description": "超级会员状态,兼容 NapCat;不可用时省略"
},
"is_years_vip": {
"type": "boolean",
"description": "年费会员状态,不可用时省略"
},
"vip_level": {
"type": "integer",
"description": "会员等级,不可用时省略"
},
"level": {
"type": "integer",
"description": "QQ 等级,同 qq_level(仅查到资料时返回)"
},
"status": {
"type": "integer",
"description": "在线状态码"
@@ -20957,7 +21562,7 @@ export const CATEGORIES: CatalogCategory[] = [
},
{
"category": "空间",
"count": 28
"count": 29
},
{
"category": "系统表情",
+51
View File
@@ -0,0 +1,51 @@
# Contact profiles
`get_friend_list` and `get_friends_with_category` preserve their existing result
shapes and add optional public profile fields to each friend. By default they
only read the paginated roster: they do not issue a profile request for every
friend. Both accept `with_profile: true` to explicitly query additional details.
Large lists may require a longer client timeout.
Explicit enrichment uses a five-minute cache belonging to the current account,
deduplicates simultaneous queries and limits aggregate profile concurrency to
four. Values already supplied by the roster take precedence, including empty
strings, zero and false. An enrichment failure fails the action after draining
the current batch; it is logged, is not cached and is not automatically retried.
A later call may retry it. The ordinary flat list retains its existing logged
fallback to cached friends when the roster cannot be refreshed.
Friend rows contain `user_id`, `nickname`, `remark`, and `category_id` when
available. Public fields also appear in `get_stranger_info` when QQ supplies them:
| Fields | Meaning |
| --- | --- |
| `long_nick`, `sex`, `age`, `level` | Signature, gender, age and QQ level |
| `birthday_year`, `birthday_month`, `birthday_day` | Birthday; a hidden year is omitted |
| `phone_num`, `email` | Contact details made available by the profile |
| `country`, `province`, `city`, `college` | Location and school |
| `is_qq_vip`, `is_vip`, `is_years_vip`, `vip_level` | Ordinary membership, super membership (existing meaning of `is_vip`), annual membership and level |
| `privilege_icons` | `jump_url` if supplied, plus `open` and `closed` icon lists |
Each privilege entry may contain `type`, `level`, `flag`, `is_big`, `jump_url`,
`icon_url` and `deluxe_icon_url`. The two icon URLs can coexist. Flags retain
their server values; they are not guessed to mean annual or premium membership.
Local downloaded icon paths are not part of the response.
Missing data is omitted rather than replaced with false, zero or an empty list.
An explicitly returned empty icon-list body produces `open: [], closed: []`;
unavailable icon data omits `privilege_icons`. Existing required stranger fields
and aliases retain their earlier defaults. Malformed optional birthdays are
logged without recording their values; malformed text or privilege payloads
fail decoding.
SDK calls keep the existing options argument:
```ts
const friends = await client.getFriendList({ withProfile: true, timeoutMs: 120_000 });
const categories = await client.call('get_friends_with_category', { with_profile: true });
```
The exported `FriendInfo`, `StrangerInfo`, `PublicProfileFields` and
`ProfilePrivilege` types describe these fields. Returned availability depends
on QQ and the account's access; requesting enrichment does not guarantee every
field is present.
+26
View File
@@ -0,0 +1,26 @@
# 群文件发送与临时存储
`upload_group_file` 和 `send_group_msg` 中的文件段默认使用群永久文件空间。
当服务器明确返回容量或文件数量限制时,SnowLuma 会尝试一次临时存储,并在日志中记录这次切换。
临时申请、文件传输或聊天发布失败仍会报错;权限不足、连接失败等其他错误不会触发切换。
临时文件可能过期,不能作为永久保存的替代。
## 消息内容限制
进入临时文件路径时,一条消息只能包含文件或图片段。
含文字、提及、表情等其他内容的混合消息会被拒绝,需要调用方拆成独立消息后再发送。
合并转发按每个节点的内容检查同一规则。
SnowLuma 会在发布聊天消息前检查附件;发现不允许的组合时,不会先发文字、再丢掉附件或文字。
检查之前已完成的其他附件上传不会自动删除。上传成功后如果聊天发布失败,错误仍会保留文件标识。
这不是跨多条消息的事务:开始发布后出现的网络或服务端错误仍可能使前面的消息已经送达。
普通图片加文字仍通过图片消息通道发送,不会因为群永久文件空间不足而转成群文件。
永久文件与文字的现有分开发送方式保持兼容。超大视频按原有规则转成文件后,也适用临时文件的内容限制。
## 文件复用与下载
运行期间上传过的群文件会按账号、群和文件标识保留其存储类型。
同一群中用 `file_id` 再次发送、获取下载链接或生成合并转发时,会使用该存储类型。
`get_group_file_url` 显式传入的 `busid` 仍优先;未提供有效值时,使用当前会话记住的类型,否则沿用永久文件默认值。
上传记录不是持久化目录;重启后获取临时文件链接,应从群文件列表取得对应的 `busid` 并传入。
+55
View File
@@ -0,0 +1,55 @@
# 群邀请与入群身份
成员 A 邀请 B,管理员 C 审批时,邀请人、入群者与处理者是三个独立身份。
不要把 `group_increase.operator_id` 当成邀请人,也不要仅凭 `sub_type: invite` 推断两者相同。
## 入群通知
`group_increase` 保留原有的 `user_id`、`operator_id` 和 `sub_type`,增加:
| 字段 | 含义 |
| --- | --- |
| `invitor_id` | QQ 明确提供的独立邀请人 QQ 号;无法确定时为 `0` |
| `invitor_status` | `known` 表示邀请人 QQ 号已知;`unknown` 表示无法确定 |
部分审批入群推送提供独立邀请人信息,SnowLuma 从该推送读取并解析身份。
二维码分享者与邀请人分开处理;旧式推送、自身入群通知或缺少来源信息的通知保留 `unknown`。
不会按同群、同成员或时间接近程度猜测邀请关系,也不会用操作者填充邀请人。
身份查询失败会留下日志,入群事件仍按现有策略上报,未知邀请人不阻断通知。
## 群申请列表
`get_group_system_msg` 返回的每条记录增加以下字段:
| 字段 | 含义 |
| --- | --- |
| `target_uin`、`target_nick` | 申请或被邀请入群者,始终表示 B |
| `operator_uin`、`operator_nick` | 处理该申请的操作者;审批场景中表示 C |
| `target_status`、`invitor_status`、`operator_status` | 对应 QQ 号为 `known` 或 `unknown` |
原有 `invitor_uin`、`invitor_nick` 表示 A。`requester_uin` 保持兼容:普通申请表示申请人,
邀请登录账号入群的记录则表示邀请人。需要区分三方时,应使用 `target_uin`、`invitor_uin`、`operator_uin`。
QQ 只提供 UID 时会查询对应 QQ 号,查询去重并限制并发;查询错误会返回接口错误,不伪装成空列表。
```json
{
"target_uin": 10002,
"target_status": "known",
"invitor_uin": 10004,
"invitor_status": "known",
"operator_uin": 10003,
"operator_status": "known",
"checked": true
}
```
**`0` 或 `unknown` 不代表“没有邀请人”。** QQ 未提供身份、记录不可见、身份尚未解析等情况均不能证明没有邀请人。
当前已确认的字段不足以对缺失信息可靠作出“无邀请人”的判断,因此不输出这种推断。
同样,`checked: true` 只表示已处理,不代表必然审批通过;`operator_uin` 也可能是拒绝请求的人。
`count` 限制每个收件箱读取的记录数(最多 100);`group_id` 在读取后过滤,
并非查询指定群的完整历史。`only_pending` 默认为 `false`。空数组表示本次读取范围内没有匹配记录,
不能证明某次入群没有邀请人。调试日志会分别记录收件箱数量、类型筛选和最终筛选数量。
SDK 的 `getGroupSystemMessages()` 提供相应类型。新增字段在 SDK 中可选,以兼容旧服务端;
连接旧服务端时,缺失的状态也应视为未知。
+86
View File
@@ -0,0 +1,86 @@
# OneBot HTTP event streams
An HTTP server can serve actions and Server-Sent Events on the same listener.
Enable **SSE** in the WebUI's HTTP API adapter, or set `enableSse: true` on an
entry in `networks.httpServers`. The default is `false`; existing HTTP and
WebSocket configurations keep their behavior. SSE and `enableWebSocket` may both
be enabled.
```json
{
"name": "web-client",
"host": "127.0.0.1",
"port": 3000,
"path": "/api",
"enableSse": true,
"accessToken": "replace-with-your-token",
"messageFormat": "array",
"reportSelfMessage": false
}
```
`GET /api/_events?access_token=<token>` opens the event stream. Actions continue
to use `POST /api/<action>` with a JSON parameter object. HTTP requests accept
`Authorization: Bearer <token>`, `Authorization: <token>` (for Stapxs QQ Lite), or
the `access_token` query parameter. The configured token and bind address still
apply. Empty tokens retain the existing unauthenticated HTTP behavior.
```js
const events = new EventSource(`api/_events?access_token=${encodeURIComponent(token)}`);
events.onmessage = ({ data }) => console.log(JSON.parse(data));
events.onerror = () =>
console.error('Event connection interrupted; check connection and authentication');
const response = await fetch('api/get_status', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: token },
body: JSON.stringify({}),
});
if (!response.ok) throw new Error(`Action failed: HTTP ${response.status}`);
console.log(await response.json());
// Close the stream when the owning page/component is disposed.
// events.close();
```
Configure Stapxs's SSE event address as `api/_events` and HTTP address as `api`
when both are exposed under that same-origin proxy prefix. Forward the request
path, query string, authorization and `Last-Event-ID` headers unchanged. SnowLuma
does not add cross-origin access grants. TLS and any additional proxy
authentication remain the proxy's responsibility.
Responses use `text/event-stream`, `Cache-Control: no-cache, no-transform`, and
`X-Accel-Buffering: no`. Events are ordinary unnamed `data:` frames containing
OneBot JSON. Connection lifecycle and current heartbeat events bootstrap each
subscription. Transport comments (`: ping`) are sent every 15 seconds; they are
not OneBot events. The browser's reconnect delay is 3 seconds.
## Reconnect and resource limits
Every broadcast event has an opaque `id`. A reconnect with `Last-Event-ID`
replays events after that cursor, in order, before connection bootstrap events
and subsequent live events. Native EventSource sends this header automatically
when reconnecting the same object. A new subscription without the header starts
at the present and does not receive old messages.
Each adapter retains at most 256 events and 8 MiB in memory, including while no
client is connected. This is a short reconnect window, not durable message
history. Accounts and adapter instances have independent histories. Event IDs
are invalidated on restart, shutdown, token rotation, report-policy changes or
disabling SSE. Neither replay nor live delivery bypasses `messageFormat` or
`reportSelfMessage`.
An invalid cursor returns HTTP 400. An expired, future or foreign cursor returns
HTTP 409 with `wording` explaining that replay is unavailable. There is no silent
fallback to live-only delivery. After reconciling the application's state/history,
close and recreate EventSource to subscribe without the old cursor. EventSource's
error callback does not expose the HTTP error body; fetch-based consumers can
inspect it directly. Bootstrap events can share the latest broadcast cursor and
must not be treated as newly persisted message events.
Each client's pending output is limited to 8 MiB. Slow readers are disconnected
with a warning instead of retaining unbounded events or blocking other clients.
A single frame exceeding this limit also disconnects that client. Reconnection
is subject to the same replay limits. Disconnect, hot reload and shutdown release
connections and heartbeat timers; rotating the token revokes existing streams.
Tests: `pnpm --filter @snowluma/onebot exec vitest run tests/http-server-sse.test.ts tests/http-sse-backpressure.test.ts tests/http-server-websocket-config.test.ts`.
+42
View File
@@ -0,0 +1,42 @@
# Reply targets
A normal OneBot `reply` segment identifies a message by its non-zero, signed
`message_id`. Negative identifiers are valid. The identifier generation rules
for ordinary incoming messages and send results are unchanged.
Private QQ quotes can use a sender-local sequence instead of the conversation
sequence used for message identifiers. SnowLuma checks the conversation, sender
direction, available timestamp and quoted text against stored messages. Matching
numbers from different sequence namespaces do not by themselves prove that two
records identify the same message. The current message is excluded from its own
quote lookup.
When the target is not available locally, live event processing requests bounded
private history before converting and dispatching the event. A verified history
message is stored under its actual identifier, so an immediate `get_msg` can
retrieve it. Existing verified identifiers are preserved when filling a missing
body, and recalled messages are not restored.
An unresolved or ambiguous private target does not produce a guessed identifier
or a new placeholder record. The normal event omits that `reply` segment and
keeps the rest of the message. Warnings identify unresolved targets; trace logs
record the lookup result, conversation, sequence, timestamp and selected
identifier without logging quoted content. Fetch failures remain visible.
Group quotes retain their group-sequence lookup. Forwarded nodes retain their
inline quote content, which can be resent even when the original message is not
available in the local account's history.
Image uploads retain their download reference and actual filename in durable
message metadata. `get_msg` refreshes each image from that message's own reference,
so a reused filename or a restart does not select another upload.
For older records missing an image reference, `get_msg` requests bounded history
for the stored conversation and sequence (or the stored timestamp and client
sequence for legacy private records). Only a unique message with matching sender,
time and ordered image fingerprints can fill the missing references. The repair
is saved under the existing signed `message_id`; it preserves message content
and identity metadata and never restores a record removed while the request was pending.
Complete images need no history request. If history is unavailable or cannot
verify the match, the unverified image data is left intact and a warning is logged;
download URLs are not guessed.
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "2.3.0",
"version": "2.4.2",
"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>'`.",
@@ -62,6 +62,14 @@ export const messageDataSchema = {
additionalProperties: true,
} satisfies JsonSchema;
export const messageWithAutoReplySchema = {
...messageDataSchema,
properties: {
...messageDataSchema.properties,
auto_reply: { const: true, description: '仅当 QQ 标记该私聊消息为自动回复时提供' },
},
} satisfies JsonSchema;
// Forward nodes carry their original identifiers, not locally hashed message IDs.
export const forwardNodeSchema: JsonSchema = {
...messageDataSchema,
@@ -0,0 +1,54 @@
const privilegeSchema = {
type: 'object',
properties: {
type: { type: 'integer', description: '业务类型' },
level: { type: 'integer', description: '业务等级' },
flag: { type: 'integer', description: '服务端业务标志' },
is_big: { type: 'integer', description: '服务端大图标标志' },
jump_url: { type: 'string', description: '业务跳转地址' },
icon_url: { type: 'string', description: '普通图标地址' },
deluxe_icon_url: { type: 'string', description: '高级图标地址,可与普通图标同时存在' },
},
};
export const publicProfileProperties = {
long_nick: { type: 'string', description: '个性签名' },
sex: { type: 'string', enum: ['male', 'female', 'unknown'], description: '性别' },
age: { type: 'integer', description: '年龄' },
level: { type: 'integer', description: 'QQ 等级' },
birthday_year: { type: 'integer', description: '生日年份,未公开时省略' },
birthday_month: { type: 'integer', description: '生日月份(1-12)' },
birthday_day: { type: 'integer', description: '生日日期(1-31)' },
phone_num: { type: 'string', description: '资料卡公开的电话号码' },
email: { type: 'string', description: '资料卡公开的邮箱' },
country: { type: 'string', description: '国家' },
province: { type: 'string', description: '省份' },
city: { type: 'string', description: '城市' },
college: { type: 'string', description: '学校' },
is_qq_vip: { type: 'boolean', description: '普通会员状态' },
is_vip: { type: 'boolean', description: '超级会员状态,兼容已有接口' },
is_years_vip: { type: 'boolean', description: '年费会员状态' },
vip_level: { type: 'integer', description: '会员等级' },
privilege_icons: {
type: 'object',
description: '业务图标;未返回该资料时省略整个字段,空列表表示没有该类图标',
properties: {
jump_url: { type: 'string', description: '业务列表跳转地址' },
open: { type: 'array', description: '已开通业务', items: privilegeSchema },
closed: { type: 'array', description: '未开通业务', items: privilegeSchema },
},
required: ['open', 'closed'],
},
};
export const friendResultSchema = {
type: 'object',
properties: {
user_id: { type: 'integer', description: '好友 QQ 号' },
nickname: { type: 'string', description: '好友昵称' },
remark: { type: 'string', description: '好友备注' },
category_id: { type: 'integer', description: '好友分组编号,有来源时返回' },
...publicProfileProperties,
},
required: ['user_id', 'nickname', 'remark'],
};
+23 -21
View File
@@ -3,7 +3,7 @@ import { mapWithConcurrency } from '@snowluma/common/concurrency';
import { positiveIntEnv } from '@snowluma/common/env';
import { readFile } from 'node:fs/promises';
import { FriendDressError } from '@snowluma/protocol/web/friend-dress';
import { formatGroupRequestFlag } from '@snowluma/protocol/qq-info';
import { formatGroupRequestFlag, groupRequestSubType } from '@snowluma/protocol/qq-info';
import type {
GroupEssenceContent,
GroupEssenceMessage,
@@ -21,10 +21,13 @@ import {
} from '../types';
import { defineAction, groupAction, groupUserAction, f, type Field } from '../action-kit';
import { groupInfoReturnsSchema } from './group-info';
import { friendResultSchema } from './contact-profile-schema';
import { formatFriend } from '../modules/contact-profile';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
import {
messageIdSchema,
messageDataSchema,
messageWithAutoReplySchema,
forwardNodeSchema,
messageSegmentSchema,
mediaInfoSchema,
@@ -1037,7 +1040,7 @@ export const actions = [
messages: {
type: 'array',
description: '消息对象数组;去除 post_type/self_id,附带 real_id',
items: messageDataSchema,
items: messageWithAutoReplySchema,
},
},
required: ['messages'],
@@ -2647,7 +2650,8 @@ export const actions = [
],
summary: '获取分组好友列表',
readOnly: true,
returns: '好友分组数组;每组包含 categoryId、categoryName、categoryMbCount 和 buddyList。',
returns:
'好友分组数组;buddyList 与 get_friend_list 使用相同资料字段。默认只使用列表回包,with_profile=true 主动补查,失败会报错;未返回的资料省略。',
returnsSchema: {
type: 'array',
description: '带分组的好友列表',
@@ -2660,33 +2664,30 @@ export const actions = [
buddyList: {
type: 'array',
description: '该分组内的好友',
items: {
type: 'object',
properties: {
user_id: { type: 'integer', description: 'QQ 号' },
nickname: { type: 'string', description: '昵称' },
remark: { type: 'string', description: '好友备注' },
},
required: ['user_id', 'nickname', 'remark'],
},
items: friendResultSchema,
},
},
required: ['categoryId', 'categoryName', 'categoryMbCount', 'buddyList'],
},
},
params: {},
run: async (_p, ctx) => {
const categories = await ctx.bridge.apis.contacts.fetchFriendCategories();
params: {
with_profile: f
.bool()
.default(false)
.describe('主动补查好友公开资料,按账号缓存五分钟;大列表可能耗时较长'),
},
run: async (p, ctx) => {
const categories = await ctx.bridge.apis.contacts.fetchFriendCategories({
withProfile: p.with_profile,
});
return okResponse(
categories.map((category) => ({
categoryId: category.categoryId,
categoryName: category.categoryName,
categoryMbCount: category.memberCount,
buddyList: category.friends.map((friend) => ({
user_id: friend.uin,
nickname: friend.nickname,
remark: friend.remark,
})),
buddyList: category.friends.map((friend) =>
formatFriend(friend, category.categoryId),
),
})),
);
},
@@ -5485,7 +5486,8 @@ export const actions = [
// 与标准群系统消息共用过滤收件箱,只保留方言动作的返回形状。
// 这几个动作只是为实际使用中的 OneBot 方言客户端重命名并投影相同数据。
async function fetchFilteredGroupRequests(ctx: ApiActionContext) {
return ctx.bridge.apis.contacts.fetchGroupRequests(true);
const requests = await ctx.bridge.apis.contacts.fetchGroupRequests(true);
return requests.filter((request) => groupRequestSubType(request) !== undefined);
}
function parseDownloadHeaders(headers: unknown): Record<string, string> {
+18 -14
View File
@@ -1,5 +1,6 @@
import { defineAction, f } from '../action-kit';
import { okResponse } from '../types';
import { failedResponse, okResponse, RETCODE } from '../types';
import { friendResultSchema, publicProfileProperties } from './contact-profile-schema';
export const actions = [
defineAction({
@@ -12,23 +13,25 @@ export const actions = [
],
summary: '获取好友列表',
readOnly: true,
returns: '好友列表数组,每项含 QQ 号、昵称与备注。',
returns:
'好友列表,包含账号、昵称、备注及回包已有的公开资料;with_profile=true 时主动补查,失败会报错。未返回的资料省略,零、空字符串和 false 保留。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
user_id: { type: 'integer', description: '好友 QQ 号' },
nickname: { type: 'string', description: '好友昵称' },
remark: { type: 'string', description: '好友备注' },
},
required: ['user_id', 'nickname', 'remark'],
},
items: friendResultSchema,
},
params: {},
run: async (_p, ctx) => {
params: {
with_profile: f
.bool()
.default(false)
.describe('主动补查好友公开资料,按账号缓存五分钟;大列表可能耗时较长'),
},
run: async (p, ctx) => {
if (ctx.getFriendList) {
return okResponse(await ctx.getFriendList());
return okResponse(await ctx.getFriendList(p.with_profile));
}
if (p.with_profile) {
return failedResponse(RETCODE.ACTION_FAILED, 'friend profile provider unavailable');
}
return okResponse([]);
@@ -53,6 +56,7 @@ export const actions = [
returnsSchema: {
type: 'object',
properties: {
...publicProfileProperties,
user_id: { type: 'integer', description: 'QQ 号' },
uid: { type: 'string', description: '账号唯一标识(仅查到资料时返回)' },
qid: { type: 'string', description: '自定义账号标识(仅查到资料时返回)' },
+5 -5
View File
@@ -4,17 +4,17 @@ import { RETCODE, failedResponse, okResponse } from '../types';
// NapCat/LLOneBot omit `busid` from their `get_group_file_url` schema entirely,
// so whatever value a client tacks on is silently ignored. Mirror that here:
// accept any value, coerce when it's a usable non-negative integer, else fall
// back to the canonical 102. Restores the legacy `asNumber(busid) || 102`
// back to the uploaded file's known storage type (otherwise 102). Retains the
// semantics that a strict `f.int({min:0}).default(102)` regressed (a *present*
// non-numeric busid was rejected with `expected an integer`). See issue #147.
function busidOr102(raw: unknown): number {
function optionalBusId(raw: unknown): number | undefined {
const n =
typeof raw === 'number' && Number.isFinite(raw)
? Math.trunc(raw)
: typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))
? Math.trunc(Number(raw))
: NaN;
return Number.isInteger(n) && n >= 0 ? n : 102;
return Number.isInteger(n) && n >= 0 ? n : undefined;
}
export const actions = [
@@ -159,7 +159,7 @@ export const actions = [
properties: { url: { type: 'string', description: '文件下载直链' } },
required: ['url'],
},
// busid is accepted but tolerant (see busidOr102): NapCat/LLBot ignore it,
// busid is accepted but tolerant (see optionalBusId): NapCat/LLBot ignore it,
// so a present null/empty/non-numeric value must not 400 the request (#147).
params: { file_id: f.fileId(), busid: f.raw() },
run: async (p, ctx) => {
@@ -167,7 +167,7 @@ export const actions = [
url: await ctx.bridge.apis.groupFile.getUrl(
p.group_id,
p.file_id,
busidOr102(p.busid),
optionalBusId(p.busid),
),
});
},
+43 -4
View File
@@ -577,7 +577,8 @@ export const actions = [
],
summary: '获取群系统消息',
readOnly: true,
returns: '群系统消息数组,可按群号或未处理状态过滤。',
returns:
'群系统消息数组,分别提供入群者、邀请人和处理者,可按群号或未处理状态过滤。身份为 0 时须查看状态;未知不代表不存在邀请人。',
returnsSchema: {
type: 'array',
items: {
@@ -586,10 +587,41 @@ export const actions = [
group_id: { type: 'integer', description: '群号' },
group_name: { type: 'string', description: '群名称' },
request_id: { type: 'integer', description: '请求序列号' },
requester_uin: { type: 'integer', description: '申请人 QQ 号' },
requester_nick: { type: 'string', description: '申请人昵称' },
invitor_uin: { type: 'integer', description: '邀请人 QQ 号,无邀请时为 0' },
requester_uin: {
type: 'integer',
description: '请求发起人 QQ 号;邀请登录账号入群时表示邀请人',
},
requester_nick: { type: 'string', description: '请求发起人昵称' },
target_uin: {
type: 'integer',
description: '申请或被邀请入群者 QQ 号,未知时为 0',
},
target_nick: { type: 'string', description: '入群者昵称' },
target_status: {
type: 'string',
enum: ['known', 'unknown'],
description: '入群者 QQ 号是否已知',
},
invitor_uin: {
type: 'integer',
description: '邀请人 QQ 号,未知时为 0;不能据此认定没有邀请人',
},
invitor_nick: { type: 'string', description: '邀请人昵称' },
invitor_status: {
type: 'string',
enum: ['known', 'unknown'],
description: '邀请人 QQ 号是否已知;缺失信息为 unknown',
},
operator_uin: {
type: 'integer',
description: '处理该申请的操作者 QQ 号,未知时为 0',
},
operator_nick: { type: 'string', description: '处理者昵称' },
operator_status: {
type: 'string',
enum: ['known', 'unknown'],
description: '处理者 QQ 号是否已知;已知不代表审批通过',
},
message: { type: 'string', description: '验证留言' },
checked: { type: 'boolean', description: '是否已处理' },
flag: { type: 'string', description: '处理请求使用的规范 flag' },
@@ -600,8 +632,15 @@ export const actions = [
'request_id',
'requester_uin',
'requester_nick',
'target_uin',
'target_nick',
'target_status',
'invitor_uin',
'invitor_nick',
'invitor_status',
'operator_uin',
'operator_nick',
'operator_status',
'message',
'checked',
'flag',
+6 -2
View File
@@ -2,7 +2,11 @@ import { createLogger } from '@snowluma/common/logger';
import type { JsonObject, JsonValue } from '../types';
import { defineAction, groupAction, f, type Field } from '../action-kit';
import { RETCODE, failedResponse, okResponse } from '../types';
import { messageResultSchema, messageIdSchema, messageDataSchema } from '../action-result-schemas';
import {
messageResultSchema,
messageIdSchema,
messageWithAutoReplySchema,
} from '../action-result-schemas';
/** send_msg only (#426). Some clients send `group_id: ""` on private chats.
* Treat that exact empty string as absent. Do not change `f.groupId()`. */
@@ -210,7 +214,7 @@ export const actions = [
],
returnsSchema: {
allOf: [
messageDataSchema,
messageWithAutoReplySchema,
{
type: 'object',
properties: {
+43 -2
View File
@@ -79,6 +79,45 @@ export const actions = [
run: async (p, ctx) =>
okResponse(await ctx.bridge.apis.qzone.getHomeFeeds(p.target_uin, p.cursor)),
}),
defineAction({
name: 'get_qzone_feed_detail',
summary: '按说说 tid 读取完整空间动态,可用于生成分享卡片',
readOnly: true,
examples: [
{
summary: '按说说编号获取完整动态',
params: { tid: '1127000000f1536501000000' },
notes: '将示例 tid 替换为 get_qzone_msg_list 或 send_qzone_msg 返回的 24 位十六进制说说编号。把结果的 feed 原样传给 get_qzone_share_ark;读取和分享均受空间权限限制。',
},
],
returns:
'完整动态及上游详情字段。feed 保留图片、视频、分享信息和未知字段,可直接用于 get_qzone_share_ark;attach_info 保留上游评论游标,不自动翻页。',
returnsSchema: {
type: 'object',
additionalProperties: true,
properties: {
feed: {
type: 'object',
additionalProperties: true,
description: '去除上游包装后的完整动态,可原样传给 get_qzone_share_ark',
},
attach_info: {
type: ['string', 'null'],
description: '上游评论续页游标,未提供时为 null;不保证评论及回复完整',
},
},
required: ['feed', 'attach_info'],
},
params: {
tid: f.string({ allowEmpty: false, maxLen: 24 }).describe('24 位十六进制说说编号'),
},
rules: (r) => [
r.rule('tid must be a 24-character hexadecimal post ID', (p) =>
/^[0-9a-f]{24}$/i.test(p.tid),
),
],
run: async (p, ctx) => okResponse(await ctx.bridge.apis.qzone.getFeedDetail(p.tid)),
}),
defineAction({
name: 'get_qzone_share_ark',
summary: '生成空间动态分享卡片,返回原文及分享提示',
@@ -100,7 +139,7 @@ export const actions = [
},
},
},
notes: 'feed 原样取自 get_qzone_home_feeds 或 get_qzone_public_feeds。分享链接可能允许未登录者访问并包含作者 QQ 号;如 requires_confirmation=true,发送前展示 notice 并取得确认。将 ark 原文作为 JSON 消息发送,不要修改卡片内容。',
notes: 'feed 原样取自 get_qzone_feed_detail 的 feed,或 get_qzone_home_feeds / get_qzone_public_feeds 的 feeds 条目。分享链接可能允许未登录者访问并包含作者 QQ 号;如 requires_confirmation=true,发送前展示 notice 并取得确认。将 ark 原文作为 JSON 消息发送,不要修改卡片内容。',
},
],
returns: '生成卡片但不发送消息;后续发送仍返回普通消息编号。',
@@ -116,7 +155,9 @@ export const actions = [
},
required: ['ark', 'requires_confirmation', 'notice'],
},
params: { feed: f.object().describe('主页或推荐列表返回的完整动态,保留所有原始字段') },
params: {
feed: f.object().describe('主页、详情或推荐列表返回的完整动态,保留所有原始字段'),
},
run: async (p, ctx) => okResponse(await ctx.bridge.apis.qzone.getShareArk(p.feed)),
}),
defineAction({
+1 -1
View File
@@ -76,7 +76,7 @@ export interface ApiActionContext {
deleteMessage: (messageId: number, meta: MessageMeta) => Promise<void>;
canSendImage: () => boolean;
canSendRecord: () => boolean;
getFriendList: () => Promise<JsonObject[]>;
getFriendList: (withProfile?: boolean) => Promise<JsonObject[]>;
getGroupList: (noCache?: boolean) => Promise<JsonObject[]>;
getGroupInfo: (groupId: number, noCache?: boolean) => Promise<JsonObject | null>;
getGroupMemberList: (groupId: number, noCache?: boolean) => Promise<JsonObject[]>;
+79 -2
View File
@@ -24,6 +24,11 @@ const CONFIG_DIR = 'config';
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
const NODE_TIMER_MAX_MS = 2_147_483_647;
/** Bounds for a per-adapter inbound WebSocket frame cap. 2 GiB is several
* orders of magnitude past any real OneBot frame; above that a sender has to
* split its payload instead of expecting a single buffer to hold it. */
const MAX_PAYLOAD_BYTES_MIN = 1024;
const MAX_PAYLOAD_BYTES_MAX = 2 * 1024 * 1024 * 1024;
const PER_UIN_SNAPSHOT_MARKER = 'snapshot';
const DEFAULT_STATUS_COMMAND: StatusCommandConfig = {
@@ -51,6 +56,7 @@ export function makeDefaultOneBotConfig(): OneBotConfig {
port: 3000,
path: '/',
enableWebSocket: false,
enableSse: false,
accessToken: generateAccessToken(),
messageFormat: 'array',
reportSelfMessage: false,
@@ -412,11 +418,15 @@ function validateRestoreAdapterArray(
: ['url', 'role', 'reconnectIntervalMs'];
if (kind === 'httpServers') {
specific.push('enableWebSocket');
specific.push('enableWebSocket', 'enableSse', 'maxPayloadBytes');
}
if (kind === 'wsServers') {
specific.push('role');
specific.push('role', 'maxPayloadBytes');
}
if (kind === 'wsClients') {
specific.push('maxPayloadBytes');
}
const allowed = new Set<string>([...RESTORE_BASE_ADAPTER_KEYS, ...specific]);
@@ -453,6 +463,10 @@ function validateRestoreAdapterArray(
invalid(`${pathAt}.reportSelfMessage must be a boolean`);
}
if (kind !== 'httpClients') {
parseMaxPayloadBytes(raw.maxPayloadBytes, pathAt);
}
if (kind === 'httpServers' || kind === 'wsServers') {
const port = parseRestoreInteger(raw.port);
@@ -475,6 +489,14 @@ function validateRestoreAdapterArray(
) {
invalid(`${pathAt}.enableWebSocket must be a boolean`);
}
if (
kind === 'httpServers' &&
raw.enableSse !== undefined &&
typeof raw.enableSse !== 'boolean'
) {
invalid(`${pathAt}.enableSse must be a boolean`);
}
} else {
if (raw.url !== undefined && typeof raw.url !== 'string') {
invalid(`${pathAt}.url must be a string`);
@@ -656,16 +678,23 @@ export function assertValidOneBotConfig(value: unknown): asserts value is OneBot
const serverBindings = new Map<string, string>();
validateNetworkList(value.networks, 'httpServers', seen, (item, at) => {
validateServer(item, at);
parseMaxPayloadBytes(item.maxPayloadBytes, at);
if (item.enableWebSocket !== undefined && typeof item.enableWebSocket !== 'boolean') {
invalid(`${at}.enableWebSocket must be a boolean`);
}
if (item.enableSse !== undefined && typeof item.enableSse !== 'boolean') {
invalid(`${at}.enableSse must be a boolean`);
}
validateServerBinding(item, at, serverBindings);
});
validateNetworkList(value.networks, 'httpClients', seen, (item, at) => {
validateClient(item, at, new Set(['http:', 'https:']));
rejectHttpClientMaxPayloadBytes(item, at);
if (
item.timeoutMs !== undefined &&
(typeof item.timeoutMs !== 'number' ||
@@ -680,10 +709,12 @@ export function assertValidOneBotConfig(value: unknown): asserts value is OneBot
validateServer(item, at);
validateServerBinding(item, at, serverBindings);
validateRole(item.role, `${at}.role`);
parseMaxPayloadBytes(item.maxPayloadBytes, at);
});
validateNetworkList(value.networks, 'wsClients', seen, (item, at) => {
validateClient(item, at, new Set(['ws:', 'wss:']));
validateRole(item.role, `${at}.role`);
parseMaxPayloadBytes(item.maxPayloadBytes, at);
if (
item.reconnectIntervalMs !== undefined &&
@@ -816,6 +847,33 @@ function validateNetworkBase(item: JsonObject, at: string): void {
}
}
/** Apply the same limit validation to files, restores and API writes. */
function parseMaxPayloadBytes(value: unknown, at: string): number | undefined {
if (value === undefined) {
return undefined;
}
if (
typeof value !== 'number' ||
!Number.isSafeInteger(value) ||
value < MAX_PAYLOAD_BYTES_MIN ||
value > MAX_PAYLOAD_BYTES_MAX
) {
invalid(
`${at}.maxPayloadBytes must be an integer between ${MAX_PAYLOAD_BYTES_MIN} and ${MAX_PAYLOAD_BYTES_MAX}`,
);
}
return value;
}
function rejectHttpClientMaxPayloadBytes(item: JsonObject, at: string): void {
// A frame cap on the pure HTTP POST adapter would be saved and ignored.
if (item.maxPayloadBytes !== undefined) {
invalid(`${at}.maxPayloadBytes is only supported by WebSocket adapters`);
}
}
function validateServer(item: JsonObject, at: string): void {
if (
!Number.isInteger(item.port) ||
@@ -1030,6 +1088,7 @@ function applyBase(
accessToken?: string;
messageFormat: MessageFormat;
reportSelfMessage: boolean;
maxPayloadBytes?: number;
},
): void {
out.name = n.name;
@@ -1044,6 +1103,10 @@ function applyBase(
out.messageFormat = n.messageFormat;
out.reportSelfMessage = n.reportSelfMessage;
if (n.maxPayloadBytes !== undefined) {
out.maxPayloadBytes = n.maxPayloadBytes;
}
}
function httpServerToJson(n: HttpServerNetwork): JsonObject {
@@ -1053,6 +1116,7 @@ function httpServerToJson(n: HttpServerNetwork): JsonObject {
out.port = n.port;
out.path = n.path ?? '/';
out.enableWebSocket = n.enableWebSocket === true;
out.enableSse = n.enableSse === true;
return out;
}
@@ -1362,10 +1426,16 @@ function parseBase(value: JsonObject, defaults: AdapterDefaults) {
}
function parseHttpServer(value: JsonObject, defaults: AdapterDefaults): HttpServerNetwork | null {
const maxPayloadBytes = parseMaxPayloadBytes(value.maxPayloadBytes, 'http server');
if (value.enableWebSocket !== undefined && typeof value.enableWebSocket !== 'boolean') {
invalid('http server enableWebSocket must be a boolean');
}
if (value.enableSse !== undefined && typeof value.enableSse !== 'boolean') {
invalid('http server enableSse must be a boolean');
}
const port = asNumber(value.port, 0);
if (port <= 0) {
@@ -1378,10 +1448,13 @@ function parseHttpServer(value: JsonObject, defaults: AdapterDefaults): HttpServ
port,
path: asString(value.path, '/'),
enableWebSocket: value.enableWebSocket === true,
enableSse: value.enableSse === true,
maxPayloadBytes,
});
}
function parseHttpClient(value: JsonObject, defaults: AdapterDefaults): HttpClientNetwork | null {
rejectHttpClientMaxPayloadBytes(value, 'http client');
const url = asString(value.url);
const base = parseBase(value, defaults);
@@ -1398,6 +1471,7 @@ function parseHttpClient(value: JsonObject, defaults: AdapterDefaults): HttpClie
}
function parseWsServer(value: JsonObject, defaults: AdapterDefaults): WsServerNetwork | null {
const maxPayloadBytes = parseMaxPayloadBytes(value.maxPayloadBytes, 'websocket server');
const port = asNumber(value.port, 0);
if (port <= 0) {
@@ -1410,10 +1484,12 @@ function parseWsServer(value: JsonObject, defaults: AdapterDefaults): WsServerNe
port,
path: asString(value.path, '/'),
role: asRole(value.role, 'Universal'),
maxPayloadBytes,
});
}
function parseWsClient(value: JsonObject, defaults: AdapterDefaults): WsClientNetwork | null {
const maxPayloadBytes = parseMaxPayloadBytes(value.maxPayloadBytes, 'websocket client');
const url = asString(value.url);
const base = parseBase(value, defaults);
@@ -1427,6 +1503,7 @@ function parseWsClient(value: JsonObject, defaults: AdapterDefaults): WsClientNe
url,
role: asRole(value.role, 'Universal'),
reconnectIntervalMs: Math.max(1000, reconnectIntervalMs),
maxPayloadBytes,
});
}
@@ -15,6 +15,7 @@ import type {
} from './index';
import { GROUP_MESSAGE_EVENT, privateMessageEventName } from '../message-id';
import { resolveReplyId } from './utils';
import type { PrivateQuoteSource } from '../private-quote';
// ─────────────────────────────────────────────────────────────────────────
// 消息元素 codec 表(onebot 侧)—— 把「同一种元素」的两个 onebot 方向并到一处:
@@ -42,6 +43,7 @@ export interface ToSegmentContext {
mediaUrlResolver?: MediaUrlResolver | null;
messageIdResolver?: MessageIdResolver | null;
mediaSegmentSink?: MediaSegmentSink | null;
currentMessage?: PrivateQuoteSource;
}
// The image segment is the one intentional triangular mapping: an image with
@@ -295,17 +297,20 @@ export const ELEMENT_CODECS = {
const eventName = ctx.isGroup
? GROUP_MESSAGE_EVENT
: privateMessageEventName(sentBySelf, false);
const id = await resolveReplyId(
ctx.isGroup,
ctx.sessionId,
element.replySeq ?? 0,
ctx.messageIdResolver,
eventName,
element.replyTime && element.replyTime > 0
? element.replyTime
: Number.MAX_SAFE_INTEGER,
element.replyElements,
);
const id =
element.replyMessageId ??
(await resolveReplyId(
ctx.isGroup,
ctx.sessionId,
element.replySeq ?? 0,
ctx.messageIdResolver,
eventName,
element.replyTime && element.replyTime > 0
? element.replyTime
: Number.MAX_SAFE_INTEGER,
element.replyElements,
ctx.currentMessage,
));
return { type: 'reply', data: { id: String(id) } };
},
async fromSegment(data, options) {
@@ -1,5 +1,6 @@
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
import type { JsonObject } from '../types';
import type { PrivateQuoteSource } from '../private-quote';
import { convertFriendMessage, convertGroupMessage, convertTempMessage } from './to-message';
import {
convertBotOffline,
@@ -40,6 +41,7 @@ export type MessageIdResolver = (
eventName: string,
timestamp?: number,
replyElements?: readonly MessageElement[],
excludedMessage?: PrivateQuoteSource,
) => number | Promise<number>;
export type MediaSegmentSink = (
@@ -53,7 +53,16 @@ async function convertPrivateMessage(
messageIdSequence,
eventName,
);
const segments = await toSegments(ctx, event.elements, false, sessionId);
const segments = await elementsToOneBotSegments(ctx, event.elements, false, sessionId, {
currentMessage: {
id: messageId,
sequence: hasCanonicalNtSequence ? ntSequence : 0,
clientSequence:
event.kind === 'friend_message' ? (event.clientSeq ?? event.msgSeq) : event.msgSeq,
timestamp: event.time,
sentBySelf: isSelf,
},
});
const sender: JsonObject = {
user_id: event.senderUin,
nickname: event.senderNick,
@@ -80,6 +89,10 @@ async function convertPrivateMessage(
sender,
};
if (event.autoReply) {
fields.auto_reply = true;
}
if (isSelf && sessionId > 0 && sessionId !== ctx.selfId) {
fields.target_id = sessionId;
}
@@ -35,6 +35,8 @@ export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMember
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
invitor_id: event.invitorUin ?? 0,
invitor_status: (event.invitorUin ?? 0) > 0 ? 'known' : 'unknown',
});
}
@@ -5,6 +5,7 @@ import { getElementCodec } from './element-codecs';
import { createLogger } from '@snowluma/common/logger';
import type { ConverterContext } from './index';
import { attachMessageMedia } from '../message-media';
import type { PrivateQuoteSource } from '../private-quote';
const log = createLogger('OneBot');
@@ -13,9 +14,15 @@ export async function elementsToOneBotSegments(
elements: MessageElement[],
isGroup: boolean,
sessionId: number,
options: { includeReplyContent?: boolean } = {},
options: { includeReplyContent?: boolean; currentMessage?: PrivateQuoteSource } = {},
): Promise<JsonArray> {
const segmentCtx: ToSegmentContext = { ...ctx, isGroup, sessionId, mediaSegmentSink: null };
const segmentCtx: ToSegmentContext = {
...ctx,
isGroup,
sessionId,
mediaSegmentSink: null,
currentMessage: options.currentMessage,
};
const result: JsonArray = [];
for (const element of elements) {
@@ -34,6 +41,21 @@ export async function elementsToOneBotSegments(
continue;
}
if (
element.type === 'reply' &&
(segment.data as JsonObject).id === '0' &&
!options.includeReplyContent
) {
log.warn(
'quote target unresolved: group=%s session=%d seq=%d time=%s; omitting reply id',
isGroup,
sessionId,
element.replySeq,
element.replyTime,
);
continue;
}
// Forward quotes often refer to messages outside the local account's
// history. Carry their inline content so consumers can resend the node.
if (
+6 -1
View File
@@ -1,6 +1,7 @@
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { MessageIdResolver } from './index';
import type { MessageElement } from '@snowluma/protocol/events';
import type { PrivateQuoteSource } from '../private-quote';
export function isSameActor(
leftUin: number,
@@ -43,6 +44,7 @@ export async function resolveReplyId(
eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT,
timestamp?: number,
replyElements?: readonly MessageElement[],
excludedMessage?: PrivateQuoteSource,
): Promise<number> {
const seq = Math.trunc(sequence);
@@ -58,11 +60,14 @@ export async function resolveReplyId(
eventName,
timestamp,
replyElements,
excludedMessage,
);
if (Number.isInteger(resolved) && resolved !== 0) {
if (Number.isInteger(resolved)) {
return resolved;
}
throw new Error('reply resolver returned an invalid message id');
}
return seq;
+29 -27
View File
@@ -176,10 +176,38 @@ async function convertAndDispatch(
state: EventTraceState,
messageIdOverride?: number,
): Promise<void> {
let preparedEvent = event;
if (event.kind === 'friend_message' && (await isFriendMessageRecalled(ctx, log, event))) {
traceEventTerminal(log, event.kind, state, 'dropped', 'recalled_before_backfill');
return;
}
// If this message quotes one we don't have, fetch + persist it first (gated +
// throttled) so a consumer's get_msg on the quote resolves. No-op for the
// common case (no reply, or the quoted message is already stored). Never let a
// back-fill failure block delivery of the live message.
try {
preparedEvent = await backfillReplyTarget(ctx, event);
} catch (error) {
// Best-effort — dispatch the live event regardless, but keep the failure
// attributable so a repeated store/server miss is diagnosable.
log.warn(
'reply backfill failed kind=%s: %s',
event.kind,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
log.trace(() => [
'event_branch kind=%s reason=reply_backfill_failed error=%s',
event.kind,
error instanceof Error ? (error.stack ?? error.message) : String(error),
]);
}
let converted;
try {
converted = await convertEvent(ctx.converterCtx, event);
converted = await convertEvent(ctx.converterCtx, preparedEvent);
} catch (error) {
traceEventTerminal(log, event.kind, state, 'failed', 'converter_threw', error);
throw error;
@@ -200,32 +228,6 @@ async function convertAndDispatch(
renderParamsVerbose(converted),
]);
if (event.kind === 'friend_message' && (await isFriendMessageRecalled(ctx, log, event))) {
traceEventTerminal(log, event.kind, state, 'dropped', 'recalled_before_backfill');
return;
}
// If this message quotes one we don't have, fetch + persist it first (gated +
// throttled) so a consumer's get_msg on the quote resolves. No-op for the
// common case (no reply, or the quoted message is already stored). Never let a
// back-fill failure block delivery of the live message.
try {
await backfillReplyTarget(ctx, event);
} catch (error) {
// Best-effort — dispatch the live event regardless, but keep the failure
// attributable so a repeated store/server miss is diagnosable.
log.warn(
'reply backfill failed kind=%s: %s',
event.kind,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
log.trace(() => [
'event_branch kind=%s reason=reply_backfill_failed error=%s',
event.kind,
error instanceof Error ? (error.stack ?? error.message) : String(error),
]);
}
// Backfill can await several network/media operations. Re-check immediately
// before dispatch so a recall that arrived during that gap wins the race.
if (event.kind === 'friend_message' && (await isFriendMessageRecalled(ctx, log, event))) {
+3 -2
View File
@@ -5,6 +5,7 @@ import type { ApiActionContext } from './api-handler';
import type { ConverterContext } from './event-converter';
import type { MediaStore } from './media-store';
import type { MessageStore } from './message-store';
import { readMessageWithImageRepair } from './message-image-repair';
import type { TempSessionStore } from './temp-session-store';
import {
getDownloadRKeys,
@@ -76,7 +77,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getLoginInfo: () => getLoginInfo(ref),
isOnline: () => true,
getUptimeMs: () => ref.getUptimeMs(),
getMessage: async (messageId) => await messageStore.findEvent(messageId),
getMessage: (messageId) => readMessageWithImageRepair(ref, messageId),
refreshMessageMedia: (messageId, event) => refreshMessageMedia(ref, messageId, event),
getMessageMeta: async (messageId) => await messageStore.findMeta(messageId),
cacheMessageMetas: async (entries) => await messageStore.storeMetas(entries),
@@ -100,7 +101,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
sendGroupMessage: (groupId, message, autoEscape) =>
sendGroupMessage(ref, groupId, message, autoEscape),
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
getFriendList: () => getFriendList(bridge),
getFriendList: (withProfile) => getFriendList(bridge, withProfile),
getGroupList: (noCache) => getGroupList(bridge, noCache),
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, groupId, noCache),
getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, groupId, noCache),
+3 -46
View File
@@ -18,15 +18,9 @@ import type { GlobalSettings } from './global-config';
import { MediaIndexer } from './media-indexer';
import { MediaStore } from './media-store';
import { MediaUrlResolver } from './media-url-resolver';
import {
GROUP_MESSAGE_EVENT,
PRIVATE_MESSAGE_EVENT,
PRIVATE_NT_MESSAGE_EVENT,
PRIVATE_SENT_MESSAGE_EVENT,
hashMessageIdInt32,
privateMessageEventName,
} from './message-id';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, privateMessageEventName } from './message-id';
import { MessageStore } from './message-store';
import { createMessageIdResolver } from './message-id-resolver';
import { sendGroupMessage, sendPrivateMessage } from './modules/message-actions';
import {
buildStatusText,
@@ -159,44 +153,7 @@ export class OneBotInstance {
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
mediaUrlResolver: (element, isGroup, sessionId) =>
mediaUrlResolver.resolve(element, isGroup, sessionId),
messageIdResolver: async (
isGroup,
sessionId,
sequence,
eventName,
timestamp,
replyElements,
) => {
const resolvedEventName =
eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT);
if (
!isGroup &&
timestamp !== undefined &&
(resolvedEventName === PRIVATE_MESSAGE_EVENT ||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT)
) {
const storedId = await this.messageStore.resolvePrivateReplyMessageId(
sessionId,
sequence,
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
timestamp,
replyElements,
);
if (storedId !== null) {
return storedId;
}
}
return hashMessageIdInt32(
sequence,
sessionId,
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT
? PRIVATE_NT_MESSAGE_EVENT
: resolvedEventName,
);
},
messageIdResolver: createMessageIdResolver(this.messageStore),
mediaSegmentSink: async (mediaType, element, data, isGroup, sessionId) =>
await mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
};
+1 -1
View File
@@ -22,7 +22,7 @@ export class MediaIndexer {
file: file || element.fileId || '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileId ?? '',
fileName: element.fileName || element.fileId || '',
subType: element.subType ?? 0,
summary: element.summary ?? '',
imageUrl: element.imageUrl ?? '',
@@ -0,0 +1,54 @@
import type { MessageIdResolver } from './event-converter';
import type { MessageStore } from './message-store';
import {
GROUP_MESSAGE_EVENT,
PRIVATE_MESSAGE_EVENT,
PRIVATE_NT_MESSAGE_EVENT,
PRIVATE_SENT_MESSAGE_EVENT,
hashMessageIdInt32,
} from './message-id';
export function createMessageIdResolver(
store: Pick<MessageStore, 'resolvePrivateReplyMessageId'>,
): MessageIdResolver {
return async (
isGroup,
sessionId,
sequence,
eventName,
timestamp,
replyElements,
excludedMessage,
) => {
const resolvedEventName =
eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT);
if (
!isGroup &&
timestamp !== undefined &&
(resolvedEventName === PRIVATE_MESSAGE_EVENT ||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT)
) {
const storedId = await store.resolvePrivateReplyMessageId(
sessionId,
sequence,
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
timestamp,
replyElements,
excludedMessage,
);
// Quote sequences are not canonical message-id inputs. A miss must
// remain unresolved so the live pipeline can fetch and verify history.
return storedId ?? 0;
}
return hashMessageIdInt32(
sequence,
sessionId,
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT
? PRIVATE_NT_MESSAGE_EVENT
: resolvedEventName,
);
};
}
+288
View File
@@ -0,0 +1,288 @@
import { createLogger } from '@snowluma/common/logger';
import type { FriendMessage, GroupMessage, MessageElementOf } from '@snowluma/protocol/events';
import type { OneBotInstanceContext } from './instance-context';
import { segmentsToRawMessage } from './helper/cq';
import {
attachMessageMedia,
imageMd5FromFile,
isStoredMediaSegment,
type MessageMedia,
type StoredMediaSegment,
} from './message-media';
import { PRIVATE_QUOTE_MAX_DRIFT_SECONDS } from './private-quote';
import { hasAuthoritativeSequence, type JsonObject, type MessageMeta } from './types';
const log = createLogger('OneBot');
type RepairContext = Pick<OneBotInstanceContext, 'selfId' | 'bridge' | 'messageStore'>;
type HistoryMessage = FriendMessage | GroupMessage;
function remoteUrl(value: unknown): value is string {
return typeof value === 'string' && /^https?:\/\//i.test(value);
}
function imageReference(element: MessageMedia | undefined): string {
return remoteUrl(element?.imageUrl)
? element.imageUrl
: remoteUrl(element?.url)
? element.url
: '';
}
/** Repair only missing image references. Full server events must not replace the
* original message body, sender classification, signed id or sequence metadata.
*/
export async function readMessageWithImageRepair(
ref: RepairContext,
messageId: number,
): Promise<JsonObject | null> {
const event = await ref.messageStore.findEvent(messageId);
if (!event || !Array.isArray(event.message)) {
return event;
}
const segments = event.message.filter(isStoredMediaSegment);
if (!segments.some((segment) => segment.type === 'image' && !remoteUrl(segment.data.url))) {
return event;
}
try {
const media = await ref.messageStore.findMedia(messageId);
if (
media &&
(media.length !== segments.length ||
media.some((element, index) => element.type !== segments[index]!.type))
) {
throw new Error('stored media association is inconsistent');
}
const missing = segments.map(
(segment, index) =>
segment.type === 'image' &&
!remoteUrl(segment.data.url) &&
!imageReference(media?.[index]),
);
if (!missing.some(Boolean)) {
return event;
}
const storedMeta = await ref.messageStore.findMeta(messageId);
// As in private history listing, old self-keyed outgoing rows require
// their explicit recipient. This changes lookup scope, never stored identity.
const meta =
storedMeta &&
!storedMeta.isGroup &&
storedMeta.targetId === ref.selfId &&
event.user_id === ref.selfId &&
typeof event.target_id === 'number' &&
Number.isSafeInteger(event.target_id) &&
event.target_id > 0
? { ...storedMeta, targetId: event.target_id }
: storedMeta;
if (
!meta ||
meta.targetId <= 0 ||
meta.timestamp <= 0 ||
!Number.isSafeInteger(event.user_id) ||
Number(event.user_id) <= 0 ||
(event.self_id !== undefined && event.self_id !== ref.selfId) ||
event.message_type !== (meta.isGroup ? 'group' : 'private') ||
(meta.isGroup ? event.group_id !== meta.targetId : event.sub_type !== 'friend') ||
(!meta.isGroup && event.target_id !== undefined && event.target_id !== meta.targetId)
) {
throw new Error('stored message identity is incomplete');
}
const candidates = (await fetchHistory(ref, meta)).filter((source) =>
matchesIdentity(source, event, meta, ref.selfId),
);
if (candidates.length !== 1) {
throw new Error(`expected one matching history message, got ${candidates.length}`);
}
const images = candidates[0]!.elements.filter(
(element): element is MessageElementOf<'image'> => element.type === 'image',
);
const storedImages = segments.filter((segment) => segment.type === 'image');
if (images.length !== storedImages.length) {
throw new Error('history image count differs from stored message');
}
const updated = structuredClone(event);
const updatedSegments = (updated.message as JsonObject[]).filter(isStoredMediaSegment);
// Never create empty placeholders for other media: they would prevent
// a later complete history response from filling their real metadata.
const attachSnapshots =
media !== null || segments.every((segment) => segment.type === 'image');
let imageIndex = 0;
for (const [index, segment] of updatedSegments.entries()) {
const old = media?.[index];
let element: MessageMedia = old ?? { type: segment.type };
if (segment.type === 'image') {
const image = images[imageIndex++]!;
verifyImage(old, segment, image);
if (missing[index]) {
const url = imageReference(image);
if (!url) {
throw new Error('history image has no download reference');
}
element = { ...image, imageUrl: url };
segment.data.url = url;
} else if (!old) {
element = { ...image, imageUrl: String(segment.data.url) };
}
}
if (attachSnapshots) {
attachMessageMedia(segment, element);
}
}
updated.raw_message = segmentsToRawMessage(updated.message as JsonObject[]);
if (!(await ref.messageStore.updateMedia(messageId, event, updated))) {
log.debug(
'[get_msg] image history repair skipped after concurrent update message_id=%d',
messageId,
);
return ref.messageStore.findEvent(messageId);
}
log.debug(
'[get_msg] image history repair saved message_id=%d images=%d',
messageId,
missing.filter(Boolean).length,
);
return updated;
} catch (error) {
// get_msg retains its documented partial-media behavior; do not invent
// a URL or overwrite a record when history cannot prove the association.
log.warn(
'[get_msg] image history repair failed message_id=%d: %s',
messageId,
error instanceof Error ? error.message : String(error),
);
return ref.messageStore.findEvent(messageId);
}
}
async function fetchHistory(ref: RepairContext, meta: MessageMeta): Promise<HistoryMessage[]> {
if (meta.isGroup) {
if (!hasAuthoritativeSequence(meta)) {
throw new Error('group message has no verified sequence');
}
const message = await ref.bridge.apis.message.getGroupMessageBySeq(
meta.targetId,
meta.sequence,
ref.selfId,
);
return message ? [message] : [];
}
const uid = await ref.bridge.resolveUserUid(meta.targetId);
if (!uid) {
throw new Error('private history peer could not be resolved');
}
if (meta.sequenceAuthoritative && Number.isSafeInteger(meta.sequence) && meta.sequence > 0) {
const message = await ref.bridge.apis.message.getC2cMessageBySeq(
uid,
meta.sequence,
ref.selfId,
);
return message ? [message] : [];
}
if (meta.clientSequence <= 0) {
throw new Error('private message has no verified client sequence');
}
return ref.bridge.apis.message.getC2cLatestHistory(
uid,
20,
ref.selfId,
Math.min(0xffff_ffff, meta.timestamp + 1),
);
}
function matchesIdentity(
source: HistoryMessage,
event: JsonObject,
meta: MessageMeta,
selfId: number,
): boolean {
if (
source.selfUin !== selfId ||
source.senderUin !== event.user_id ||
!Number.isSafeInteger(source.time) ||
source.time <= 0 ||
Math.abs(source.time - meta.timestamp) > PRIVATE_QUOTE_MAX_DRIFT_SECONDS
) {
return false;
}
if (source.kind === 'group_message') {
return meta.isGroup && source.groupId === meta.targetId && source.msgSeq === meta.sequence;
}
// These history requests explicitly bind the peer UID. Older outgoing
// responses can omit toUin; preserve that binding, never substitute selfId.
const peer = source.peerUin ?? (source.senderUin !== selfId ? source.senderUin : meta.targetId);
if (
meta.isGroup ||
peer !== meta.targetId ||
(meta.privateDirection &&
(source.senderUin === selfId) !== (meta.privateDirection === 'outgoing'))
) {
return false;
}
return meta.sequenceAuthoritative && Number.isSafeInteger(meta.sequence) && meta.sequence > 0
? source.sequenceAuthoritative !== false && source.ntMsgSeq === meta.sequence
: (source.clientSeq ?? source.msgSeq) === meta.clientSequence;
}
function verifyImage(
old: MessageMedia | undefined,
segment: StoredMediaSegment,
image: MessageElementOf<'image'>,
): void {
// Older rows lack per-message snapshots but expose the content hash as the
// image filename. Arbitrary aliases cannot establish this association.
const legacyMd5 = imageMd5FromFile(segment.data.file ?? segment.data.file_id);
const fingerprints = { md5Hex: old?.md5Hex || legacyMd5, sha1Hex: old?.sha1Hex };
let matched = false;
for (const field of ['md5Hex', 'sha1Hex'] as const) {
const before = fingerprints[field];
const after = image[field];
if (!before || !after) {
continue;
}
if (before.toLowerCase() !== after.toLowerCase()) {
throw new Error('history image fingerprint conflicts with stored message');
}
matched = true;
}
if (!matched) {
throw new Error('history image fingerprint cannot be verified');
}
}
+22 -1
View File
@@ -1,8 +1,29 @@
import type { MessageElement } from '@snowluma/protocol/events';
import { serializeMediaInfo } from './media-store';
import type { JsonObject } from './types';
import type { JsonObject, JsonValue } from './types';
export type MessageMedia = Extract<MessageElement, { type: 'image' | 'record' | 'video' }>;
export type StoredMediaSegment = JsonObject & { type: MessageMedia['type']; data: JsonObject };
export function isStoredMediaSegment(segment: JsonValue): segment is StoredMediaSegment {
return (
segment !== null &&
typeof segment === 'object' &&
!Array.isArray(segment) &&
(segment.type === 'image' || segment.type === 'record' || segment.type === 'video') &&
segment.data !== null &&
typeof segment.data === 'object' &&
!Array.isArray(segment.data)
);
}
/** Legacy image segments use a content hash filename; arbitrary aliases prove nothing. */
export function imageMd5FromFile(file: unknown): string | undefined {
return typeof file === 'string'
? /^([a-f0-9]{32})\.(?:png|jpe?g|webp|gif|bmp)$/i.exec(file)?.[1]?.toLowerCase()
: undefined;
}
const mediaSnapshot = Symbol('message media snapshot');
type MediaSegment = JsonObject & { [mediaSnapshot]?: MessageMedia };
+120 -276
View File
@@ -1,8 +1,14 @@
import { SqliteDatabase, type SqliteStatement } from '@snowluma/sqlite';
import { SqliteDatabase, type SqliteRow, type SqliteStatement } from '@snowluma/sqlite';
import { createLogger } from '@snowluma/common/logger';
import type { JsonObject, MessageMeta } from './types';
import type { MessageElement } from '@snowluma/protocol/events';
import { cqUnescape } from './helper/cq';
import {
cachedQuotePreview,
isUsableQuoteTime,
PRIVATE_QUOTE_MAX_DRIFT_SECONDS,
selectPrivateQuote,
type PrivateQuoteSource,
} from './private-quote';
import { openSqliteDb } from './sqlite-open';
import {
mergeMessageMedia,
@@ -39,6 +45,7 @@ export class MessageStore {
private stmtStoreMeta!: SqliteStatement;
private stmtFindEvent!: SqliteStatement;
private stmtFindMedia!: SqliteStatement;
private stmtUpdateMedia!: SqliteStatement;
private stmtFindMeta!: SqliteStatement;
private stmtResolveReplyGroup!: SqliteStatement;
private stmtResolveReplyPrivate!: SqliteStatement;
@@ -49,9 +56,8 @@ export class MessageStore {
private stmtFindLatestPersistedAuthoritativeSequence!: SqliteStatement;
private stmtListIncomingC2CSessions!: SqliteStatement;
private stmtFindPrivateRecall!: SqliteStatement;
private stmtFindPrivateMessageAtTime!: SqliteStatement;
private stmtFindPrivateMessageBySequence!: SqliteStatement;
private stmtFindPrivateOutgoingNearTime!: SqliteStatement;
private stmtFindPrivateReplyBySequence!: SqliteStatement;
private stmtFindPrivateReplyByTime!: SqliteStatement;
private stmtFindPrivateRecallTombstone!: SqliteStatement;
private stmtUpsertPrivateRecallTombstone!: SqliteStatement;
private stmtDeleteMessage!: SqliteStatement;
@@ -117,6 +123,10 @@ export class MessageStore {
this.stmtFindMedia = this.db.prepare(
'SELECT media_data FROM messages WHERE message_hash = ?',
);
this.stmtUpdateMedia = this.db.prepare(
`UPDATE messages SET data = ?, media_data = ?
WHERE message_hash = ? AND data = ? AND media_data IS ?`,
);
this.stmtFindMeta = this.db.prepare(
'SELECT is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp FROM messages WHERE message_hash = ?',
@@ -205,27 +215,22 @@ export class MessageStore {
LIMIT 1`,
);
this.stmtFindPrivateMessageAtTime = this.db.prepare(
`SELECT message_hash, data
FROM messages
WHERE is_group = 0 AND session_id = ? AND private_direction = ? AND timestamp = ?`,
this.stmtFindPrivateReplyBySequence = this.db.prepare(
`SELECT message_hash, sequence, sequence_authoritative, client_sequence, timestamp, data
FROM messages
WHERE is_group = 0 AND session_id = ? AND private_direction = ?
AND client_sequence = ? AND timestamp BETWEEN ? AND ?
UNION
SELECT message_hash, sequence, sequence_authoritative, client_sequence, timestamp, data
FROM messages
WHERE is_group = 0 AND session_id = ? AND private_direction = ?
AND sequence = ? AND sequence_authoritative = 1 AND timestamp BETWEEN ? AND ?`,
);
this.stmtFindPrivateMessageBySequence = this.db.prepare(
`SELECT message_hash
FROM messages
WHERE is_group = 0 AND session_id = ? AND sequence = ?
AND private_direction = ? AND sequence_authoritative = 1
LIMIT 1`,
);
this.stmtFindPrivateOutgoingNearTime = this.db.prepare(
`SELECT message_hash
FROM messages
WHERE is_group = 0 AND session_id = ? AND private_direction = ?
AND timestamp BETWEEN ? AND ?
ORDER BY ABS(timestamp - ?) ASC, sequence DESC
LIMIT 2`,
this.stmtFindPrivateReplyByTime = this.db.prepare(
`SELECT message_hash, sequence, sequence_authoritative, client_sequence, timestamp, data
FROM messages
WHERE is_group = 0 AND session_id = ? AND private_direction = ?
AND timestamp BETWEEN ? AND ?`,
);
this.stmtFindPrivateRecallTombstone = this.db.prepare(
@@ -326,6 +331,33 @@ export class MessageStore {
});
}
/** Enrich a read record without changing its identity or restoring a removed row. */
async updateMedia(
messageId: number,
expected: JsonObject,
updated: JsonObject,
): Promise<boolean> {
const before = JSON.stringify(expected);
updated = snapshotMessageEvent(updated);
return this.db.serial(async () => {
await this.initialization;
const previous = (await this.stmtFindMedia.get(messageId)) as
{ media_data: string | null } | undefined;
const media = mergeMessageMedia(
previous?.media_data ?? null,
serializeMessageMedia(updated),
);
const result = await this.stmtUpdateMedia.run(
JSON.stringify(updated),
media,
messageId,
before,
previous?.media_data ?? null,
);
return result.changes === 1;
});
}
async findMedia(messageId: number): Promise<MessageMedia[] | null> {
return this.db.serial(async () => {
await this.initialization;
@@ -618,217 +650,66 @@ export class MessageStore {
});
}
/**
* Resolve a private quote to a stored OneBot id. Prefer the quoted
* sender-local sequence, then the conversation sequence. For a
* self-sent target, also match the send receipt by time because QQ's
* quote sequence is often neither of those stored values, and the
* quote time can drift a few seconds from the send receipt.
*/
/** Resolve quotes independently of recall lookup: a reused sequence is not an identity. */
async resolvePrivateReplyMessageId(
sessionId: number,
replySequence: number,
sentBySelf: boolean,
timestamp?: number,
replyElements?: readonly MessageElement[],
excludedMessage?: PrivateQuoteSource,
): Promise<number | null> {
return this.db.serial(async () => {
await this.initialization;
if (Number.isSafeInteger(replySequence) && replySequence > 0) {
const byClientSequence = await this.findPrivateMessageId(
sessionId,
replySequence,
sentBySelf,
timestamp,
);
if (byClientSequence !== null) {
return byClientSequence;
}
const byConversationSequence = await this.findPrivateMessageIdBySequence(
sessionId,
replySequence,
sentBySelf,
);
if (byConversationSequence !== null) {
return byConversationSequence;
}
}
if (!sentBySelf) {
return null;
}
const byExactTime = await this.findPrivateMessageIdAtTime(
sessionId,
true,
const hasTime = isUsableQuoteTime(timestamp);
const lower = hasTime ? timestamp - PRIVATE_QUOTE_MAX_DRIFT_SECONDS : 0;
const upper = hasTime
? timestamp + PRIVATE_QUOTE_MAX_DRIFT_SECONDS
: Number.MAX_SAFE_INTEGER;
const key = {
sequence: replySequence,
sentBySelf,
timestamp,
replyElements,
);
if (byExactTime !== null) {
return byExactTime;
}
const byNearbyTime = await this.findUniquePrivateOutgoingNearTime(sessionId, timestamp);
if (byNearbyTime !== null) {
return byNearbyTime;
}
return null;
});
}
async findPrivateMessageIdAtTime(
sessionId: number,
sentBySelf: boolean,
timestamp?: number,
replyElements?: readonly MessageElement[],
): Promise<number | null> {
return this.db.serial(async () => {
await this.initialization;
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) {
return null;
}
if (!isUsablePrivateQuoteTime(timestamp)) {
return null;
}
const rows = (await this.stmtFindPrivateMessageAtTime.all(
sessionId,
sentBySelf ? 1 : 0,
timestamp,
)) as { message_hash: number; data: string | null }[];
if (rows.length === 0) {
return null;
}
let matches = rows;
if (rows.length > 1) {
const text =
replyElements?.length && replyElements.every((e) => e.type === 'text')
? replyElements.map((e) => e.text ?? '').join('')
: null;
const candidates = text
? rows
.map((row) => ({ row, preview: cachedQuoteText(row.data) }))
.filter(
({ preview }) => preview === null || preview.text.startsWith(text),
)
elements: replyElements,
exclude: excludedMessage,
};
const rows =
Number.isSafeInteger(replySequence) && replySequence > 0
? ((await this.stmtFindPrivateReplyBySequence.all(
sessionId,
sentBySelf ? 1 : 0,
replySequence,
lower,
upper,
sessionId,
sentBySelf ? 1 : 0,
replySequence,
lower,
upper,
)) as PrivateReplyRow[])
: [];
matches =
candidates.length === 1 &&
candidates[0]!.preview?.plain &&
candidates[0]!.preview.text === text
? [candidates[0]!.row]
: [];
let selected = selectPrivateQuote(rows.map(privateReplyCandidate), key);
if (matches.length !== 1) {
log.debug(
'private quote time is ambiguous: peer=%d time=%d candidates=%d contentMatches=%d',
sessionId,
timestamp,
rows.length,
matches.length,
);
return null;
}
}
const row = matches[0]!;
if (!isValidMessageId(row.message_hash)) {
throw new Error(
`private message lookup matched invalid message id ${String(row.message_hash)}`,
);
}
return row.message_hash;
});
}
async findPrivateMessageIdBySequence(
sessionId: number,
sequence: number,
sentBySelf: boolean,
): Promise<number | null> {
return this.db.serial(async () => {
await this.initialization;
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) {
return null;
}
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
return null;
}
const row = (await this.stmtFindPrivateMessageBySequence.get(
sessionId,
sequence,
sentBySelf ? 1 : 0,
)) as { message_hash: number } | undefined;
if (!row) {
return null;
}
if (!isValidMessageId(row.message_hash)) {
throw new Error(
`private message lookup matched invalid message id ${String(row.message_hash)}`,
);
}
return row.message_hash;
});
}
async findUniquePrivateOutgoingNearTime(
sessionId: number,
timestamp?: number,
): Promise<number | null> {
return this.db.serial(async () => {
await this.initialization;
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) {
return null;
}
if (!isUsablePrivateQuoteTime(timestamp)) {
return null;
}
for (const windowSeconds of PRIVATE_REPLY_TIME_WINDOWS_SECONDS) {
const rows = (await this.stmtFindPrivateOutgoingNearTime.all(
if (!selected.candidate && selected.reason !== 'ambiguous' && sentBySelf && hasTime) {
const nearby = (await this.stmtFindPrivateReplyByTime.all(
sessionId,
1,
timestamp - windowSeconds,
timestamp + windowSeconds,
timestamp,
)) as Array<{ message_hash: number }>;
if (rows.length !== 1) {
continue;
}
if (!isValidMessageId(rows[0].message_hash)) {
throw new Error(
`private message lookup matched invalid message id ${String(rows[0].message_hash)}`,
);
}
return rows[0].message_hash;
lower,
upper,
)) as PrivateReplyRow[];
selected = selectPrivateQuote(nearby.map(privateReplyCandidate), key);
}
return null;
log.trace(
'private quote lookup: peer=%d seq=%d outgoing=%s time=%s result=%s messageId=%s',
sessionId,
replySequence,
sentBySelf,
timestamp,
selected.reason,
selected.candidate?.id ?? 'unknown',
);
return selected.candidate?.id ?? null;
});
}
@@ -1148,64 +1029,27 @@ function eventPrivateDirection(isGroup: boolean, event: JsonObject): number {
return -1;
}
const PRIVATE_REPLY_TIME_WINDOWS_SECONDS = [5, 30] as const;
/** Unknown, truncated, and media previews remain possible competing matches. */
function cachedQuoteText(data: string | null): { text: string; plain: boolean } | null {
if (!data) {
return null;
}
const event = JSON.parse(data) as JsonObject;
if (typeof event.message === 'string') {
return event.message.includes('[CQ:')
? null
: { text: cqUnescape(event.message), plain: true };
}
if (!Array.isArray(event.message) || event.message.length === 0) {
return null;
}
const segments = event.message as JsonObject[];
const labels: Record<string, string> = {
image: '[图片]',
record: '[语音]',
video: '[视频]',
file: '[文件]',
face: '[表情]',
mface: '[表情]',
forward: '[聊天记录]',
json: '[卡片]',
xml: '[卡片]',
};
const parts: string[] = [];
let plain = true;
for (const segment of segments) {
const body = segment?.data as JsonObject | undefined;
if (segment?.type === 'text' && typeof body?.text === 'string') {
parts.push(body.text);
} else if (typeof segment?.type === 'string' && labels[segment.type]) {
parts.push(typeof body?.summary === 'string' ? body.summary : labels[segment.type]!);
plain = false;
} else {
return null;
}
}
return { text: parts.join(''), plain };
interface PrivateReplyRow extends SqliteRow {
message_hash: number;
sequence: number;
sequence_authoritative: number;
client_sequence: number;
timestamp: number;
data: string | null;
}
function isUsablePrivateQuoteTime(timestamp: number | undefined): timestamp is number {
return (
timestamp !== undefined &&
Number.isSafeInteger(timestamp) &&
timestamp > 0 &&
timestamp < Number.MAX_SAFE_INTEGER
);
function privateReplyCandidate(row: PrivateReplyRow) {
if (!isValidMessageId(row.message_hash)) {
throw new Error(`private quote matched invalid message id ${String(row.message_hash)}`);
}
return {
id: row.message_hash,
sequence: row.sequence_authoritative === 1 ? row.sequence : 0,
clientSequence: row.client_sequence,
timestamp: row.timestamp,
preview: cachedQuotePreview(row.data),
};
}
function validatePrivateRecallKey(
+123 -68
View File
@@ -7,6 +7,8 @@ import {
} from '@snowluma/protocol/dataline/device-contacts';
import {
formatGroupRequestFlag,
groupRequestSubType,
isSelfGroupInvitation,
type GroupMemberInfo,
type GroupRequestInfo,
type UserProfileInfo,
@@ -14,6 +16,7 @@ import {
import type { QidianCorpInfo } from '@snowluma/protocol/services/qidian/fetch-corp-info';
import type { OneBotInstanceContext } from '../instance-context';
import type { JsonObject } from '../types';
import { formatFriend, formatPublicProfile } from './contact-profile';
const REQUESTER_PROFILE_CONCURRENCY = 4;
const log = createLogger('OneBot.Contacts');
@@ -49,21 +52,28 @@ async function fetchSingleGroupMembers(
}
}
function toFriendRow(friend: { uin: number; nickname: string; remark: string }): JsonObject {
return {
user_id: friend.uin,
nickname: friend.nickname,
remark: friend.remark,
};
}
export async function getFriendList(bridge: BridgeInterface): Promise<JsonObject[]> {
export async function getFriendList(
bridge: BridgeInterface,
withProfile = false,
): Promise<JsonObject[]> {
let rows: JsonObject[];
try {
rows = (await bridge.apis.contacts.fetchFriendList()).map(toFriendRow);
} catch {
rows = bridge.identity.friends.map(toFriendRow);
rows = (await bridge.apis.contacts.fetchFriendList({ withProfile })).map((friend) =>
formatFriend(friend),
);
} catch (error) {
log.warn(
'friend list refresh failed: withProfile=%s error=%s',
withProfile,
error instanceof Error ? error.message : String(error),
);
if (withProfile) {
throw error;
}
rows = bridge.identity.friends.map((friend) => formatFriend(friend));
}
const occupied = new Set(rows.map((row) => Number(row.user_id)));
@@ -302,7 +312,7 @@ export async function getGroupMemberInfo(
): Promise<JsonObject | null> {
const cached = bridge.identity.findGroupMember(groupId, userId);
if (noCache || !cached || cached.isRobot === undefined) {
if (noCache || !cached || cached.isRobot === undefined || cached.card === undefined) {
await fetchSingleGroupMembers(bridge, groupId, noCache === true);
}
@@ -393,6 +403,8 @@ function formatStrangerInfo(p: UserProfileInfo, corp?: QidianCorpInfo | null): J
...(p.svipFlag !== undefined ? { is_vip: p.svipFlag } : {}),
...(p.yearVipFlag !== undefined ? { is_years_vip: p.yearVipFlag } : {}),
...(p.vipLevel !== undefined ? { vip_level: p.vipLevel } : {}),
...(p.vipFlag !== undefined ? { is_qq_vip: p.vipFlag } : {}),
...formatPublicProfile(p.profile),
status: p.status ?? 0,
extStatus: p.extStatus ?? 0,
ext_status: p.extStatus ?? 0,
@@ -445,7 +457,12 @@ export async function getStrangerInfo(
const p = await bridge.apis.contacts.fetchUserProfile(userId);
const corp = await strangerCorpInfo(bridge, p);
return formatStrangerInfo(p, corp);
} catch {
} catch (error) {
log.warn(
'user profile refresh failed, checking cached profile: user=%d error=%s',
userId,
error instanceof Error ? error.message : String(error),
);
const p = bridge.identity.findUserProfile(userId);
if (p) {
@@ -474,26 +491,46 @@ export async function getStrangerInfo(
}
}
async function resolveRequesterUins(
async function resolveGroupRequestUins(
bridge: BridgeInterface,
requests: readonly GroupRequestInfo[],
): Promise<Map<string, { uin: number; name: string }>> {
const resolved = new Map<string, { uin: number; name: string }>();
const unresolved = new Set<string>();
const names = new Map<string, string>();
const roles = new Map<string, string>();
const unresolvedUins = new Set<number>();
for (const request of requests) {
const actor = groupRequestActor(request);
const actors = requests.flatMap((request) =>
(['target', 'invitor', 'operator'] as const).map((role) => ({
...groupRequestPerson(request, role),
groupId: request.groupId,
role,
})),
);
for (const actor of actors) {
const uid = actor.uid;
if (uid) {
roles.set(uid, actor.role === 'target' ? 'requester' : actor.role);
}
if (actor.name) {
names.set(uid || `uin:${actor.uin}`, actor.name);
}
if (uid && actor.uin > 0 && actor.name) {
resolved.set(uid, { uin: actor.uin, name: actor.name });
unresolved.delete(uid);
if (actor.uin > 0) {
resolved.set(uid || `uin:${actor.uin}`, { uin: actor.uin, name: actor.name });
if (uid) {
unresolved.delete(uid);
}
if (!actor.name) {
unresolvedUins.add(actor.uin);
}
continue;
}
@@ -503,21 +540,21 @@ async function resolveRequesterUins(
}
const cached =
bridge.identity.findUinByUid(uid, request.groupId) ??
bridge.identity.findUinByUid(uid, actor.groupId) ??
bridge.identity.findUinByUid(uid);
if (cached && cached > 0 && actor.name) {
if (cached && cached > 0) {
resolved.set(uid, { uin: cached, name: actor.name });
if (!actor.name) {
unresolvedUins.add(cached);
}
} else {
unresolved.add(uid);
}
continue;
}
if (actor.uin > 0 && !actor.name) {
unresolvedUins.add(actor.uin);
}
}
const profiles = await mapWithConcurrency(
@@ -530,13 +567,16 @@ async function resolveRequesterUins(
profile = await bridge.apis.contacts.fetchUserProfileByUid(uid);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`failed to resolve requester UIN for UID ${uid}: ${message}`, {
cause: error,
});
throw new Error(
`failed to resolve ${roles.get(uid)} UIN for UID ${uid}: ${message}`,
{
cause: error,
},
);
}
if (!Number.isSafeInteger(profile.uin) || profile.uin <= 0) {
throw new Error(`failed to resolve requester UIN for UID ${uid}`);
throw new Error(`failed to resolve ${roles.get(uid)} UIN for UID ${uid}`);
}
return [uid, profile] as const;
@@ -556,7 +596,12 @@ async function resolveRequesterUins(
async (uin) => {
try {
return [uin, await bridge.apis.contacts.fetchUserProfile(uin)] as const;
} catch {
} catch (error) {
log.warn(
'group request actor nickname unavailable: uin=%d error=%s',
uin,
error instanceof Error ? error.message : String(error),
);
return [uin, undefined] as const;
}
},
@@ -573,34 +618,18 @@ async function resolveRequesterUins(
return resolved;
}
/** Join request (7) or invite that still needs an admin (5 / mapped 22). */
function isJoinOrInviteNotify(notifyType: number | undefined): boolean {
return (
notifyType === undefined ||
notifyType === 1 ||
notifyType === 5 ||
notifyType === 7 ||
notifyType === 22
);
}
function groupRequestActor(request: GroupRequestInfo): {
function groupRequestPerson(
request: GroupRequestInfo,
role: 'target' | 'invitor' | 'operator',
): {
uid: string;
uin: number;
name: string;
} {
if (request.notifyType === 1) {
return {
uid: request.invitorUid,
uin: request.invitorUin,
name: request.invitorName,
};
}
return {
uid: request.targetUid,
uin: request.targetUin,
name: request.targetName,
uid: request[`${role}Uid`],
uin: request[`${role}Uin`],
name: request[`${role}Name`],
};
}
@@ -621,11 +650,7 @@ export async function getGroupSystemMessages(
const unique = new Map<string, GroupRequestInfo>();
for (const request of [...main, ...filtered]) {
if (!isJoinOrInviteNotify(request.notifyType)) {
continue;
}
if (request.eventType <= 0) {
if (!groupRequestSubType(request)) {
continue;
}
@@ -647,21 +672,47 @@ export async function getGroupSystemMessages(
return true;
});
const requesterUins = await resolveRequesterUins(bridge, requests);
log.debug(
'group request list: main=%d filtered=%d relevant=%d selected=%d group=%s onlyPending=%s',
main.length,
filtered.length,
unique.size,
requests.length,
query.groupId ?? 'all',
Boolean(query.onlyPending),
);
const actorUins = await resolveGroupRequestUins(bridge, requests);
return requests.map((request) => {
const actor = groupRequestActor(request);
const resolved =
(actor.uid ? requesterUins.get(actor.uid) : undefined) ??
(actor.uin > 0 ? requesterUins.get(`uin:${actor.uin}`) : undefined);
const person = (role: 'target' | 'invitor' | 'operator') => {
const actor = groupRequestPerson(request, role);
const resolved =
(actor.uid ? actorUins.get(actor.uid) : undefined) ??
(actor.uin > 0 ? actorUins.get(`uin:${actor.uin}`) : undefined);
const uin = actor.uin || resolved?.uin || 0;
const name = actor.name || actorUins.get(`uin:${uin}`)?.name || resolved?.name || '';
return { uin, name, status: uin > 0 ? 'known' : 'unknown' };
};
const target = person('target');
const invitor = person('invitor');
const operator = person('operator');
const requester = isSelfGroupInvitation(request) ? invitor : target;
return {
group_id: request.groupId,
group_name: request.groupName,
request_id: request.sequence,
requester_uin: resolved?.uin ?? actor.uin,
requester_nick: resolved?.name || actor.name,
invitor_uin: request.invitorUin,
invitor_nick: request.invitorName,
requester_uin: requester.uin,
requester_nick: requester.name,
target_uin: target.uin,
target_nick: target.name,
target_status: target.status,
invitor_uin: invitor.uin,
invitor_nick: invitor.name,
invitor_status: invitor.status,
operator_uin: operator.uin,
operator_nick: operator.name,
operator_status: operator.status,
message: request.comment,
checked: request.state !== 1,
flag: formatGroupRequestFlag(request),
@@ -710,6 +761,10 @@ function formatGroupMember(
);
}
if (member.card === undefined) {
throw new Error(`group member card unavailable: group=${groupId} member=${member.uin}`);
}
const qage = accountAge(profile?.regTime);
return {
group_id: groupId,
@@ -0,0 +1,64 @@
import type { FriendInfo, ProfilePrivilege, PublicProfileFields } from '@snowluma/protocol/qq-info';
import type { JsonObject } from '../types';
function formatPrivilege(value: ProfilePrivilege): JsonObject {
return {
...(value.type !== undefined ? { type: value.type } : {}),
...(value.level !== undefined ? { level: value.level } : {}),
...(value.flag !== undefined ? { flag: value.flag } : {}),
...(value.isBig !== undefined ? { is_big: value.isBig } : {}),
...(value.jumpUrl !== undefined ? { jump_url: value.jumpUrl } : {}),
...(value.iconUrl !== undefined ? { icon_url: value.iconUrl } : {}),
...(value.deluxeIconUrl !== undefined ? { deluxe_icon_url: value.deluxeIconUrl } : {}),
};
}
export function formatPublicProfile(profile: PublicProfileFields = {}): JsonObject {
const result: JsonObject = {};
for (const [source, target] of [
['sign', 'long_nick'],
['sex', 'sex'],
['age', 'age'],
['level', 'level'],
['birthdayYear', 'birthday_year'],
['birthdayMonth', 'birthday_month'],
['birthdayDay', 'birthday_day'],
['phoneNum', 'phone_num'],
['email', 'email'],
['country', 'country'],
['province', 'province'],
['city', 'city'],
['college', 'college'],
['vipFlag', 'is_qq_vip'],
['svipFlag', 'is_vip'],
['yearVipFlag', 'is_years_vip'],
['vipLevel', 'vip_level'],
] as const) {
if (profile[source] !== undefined) {
result[target] = profile[source];
}
}
if (profile.privilegeIcons !== undefined) {
result.privilege_icons = {
...(profile.privilegeIcons.jumpUrl !== undefined
? { jump_url: profile.privilegeIcons.jumpUrl }
: {}),
open: profile.privilegeIcons.open.map(formatPrivilege),
closed: profile.privilegeIcons.closed.map(formatPrivilege),
};
}
return result;
}
export function formatFriend(friend: FriendInfo, categoryId = friend.categoryId): JsonObject {
return {
user_id: friend.uin,
nickname: friend.nickname,
remark: friend.remark,
...(categoryId !== undefined ? { category_id: categoryId } : {}),
...formatPublicProfile(friend.profile),
};
}
+64 -33
View File
@@ -1,30 +1,18 @@
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { MessageElementOf } from '@snowluma/protocol/events';
import { createLogger } from '@snowluma/common/logger';
import type { ImageUrlResolver } from '../event-converter';
import type { CachedImage, MediaStore } from '../media-store';
import type { MessageStore } from '../message-store';
import type { OneBotInstanceContext } from '../instance-context';
import { resolveRemoteMediaUrl } from '../media-url-resolver';
import { imageMd5FromFile, isStoredMediaSegment } from '../message-media';
import { segmentsToRawMessage } from '../helper/cq';
import { pttTransKey, requestPttTransText } from './ptt-trans-waiter';
import type { JsonObject, JsonValue } from '../types';
import type { JsonObject } from '../types';
const log = createLogger('OneBot');
type StoredMediaSegment = JsonObject & { type: 'image' | 'record' | 'video'; data: JsonObject };
function isStoredMediaSegment(segment: JsonValue): segment is StoredMediaSegment {
return (
segment !== null &&
typeof segment === 'object' &&
!Array.isArray(segment) &&
(segment.type === 'image' || segment.type === 'record' || segment.type === 'video') &&
segment.data !== null &&
typeof segment.data === 'object' &&
!Array.isArray(segment.data)
);
}
export async function refreshMessageMedia(
ref: Pick<OneBotInstanceContext, 'bridge' | 'messageStore' | 'mediaStore' | 'converterCtx'>,
messageId: number,
@@ -36,13 +24,17 @@ export async function refreshMessageMedia(
const segments = event.message.filter(isStoredMediaSegment);
const voiceVideoSegments = segments.filter((segment) => segment.type !== 'image');
const media =
voiceVideoSegments.length > 0
? (await ref.messageStore.findMedia(messageId))?.filter(
(element) => element.type !== 'image',
)
: null;
const meta = voiceVideoSegments.length > 0 ? await ref.messageStore.findMeta(messageId) : null;
const snapshots = segments.length > 0 ? await ref.messageStore.findMedia(messageId) : null;
const meta = segments.length > 0 ? await ref.messageStore.findMeta(messageId) : null;
const media = snapshots?.filter((element) => element.type !== 'image');
const aligned =
snapshots?.length === segments.length &&
snapshots.every((element, index) => element.type === segments[index]!.type);
if (snapshots && !aligned && segments.some((segment) => segment.type === 'image')) {
log.warn('[get_msg] image metadata association inconsistent message_id=%d', messageId);
}
// Validate the ordered association once; a filename lookup can select another upload.
const voiceVideo =
meta &&
@@ -64,19 +56,58 @@ export async function refreshMessageMedia(
let url: string | null;
if (segment.type === 'image') {
const file =
typeof segment.data.file === 'string'
? segment.data.file
: segment.data.file_id;
const snapshot = aligned ? snapshots?.[index] : undefined;
const ownUrl =
typeof segment.data.url === 'string' && /^https?:\/\//i.test(segment.data.url)
? segment.data.url
: '';
if (typeof file !== 'string' || !file) {
continue;
if (meta && (snapshot?.type === 'image' || ownUrl)) {
const element: MessageElementOf<'image'> =
snapshot?.type === 'image'
? snapshot
: {
type: 'image' as const,
subType:
typeof segment.data.sub_type === 'number'
? segment.data.sub_type
: 0,
};
const source = element.imageUrl || element.url || ownUrl;
if (typeof source === 'string' && /^https?:\/\//i.test(source)) {
url = ref.converterCtx.imageUrlResolver
? await ref.converterCtx.imageUrlResolver(
{ ...element, imageUrl: source },
meta.isGroup,
)
: source;
} else {
url = null;
}
} else if (!snapshots) {
const file =
typeof segment.data.file === 'string'
? segment.data.file
: segment.data.file_id;
if (typeof file !== 'string' || !file) {
continue;
}
const cached = await ref.mediaStore.findImage(file);
const md5 = imageMd5FromFile(file);
url =
cached &&
meta &&
cached.isGroup === meta.isGroup &&
cached.sessionId === meta.targetId &&
(!md5 || cached.md5Hex?.toLowerCase() === md5)
? await resolveImageUrl(cached, ref.converterCtx.imageUrlResolver)
: null;
} else {
url = null;
}
url = await resolveImageUrl(
await ref.mediaStore.findImage(file),
ref.converterCtx.imageUrlResolver,
);
} else {
if (!voiceVideo) {
continue;
+337 -212
View File
@@ -15,6 +15,7 @@ import { getVideoSourceSize, MAX_VIDEO_SIZE } from '@snowluma/protocol/highway/v
import { guessFileNameFromUrl } from '@snowluma/protocol/highway/utils';
import type { MessageSendResult } from '../api-handler';
import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../event-converter';
import { applyMessageIdResolver } from '../event-converter/utils';
import { segmentsToRawMessage } from '../helper/cq';
import { persistHistoryEvent, toHistoryInt } from '../history-persistence';
import type { OneBotInstanceContext } from '../instance-context';
@@ -28,6 +29,12 @@ import {
import type { MessageStore } from '../message-store';
import { sameSelfSentMessage } from '../self-sent-event';
import { replyPreviewElements } from '../reply-preview';
import {
isUsableQuoteTime,
messageQuotePreview,
PRIVATE_QUOTE_MAX_DRIFT_SECONDS,
selectPrivateQuote,
} from '../private-quote';
import {
hasAuthoritativeSequence,
type JsonArray,
@@ -424,225 +431,296 @@ export async function getFriendHistory(
return out;
}
/**
* Back-fill the message a freshly-received reply points to, when the local store
* doesn't have the full event (e.g. a message from before SnowLuma was running,
* or one it never observed). Fetches the quoted message from the server —
* group via `SsoGetGroupMsg`, C2C via timestamp roaming, both through the shared
* history throttle gate — and persists it under the SAME id the reply resolves
* to, so a subsequent `get_msg` (or quote lookup) hits. Private replies carry
* the quoted sender's local sequence, so they are matched through a timestamp
* roam page rather than incorrectly used as an NT-sequence range anchor.
*
* No-op when: the event isn't a group/friend message, has no reply, the target
* is already stored, the uid can't be resolved, the fetch returns nothing, or
* it errors. Meant to be awaited before dispatch so the consumer's get_msg —
* which an approval bot fires right after seeing the reply — sees the message.
*/
export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant): Promise<void> {
let isGroup: boolean;
let session: number;
if (event.kind === 'group_message') {
isGroup = true;
session = event.groupId;
} else if (event.kind === 'friend_message') {
isGroup = false;
session = event.peerUin ?? event.senderUin;
} else {
return;
/** Resolve and prepare quotes before conversion, without changing the protocol event. */
export async function backfillReplyTarget(
ref: HistoryRef,
event: QQEventVariant,
): Promise<QQEventVariant> {
if (event.kind !== 'group_message' && event.kind !== 'friend_message') {
return event;
}
const session =
event.kind === 'group_message' ? event.groupId : (event.peerUin ?? event.senderUin);
if (!Number.isInteger(session) || session <= 0) {
return;
return event;
}
const reply = event.elements.find(
(e: MessageElement) =>
e.type === 'reply' && Number.isInteger(e.replySeq) && (e.replySeq ?? 0) > 0,
);
const replySeq = reply?.replySeq ?? 0;
const elements: MessageElement[] = [];
let changed = false;
if (replySeq <= 0) {
return;
for (const element of event.elements) {
if (
element.type !== 'reply' ||
!Number.isSafeInteger(element.replySeq) ||
element.replySeq <= 0
) {
elements.push(element);
continue;
}
const messageId =
event.kind === 'group_message'
? await backfillGroupReply(ref, session, element)
: await backfillPrivateReply(ref, session, event, element);
elements.push({ ...element, replyMessageId: messageId });
changed = true;
}
const quotedSender = reply?.replySenderUin ?? (isGroup ? 0 : session);
const eventName = isGroup
? GROUP_MESSAGE_EVENT
: privateMessageEventName(quotedSender === ref.selfId, false);
const resolvedId = await ref.converterCtx.messageIdResolver?.(
isGroup,
return changed ? { ...event, elements } : event;
}
async function backfillPrivateReply(
ref: HistoryRef,
session: number,
event: FriendMessage,
reply: MessageElementOf<'reply'>,
): Promise<number> {
const sender = reply.replySenderUin ?? session;
const sentBySelf = sender === ref.selfId;
const hasNtSequence = (event.ntMsgSeq ?? 0) > 0 && event.sequenceAuthoritative !== false;
const currentId = await applyMessageIdResolver(
ref.converterCtx.messageIdResolver,
false,
session,
replySeq,
eventName,
reply?.replyTime && reply.replyTime > 0 ? reply.replyTime : Number.MAX_SAFE_INTEGER,
hasNtSequence ? event.ntMsgSeq! : event.msgSeq,
privateMessageEventName(event.senderUin === ref.selfId, hasNtSequence),
);
const exclude = {
id: currentId,
sequence: hasNtSequence ? event.ntMsgSeq! : 0,
clientSequence: event.clientSeq ?? event.msgSeq,
timestamp: event.time,
sentBySelf: event.senderUin === ref.selfId,
};
const storedId = await ref.messageStore.resolvePrivateReplyMessageId(
session,
reply.replySeq,
sentBySelf,
reply.replyTime,
reply.replyElements,
exclude,
);
if (storedId !== null && (await ref.messageStore.findEvent(storedId))) {
return storedId;
}
let history: FriendMessage[] = [];
try {
const uid = await ref.bridge.resolveUserUid(session);
if (uid) {
const time = isUsableQuoteTime(reply.replyTime) ? reply.replyTime : event.time;
history = await ref.bridge.apis.message.getC2cLatestHistory(
uid,
20,
ref.selfId,
Math.min(0xffff_ffff, Math.max(1, time + 1)),
);
}
} catch (error) {
log.warn(
'private quote history failed: peer=%d seq=%d error=%s',
session,
reply.replySeq,
error instanceof Error ? error.message : String(error),
);
}
const selection = selectPrivateQuote(
history
.filter(
(candidate) =>
candidate.senderUin === sender &&
candidate.selfUin === ref.selfId &&
(candidate.peerUin ??
(candidate.senderUin === ref.selfId ? session : candidate.senderUin)) ===
session,
)
.map((source) => ({
source: { ...source, peerUin: session },
sequence: source.sequenceAuthoritative !== false ? (source.ntMsgSeq ?? 0) : 0,
clientSequence: source.clientSeq ?? source.msgSeq,
timestamp: source.time,
preview: messageQuotePreview(source.elements),
})),
{
sequence: reply.replySeq,
sentBySelf,
timestamp: reply.replyTime,
elements: reply.replyElements,
exclude,
},
);
const fetched = selection.candidate?.source;
const knownMeta = storedId !== null ? await ref.messageStore.findMeta(storedId) : null;
if (fetched) {
const json = await convertEvent(ref.converterCtx, fetched);
if (!json) {
throw new Error('private quote history could not be converted');
}
// Preserve an existing legacy id only when the fetched message confirms
// the same stored identity, rather than assigning a quote-sequence hash.
if (
storedId !== null &&
knownMeta &&
Math.abs(knownMeta.timestamp - fetched.time) <= PRIVATE_QUOTE_MAX_DRIFT_SECONDS &&
(knownMeta.sequenceAuthoritative !== false &&
knownMeta.sequence > 0 &&
fetched.sequenceAuthoritative !== false &&
(fetched.ntMsgSeq ?? 0) > 0
? knownMeta.sequence === fetched.ntMsgSeq
: knownMeta.clientSequence > 0 &&
knownMeta.clientSequence === (fetched.clientSeq ?? fetched.msgSeq))
) {
json.message_id = storedId;
}
const persisted = await persistHistoryEvent(ref.messageStore, json, session, fetched);
const id = persisted ? toHistoryInt(json.message_id) : 0;
log.trace(
'private quote history resolved: peer=%d seq=%d result=%s messageId=%d',
session,
reply.replySeq,
persisted ? selection.reason : 'recalled',
id,
);
return id;
}
// Embedded text may fill the body of a verified existing identity. It cannot
// create a new private-message identity or overwrite an unrelated record.
if (storedId !== null && knownMeta && reply.replyElements?.length) {
const segments = await elementsToOneBotSegments(
ref.converterCtx,
reply.replyElements.filter((element) => element.type !== 'reply'),
false,
session,
);
const json = buildBackfillEvent(
storedId,
knownMeta.clientSequence || knownMeta.sequence,
sender,
knownMeta.timestamp,
segments,
ref.selfId,
false,
session,
);
const persisted = await ref.messageStore.storeHistoryEvent(
storedId,
false,
session,
knownMeta.sequence,
knownMeta.eventName,
json,
{ sequenceAuthoritative: knownMeta.sequenceAuthoritative, meta: knownMeta },
);
return persisted ? storedId : 0;
}
log.trace(
'private quote unresolved: peer=%d seq=%d time=%s result=%s knownId=%s',
session,
reply.replySeq,
reply.replyTime,
selection.reason,
storedId ?? 'unknown',
);
return storedId ?? 0;
}
async function backfillGroupReply(
ref: HistoryRef,
session: number,
reply: MessageElementOf<'reply'>,
): Promise<number> {
const resolvedId = await ref.converterCtx.messageIdResolver?.(
true,
session,
reply.replySeq,
GROUP_MESSAGE_EVENT,
reply.replyTime && reply.replyTime > 0 ? reply.replyTime : Number.MAX_SAFE_INTEGER,
reply.replyElements,
);
const targetId =
Number.isInteger(resolvedId) && resolvedId !== 0
? (resolvedId as number)
: hashMessageIdInt32(replySeq, session, eventName);
: hashMessageIdInt32(reply.replySeq, session, GROUP_MESSAGE_EVENT);
if (await ref.messageStore.findEvent(targetId)) {
return;
} // Tier 0: already have the full event
return targetId;
}
let fetched: GroupMessage | null = null;
// Tier 1: fetch the quoted message from the server, keyed under the exact id
// the reply resolves to. Groups can query `replySeq` directly. C2C replies
// carry a sender-local client sequence, while SsoGetC2cMsg ranges use the
// conversation-wide NT sequence; use the quote time as a roam cursor and
// match both direction and client sequence instead.
try {
let fetched: GroupMessage | FriendMessage | null = null;
if (isGroup) {
fetched = await ref.bridge.apis.message.getGroupMessageBySeq(
session,
replySeq,
ref.selfId,
);
} else {
const friendUid = await ref.bridge.resolveUserUid(session);
if (friendUid) {
const quoteTime =
reply?.replyTime && reply.replyTime > 0 ? reply.replyTime : event.time;
const beforeTime = Math.min(0xffff_ffff, Math.max(1, quoteTime + 1));
const candidates = await ref.bridge.apis.message.getC2cLatestHistory(
friendUid,
20,
ref.selfId,
beforeTime,
);
const quotedSentBySelf = quotedSender === ref.selfId;
fetched =
[...candidates]
.reverse()
.find(
(candidate) =>
(candidate.clientSeq ?? candidate.msgSeq) === replySeq &&
(candidate.senderUin === ref.selfId) === quotedSentBySelf &&
(!reply?.replyTime || candidate.time <= reply.replyTime),
) ?? null;
}
}
if (fetched) {
const json = await convertEvent(ref.converterCtx, fetched);
if (json) {
json.message_id = targetId;
if (fetched.kind === 'group_message') {
await ref.messageStore.storeEvent(
targetId,
true,
session,
replySeq,
eventName,
json,
);
} else {
const serverSequence = fetched.ntMsgSeq ?? 0;
const sequenceAuthoritative =
fetched.sequenceAuthoritative !== false && serverSequence > 0;
await ref.messageStore.storeMeta(targetId, {
isGroup: false,
targetId: session,
sequence: serverSequence,
sequenceAuthoritative,
eventName,
clientSequence: fetched.clientSeq ?? fetched.msgSeq,
privateDirection:
fetched.senderUin === ref.selfId ? 'outgoing' : 'incoming',
random: fetched.msgId,
timestamp: fetched.time,
});
await ref.messageStore.storeEvent(
targetId,
false,
session,
serverSequence,
eventName,
json,
{ sequenceAuthoritative },
);
}
return;
}
}
} catch (err) {
fetched = await ref.bridge.apis.message.getGroupMessageBySeq(
session,
reply.replySeq,
ref.selfId,
);
} catch (error) {
log.warn(
'reply-target backfill tier-1 failed (%s)',
err instanceof Error ? err.message : String(err),
error instanceof Error ? error.message : String(error),
);
}
// Tier 2: reconstruct from the quoted message's own elements, which the push
// embeds in SrcMsg.elems — no server round-trip. Covers messages the server
// won't return (expired, self-c2c, file-only) but whose content rode along.
if (reply?.replyElements?.length) {
try {
const segments = (await elementsToOneBotSegments(
ref.converterCtx,
reply.replyElements,
isGroup,
session,
)) as JsonArray;
const fallback = buildBackfillEvent(
targetId,
replySeq,
quotedSender,
reply.replyTime ?? 0,
segments,
ref.selfId,
isGroup,
session,
);
// Inline quote metadata proves what was displayed, but not that replySeq
// still names a server-backed roam message. Keep it queryable via
// get_msg without letting it become a history/recall/reply anchor.
if (fetched) {
const json = await convertEvent(ref.converterCtx, fetched);
if (json) {
json.message_id = targetId;
await ref.messageStore.storeEvent(
targetId,
isGroup,
true,
session,
replySeq,
eventName,
fallback,
{ sequenceAuthoritative: false },
);
return;
} catch (err) {
log.warn(
'reply-target backfill tier-2 failed (%s)',
err instanceof Error ? err.message : String(err),
reply.replySeq,
GROUP_MESSAGE_EVENT,
json,
);
return targetId;
}
}
// Tier 3: minimal `[引用消息]` placeholder so get_msg(reply_id) never returns
// "message not found" — an approval bot that fires get_msg right after seeing
// the reply gets a well-formed (if sparse) event instead of an error.
const placeholder = buildBackfillEvent(
let segments: JsonArray = [{ type: 'text', data: { text: '[引用消息]' } }];
if (reply.replyElements?.length) {
segments = await elementsToOneBotSegments(
ref.converterCtx,
reply.replyElements,
true,
session,
);
}
const fallback = buildBackfillEvent(
targetId,
replySeq,
quotedSender,
reply?.replyTime ?? 0,
[{ type: 'text', data: { text: '[引用消息]' } }],
reply.replySeq,
reply.replySenderUin ?? 0,
reply.replyTime ?? 0,
segments,
ref.selfId,
isGroup,
true,
session,
);
await ref.messageStore.storeEvent(
targetId,
isGroup,
true,
session,
replySeq,
eventName,
placeholder,
reply.replySeq,
GROUP_MESSAGE_EVENT,
fallback,
{ sequenceAuthoritative: false },
);
return targetId;
}
// Build a stored-message event for a backfilled reply target (Tier 2/3).
@@ -1331,9 +1409,8 @@ export async function sendGroupMessage(
throw new Error('message is empty');
}
// Two sub-paths for group file segments:
// a) has url/path but no file_id → upload() which internally calls publish()
// b) has file_id from a prior upload_group_file → publish() only
// Prepare all file uploads before publishing any part of the message.
// Whether storage is temporary is only known after the upload preflight.
let allFileElements = elements.filter((e) => e.type === 'file');
let nonFileElements = elements.filter((e) => e.type !== 'file');
@@ -1348,6 +1425,73 @@ export async function sendGroupMessage(
}
}
let allowTemporary = nonFileElements.every((element) => element.type === 'image');
const assertStorageAllowed = (busId: number | undefined) => {
if (busId === 104 && !allowTemporary) {
throw new MessageElementValidationError(
'UNSENDABLE_TYPE',
'temporary group files require only file or image segments; remove text and other content before retrying',
'file',
);
}
};
const preparedFiles: Array<{
element: MessageElementOf<'file'>;
fileId: string;
busId?: number;
}> = [];
const prepareFiles = async (files: Array<MessageElementOf<'file'>>) => {
// Check known temporary ids first, even if preceded by a new upload.
const candidates = files.map((element) => {
const cached = element.fileId
? ref.bridge.recallUploadedFile(element.fileId)
: undefined;
const busId =
cached?.scope === 'group' && cached.groupId === groupId ? cached.busId : undefined;
assertStorageAllowed(busId);
return { element, fileId: element.fileId, busId };
});
for (const candidate of candidates) {
const { element } = candidate;
if (!candidate.fileId) {
if (!element.url) {
throw new MessageElementValidationError(
'MISSING_FIELD',
'group file segment requires file_id or url',
'file',
);
}
const name = element.fileName || guessFileNameFromUrl(element.url) || 'file';
const uploaded = await ref.bridge.apis.groupFile.upload(
groupId,
element.url,
name,
'/',
true,
false,
{ allowTemporary },
);
candidate.fileId = uploaded.fileId;
candidate.busId = uploaded.busId;
assertStorageAllowed(candidate.busId);
}
if (!candidate.fileId) {
throw new Error('group file auto-upload returned no file_id');
}
preparedFiles.push({ element, fileId: candidate.fileId, busId: candidate.busId });
}
};
await prepareFiles(allFileElements);
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendGroup>> | undefined;
if (nonFileElements.length > 0) {
@@ -1369,8 +1513,9 @@ export async function sendGroupMessage(
err instanceof Error ? err.message : String(err),
);
const { fileEls, remaining } = splitVideoFileFallback(nonFileElements, isSizeErr);
allFileElements = [...allFileElements, ...fileEls];
nonFileElements = remaining;
allowTemporary = remaining.every((element) => element.type === 'image');
await prepareFiles(fileEls);
if (nonFileElements.length > 0) {
lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements);
@@ -1379,34 +1524,14 @@ export async function sendGroupMessage(
}
}
for (const fileEl of allFileElements) {
let fileId: string;
if (fileEl.url && !fileEl.fileId) {
// upload() already calls publish() internally — do NOT call publish() again.
const name = fileEl.fileName || guessFileNameFromUrl(fileEl.url) || 'file';
const result = await ref.bridge.apis.groupFile.upload(
groupId,
fileEl.url,
name,
'/',
true,
for (const { element: fileEl, fileId, busId } of preparedFiles) {
try {
await ref.bridge.apis.groupFile.publish(groupId, fileId, busId);
} catch (err) {
throw new Error(
`group file chat post failed (fileId=${fileId}): ${err instanceof Error ? err.message : String(err)}`,
{ cause: err },
);
fileId = result.fileId ?? '';
if (!fileId) {
throw new Error('group file auto-upload returned no file_id');
}
} else if (fileEl.fileId) {
fileId = fileEl.fileId;
await ref.bridge.apis.groupFile.publish(groupId, fileId);
} else {
throw new MessageElementValidationError(
'MISSING_FIELD',
'group file segment requires file_id or url',
'file',
);
continue;
}
logSentMessage(true, groupId, [fileEl]);
+33 -7
View File
@@ -1,6 +1,11 @@
import { createLogger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { GroupRequestHandle, GroupRequestInfo } from '@snowluma/protocol/qq-info';
import {
groupRequestSubType,
isSelfGroupInvitation,
type GroupRequestHandle,
type GroupRequestInfo,
} from '@snowluma/protocol/qq-info';
const log = createLogger('OneBot.Request');
@@ -137,10 +142,7 @@ async function resolveLiveGroupRequest(
const lookup = await fetchRequestInboxes(bridge, 'uin');
const live = lookup.requests.find(
(request) =>
request.groupId === handle.groupId &&
request.sequence === handle.sequence &&
request.eventType > 0,
(request) => request.groupId === handle.groupId && request.sequence === handle.sequence,
);
if (!live) {
@@ -164,6 +166,13 @@ async function applyGroupRequest(
knownLive?: GroupRequestInfo,
): Promise<void> {
const live = knownLive ?? (await resolveLiveGroupRequest(bridge, handle));
if (!groupRequestSubType(live)) {
throw new Error(
`unsupported group request type: group=${live.groupId} sequence=${live.sequence} type=${live.eventType}`,
);
}
log.debug(
'handling group request: group=%d sequence=%d eventType=%d filtered=%s approve=%s',
live.groupId,
@@ -259,13 +268,17 @@ export async function handleGroupAddRequest(
const lookup = await fetchRequestInboxes(bridge, 'uid');
const candidates = lookup.requests.filter((request) => {
if (request.groupId !== parsed.groupId || request.state !== 1 || request.eventType <= 0) {
if (
request.groupId !== parsed.groupId ||
request.state !== 1 ||
groupRequestSubType(request) !== parsed.requestType
) {
return false;
}
if (
notice &&
(request.eventType !== 2 ||
(!isSelfGroupInvitation(request) ||
(request.targetUin > 0 && request.targetUin !== Number(bridge.identity.uin)) ||
(request.targetUid &&
bridge.identity.selfUid &&
@@ -282,6 +295,19 @@ export async function handleGroupAddRequest(
const matching = candidates[0];
if (!matching) {
log.warn(
'group request match failed: group=%d kind=%s selfInvitation=%s inboxTypes=%s',
parsed.groupId,
parsed.requestType,
Boolean(notice),
lookup.requests
.filter((request) => request.groupId === parsed.groupId)
.map(
(request) =>
`${request.notifyType ?? '?'}:${request.eventType}:${request.state}`,
)
.join(','),
);
throwMissingGroupRequest('matching group request not found', lookup.failures);
}
@@ -2,7 +2,7 @@ import { createLogger, runWithTraceRequest } from '@snowluma/common/logger';
import { WebSocketServer } from '@snowluma/websocket';
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http';
import type { ApiHandler } from '../api-handler';
import type { DispatchPayload } from '../event-filter';
import { resolveReportOptions, type DispatchPayload } from '../event-filter';
import type { ApiResponse, HttpServerNetwork, JsonObject, JsonValue } from '../types';
import {
StreamTransportClosedError,
@@ -14,6 +14,7 @@ import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext }
import { isAuthorized, normalizePath } from './utils';
import { WsServerConnections } from './ws-server-connections';
import { httpTraceparent } from './http-trace';
import { HttpSseConnections } from './http-sse-connections';
const moduleLog = createLogger('OneBot.HTTP');
@@ -26,9 +27,13 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
private acceptingActions = false;
private readonly inFlightActions = new Set<Promise<void>>();
private readonly webSocketConnections: WsServerConnections;
private readonly sseConnections: HttpSseConnections;
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx, moduleLog);
this.sseConnections = new HttpSseConnections(config, this.log, () =>
this.bootstrapMetaFrames(resolveReportOptions(this.config)),
);
this.webSocketConnections = new WsServerConnections(name, config, ctx, this.log, {
frame: (event, options) => this.metaFrame(event, options),
bootstrap: (options) => this.bootstrapMetaFrames(options),
@@ -80,6 +85,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
const wasAcceptingWebSocketActions = this.webSocketConnections.isAcceptingActions;
this.acceptingActions = false;
this.webSocketConnections.stopAccepting();
this.sseConnections.close('server closing');
this.isEnabled = false;
this.listening = false;
const server = this.server;
@@ -161,6 +167,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
this.releaseForced = true;
this.acceptingActions = false;
this.webSocketConnections.stopAccepting();
this.sseConnections.close('server closing');
this.isEnabled = false;
this.listening = false;
this.webSocketConnections.terminateAll();
@@ -206,28 +213,45 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
};
}
const detail =
let detail =
this.config.enableWebSocket === true
? `监听中 · WebSocket ${this.webSocketConnections.connectionCount} 个客户端`
: '监听中';
if (this.config.enableSse === true) {
detail += ` · SSE ${this.sseConnections.connectionCount} 个客户端`;
}
return { name: this.name, kind: 'httpServer', status: 'ok', detail };
}
protected override bindingSignature(config: HttpServerNetwork): string {
const webSocket = config.enableWebSocket === true ? 'ws' : 'http';
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path ?? '/')}#${webSocket}`;
// The frame cap is fixed when the WebSocketServer is constructed, so a
// change must rebind instead of silently keeping the old limit — but only
// when this adapter actually owns a WebSocket transport, otherwise the
// HTTP listener would be torn down for a value it never uses.
const maxPayload = config.enableWebSocket === true ? (config.maxPayloadBytes ?? '') : '';
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path ?? '/')}#${webSocket}#${maxPayload}`;
}
protected override onConfigReplaced(next: HttpServerNetwork): void {
this.webSocketConnections.updateConfig(next);
this.sseConnections.updateConfig(next);
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (this.config.enableWebSocket !== true || !this.isEnabled) {
if (!this.isEnabled) {
return;
}
this.webSocketConnections.onEvent(payload);
if (this.config.enableWebSocket === true) {
this.webSocketConnections.onEvent(payload);
}
if (this.config.enableSse === true) {
this.sseConnections.onEvent(payload);
}
}
private startServer(): Promise<void> {
@@ -242,6 +266,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
if (this.config.enableWebSocket === true) {
webSocketServer = new WebSocketServer({
server,
maxPayload: this.config.maxPayloadBytes,
verifyClient: ({ req }: { req: IncomingMessage }) =>
this.webSocketConnections.authorizeUpgrade(req),
});
@@ -301,6 +326,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
this.isEnabled = false;
this.acceptingActions = false;
this.webSocketConnections.stopAccepting();
this.sseConnections.close('server closing');
this.recordTransportFailure(error);
if (opening) {
@@ -382,11 +408,38 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
return;
}
if (!isAuthorized(req, accessToken)) {
if (!isAuthorized(req, accessToken, true)) {
respond(401, { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' });
return;
}
if (action === '_events') {
if (apiQuiescedAtIngress) {
return;
}
if (this.config.enableSse !== true) {
respond(404, {
status: 'failed',
retcode: 1404,
data: null,
wording: 'SSE is disabled',
});
} else if (req.method !== 'GET') {
res.setHeader('Allow', 'GET');
respond(405, {
status: 'failed',
retcode: 1405,
data: null,
wording: 'SSE requires GET',
});
} else {
this.sseConnections.accept(req, res);
}
return;
}
if (req.headers.traceparent !== undefined) {
const traceparent = httpTraceparent(req.headers.traceparent);
@@ -0,0 +1,275 @@
import { randomUUID } from 'node:crypto';
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { Logger } from '@snowluma/common/logger';
import { pickDispatchJson, resolveReportOptions, type DispatchPayload } from '../event-filter';
import type { HttpServerNetwork } from '../types';
const REPLAY_EVENTS = 256;
const REPLAY_BYTES = 8 * 1024 * 1024;
const CLIENT_BYTES = 8 * 1024 * 1024;
const HEARTBEAT_MS = 15_000;
interface Frame {
sequence: number;
text: string;
bytes: number;
}
interface Connection {
response: ServerResponse;
queue: Frame[];
bytes: number;
blocked: boolean;
dispose(): void;
}
/** Per-adapter event history and connections; never shared between accounts. */
export class HttpSseConnections {
private config: HttpServerNetwork;
private epoch = randomUUID();
private sequence = 0;
private droppedThrough = 0;
private history: Frame[] = [];
private historyBytes = 0;
private readonly connections = new Set<Connection>();
private heartbeat: ReturnType<typeof setInterval> | undefined;
constructor(
config: HttpServerNetwork,
private readonly log: Logger,
private readonly bootstrap: () => string[],
) {
this.config = structuredClone(config);
}
get connectionCount(): number {
return this.connections.size;
}
updateConfig(next: HttpServerNetwork): void {
if (
this.config.enableSse !== next.enableSse ||
(this.config.accessToken ?? '') !== (next.accessToken ?? '') ||
(this.config.messageFormat ?? 'array') !== (next.messageFormat ?? 'array') ||
(this.config.reportSelfMessage ?? false) !== (next.reportSelfMessage ?? false)
) {
// Replaying frames shaped under the previous policy could disclose
// events which the new report policy excludes.
this.close('configuration changed');
}
this.config = structuredClone(next);
}
accept(request: IncomingMessage, response: ServerResponse): void {
const cursor = request.headers['last-event-id'];
let after = this.sequence;
if (cursor !== undefined && cursor !== '') {
const match =
typeof cursor === 'string'
? /^([0-9a-f-]{36}):(0|[1-9]\d{0,15})$/.exec(cursor)
: null;
const value = match ? Number(match[2]) : NaN;
if (!match || !Number.isSafeInteger(value)) {
this.rejectCursor(response, 400, 'invalid Last-Event-ID');
return;
}
if (match[1] !== this.epoch || value < this.droppedThrough || value > this.sequence) {
this.rejectCursor(
response,
409,
'SSE replay unavailable; resync and reconnect without Last-Event-ID',
);
return;
}
after = value;
}
response.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
'X-Accel-Buffering': 'no',
Connection: 'keep-alive',
});
response.flushHeaders();
request.socket.setTimeout(0);
const onDrain = (): void => {
connection.blocked = false;
this.flush(connection);
};
const onError = (error: Error): void => {
this.log.warn('[%s] SSE connection failed: %s', this.config.name, error.message);
this.drop(connection);
};
const onClose = (): void => this.drop(connection);
const connection: Connection = {
response,
queue: [],
bytes: 0,
blocked: false,
dispose: () => {
response.off('drain', onDrain);
response.off('close', onClose);
response.off('error', onError);
},
};
response.on('drain', onDrain);
response.once('close', onClose);
response.on('error', onError);
this.connections.add(connection);
this.log.debug('[%s] SSE connected (%d clients)', this.config.name, this.connectionCount);
this.enqueue(connection, this.frame('retry: 3000\n\n'));
for (const frame of this.history) {
if (frame.sequence > after) {
this.enqueue(connection, frame);
}
}
// Bootstrap supplies a cursor even when there has not been a message.
// Only broadcast events consume sequence numbers and enter history.
for (const json of this.bootstrap()) {
this.enqueue(connection, this.eventFrame(json));
}
if (!this.heartbeat && this.connections.size > 0) {
this.heartbeat = setInterval(() => {
const frame = this.frame(': ping\n\n');
for (const client of this.connections) {
this.enqueue(client, frame);
}
}, HEARTBEAT_MS);
this.heartbeat.unref();
}
}
onEvent(payload: DispatchPayload): void {
const json = pickDispatchJson(payload, resolveReportOptions(this.config));
if (json === null) {
return;
}
this.sequence += 1;
const frame = this.eventFrame(json);
this.history.push(frame);
this.historyBytes += frame.bytes;
while (this.history.length > REPLAY_EVENTS || this.historyBytes > REPLAY_BYTES) {
const removed = this.history.shift()!;
this.historyBytes -= removed.bytes;
this.droppedThrough = removed.sequence;
}
for (const connection of this.connections) {
this.enqueue(connection, frame);
}
}
close(reason: string): void {
if (this.connections.size > 0) {
this.log.debug('[%s] SSE closing: %s', this.config.name, reason);
}
for (const connection of this.connections) {
this.drop(connection);
}
this.history = [];
this.historyBytes = 0;
this.sequence = 0;
this.droppedThrough = 0;
this.epoch = randomUUID();
}
private eventFrame(json: string): Frame {
return this.frame(`id: ${this.epoch}:${this.sequence}\ndata: ${json}\n\n`);
}
private frame(text: string): Frame {
return { sequence: this.sequence, text, bytes: Buffer.byteLength(text) };
}
private enqueue(connection: Connection, frame: Frame): void {
if (!this.connections.has(connection)) {
return;
}
if (connection.bytes + connection.response.writableLength + frame.bytes > CLIENT_BYTES) {
this.log.warn(
'[%s] SSE client exceeded %d buffered bytes; disconnecting',
this.config.name,
CLIENT_BYTES,
);
this.drop(connection);
return;
}
connection.queue.push(frame);
connection.bytes += frame.bytes;
this.flush(connection);
}
private flush(connection: Connection): void {
while (!connection.blocked && connection.queue.length > 0) {
const frame = connection.queue.shift()!;
connection.bytes -= frame.bytes;
try {
connection.blocked = !connection.response.write(frame.text);
} catch (error) {
this.log.warn(
'[%s] SSE write failed: %s',
this.config.name,
error instanceof Error ? error.message : String(error),
);
this.drop(connection);
return;
}
}
}
private drop(connection: Connection): void {
if (!this.connections.delete(connection)) {
return;
}
connection.queue = [];
connection.bytes = 0;
// The response error handler remains until close, including when a
// previously queued write fails during destruction.
if (connection.response.destroyed) {
connection.dispose();
} else {
connection.response.once('close', connection.dispose);
connection.response.destroy();
}
if (this.connections.size === 0 && this.heartbeat) {
clearInterval(this.heartbeat);
this.heartbeat = undefined;
}
}
private rejectCursor(response: ServerResponse, status: number, wording: string): void {
this.log.warn('[%s] rejected SSE reconnect: %s', this.config.name, wording);
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
response.end(
JSON.stringify({
status: 'failed',
retcode: status === 400 ? 1400 : 1409,
data: null,
wording,
}),
);
}
}
+13 -2
View File
@@ -2,14 +2,25 @@ import { StreamTransportClosedError } from '../streaming';
import type { WebSocket } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
export function isAuthorized(request: IncomingMessage, token: string): boolean {
/**
* Appended to a 1009 (frame-over-cap) log line. Shared so the client and server
* adapters cannot drift apart on the advice they give.
*/
export const MAX_PAYLOAD_HINT =
"Raise this adapter's maxPayloadBytes, or have the peer send a smaller frame (a URL/file reference or SILK instead of inline PCM)";
export function isAuthorized(
request: IncomingMessage,
token: string,
allowRawToken = false,
): boolean {
if (!token) {
return true;
}
const auth = request.headers.authorization ?? '';
if (auth === `Bearer ${token}`) {
if (auth === `Bearer ${token}` || (allowRawToken && auth === token)) {
return true;
}
@@ -8,7 +8,14 @@ import {
} from '../event-filter';
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend, safeSendAsync, startHeartbeat } from './utils';
import {
MAX_PAYLOAD_HINT,
rawDataToString,
safeClose,
safeSend,
safeSendAsync,
startHeartbeat,
} from './utils';
const moduleLog = createLogger('OneBot.WS-Client');
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
@@ -107,7 +114,9 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
}
protected override bindingSignature(config: WsClientNetwork): string {
return `${config.url}#${config.role ?? 'Universal'}#${Math.max(1000, config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${config.accessToken ?? ''}`;
// The frame cap is baked into the socket when it is created, so a change
// must reconnect instead of silently keeping the old limit.
return `${config.url}#${config.role ?? 'Universal'}#${Math.max(1000, config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${config.accessToken ?? ''}#${config.maxPayloadBytes ?? ''}`;
}
protected override willEnable(config: WsClientNetwork): boolean {
@@ -160,7 +169,10 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
headers.Authorization = `Bearer ${this.config.accessToken}`;
}
const socket = new WebSocket(this.config.url, { headers });
const socket = new WebSocket(this.config.url, {
headers,
maxPayload: this.config.maxPayloadBytes,
});
this.socket = socket;
// Per-socket so a hot-reload overlap (old close firing after the new socket
// is assigned, see #97) can only ever stop its own keepalive.
@@ -255,11 +267,16 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
});
socket.on('error', (err: Error) => {
// Keep the established `error <url>:` line intact (deployments grep
// it); the actionable hint is appended, never substituted.
const message = err instanceof Error ? err.message : String(err);
this.log.warn(
'[%s] error %s: %s',
this.name,
this.config.url,
err instanceof Error ? err.message : String(err),
(err as Error & { code?: number }).code === 1009
? `${message}. ${MAX_PAYLOAD_HINT}`
: message,
);
});
}
@@ -154,7 +154,9 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
}
protected override bindingSignature(config: WsServerNetwork): string {
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path)}#${config.role ?? 'auto'}#${config.accessToken ?? ''}`;
// The frame cap is fixed when the WebSocketServer is constructed, so a
// change must rebind instead of silently keeping the old limit.
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path)}#${config.role ?? 'auto'}#${config.accessToken ?? ''}#${config.maxPayloadBytes ?? ''}`;
}
protected override onConfigReplaced(next: WsServerNetwork): void {
@@ -177,6 +179,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
wss = new WebSocketServer({
host: this.config.host ?? '0.0.0.0',
port: this.config.port,
maxPayload: this.config.maxPayloadBytes,
verifyClient: (
{ req }: { req: IncomingMessage },
done: (allow: boolean, code?: number, message?: string) => void,
@@ -10,6 +10,7 @@ import {
import type { JsonObject, NetworkBase, WsRole } from '../types';
import type { NetworkAdapterContext } from './adapter';
import {
MAX_PAYLOAD_HINT,
isAuthorized,
normalizePath,
parseRequestPath,
@@ -211,10 +212,15 @@ export class WsServerConnections {
this.connections.delete(socket);
});
socket.on('error', (error: Error) => {
// Keep the established `socket error:` line intact (deployments grep
// it); the actionable hint is appended, never substituted.
const message = error instanceof Error ? error.message : String(error);
this.log.warn(
'[%s] socket error: %s',
this.name,
error instanceof Error ? error.message : String(error),
(error as Error & { code?: number }).code === 1009
? `${message}. ${MAX_PAYLOAD_HINT}`
: message,
);
});
+194
View File
@@ -0,0 +1,194 @@
import type { MessageElement } from '@snowluma/protocol/events';
import type { JsonObject } from './types';
import { cqUnescape } from './helper/cq';
// Send receipts and quoted timestamps can differ; never search outside the
// existing bounded drift window when resolving a quoted message.
export const PRIVATE_QUOTE_MAX_DRIFT_SECONDS = 30;
const TIME_WINDOWS = [0, 5, PRIVATE_QUOTE_MAX_DRIFT_SECONDS] as const;
interface QuotePreview {
text: string;
plain: boolean;
}
export interface PrivateQuoteCandidate {
id?: number;
sequence: number;
clientSequence: number;
timestamp: number;
preview: QuotePreview | null;
}
/** Identity of the containing message, which can never be its own quote target. */
export interface PrivateQuoteSource {
id: number;
sequence: number;
clientSequence: number;
timestamp: number;
sentBySelf: boolean;
}
export interface PrivateQuoteKey {
sequence: number;
sentBySelf: boolean;
timestamp?: number;
elements?: readonly MessageElement[];
exclude?: PrivateQuoteSource;
}
export function isUsableQuoteTime(timestamp: number | undefined): timestamp is number {
return (
timestamp !== undefined &&
Number.isSafeInteger(timestamp) &&
timestamp > 0 &&
timestamp < Number.MAX_SAFE_INTEGER
);
}
/** Sequence namespaces may overlap. Only a unique, consistent candidate wins. */
export function selectPrivateQuote<T extends PrivateQuoteCandidate>(
candidates: readonly T[],
quote: PrivateQuoteKey,
): { candidate: T | null; reason: 'sequence' | 'time' | 'ambiguous' | 'missing' } {
const time = isUsableQuoteTime(quote.timestamp) ? quote.timestamp : null;
const text =
quote.elements?.length && quote.elements.every((element) => element.type === 'text')
? quote.elements.map((element) => element.text ?? '').join('')
: '';
const nearby = candidates.filter((candidate) => {
const source = quote.exclude;
if (
source &&
(candidate.id === source.id ||
(source.sentBySelf === quote.sentBySelf &&
((source.sequence > 0 && candidate.sequence === source.sequence) ||
(source.clientSequence > 0 &&
candidate.clientSequence === source.clientSequence &&
candidate.timestamp === source.timestamp))))
) {
return false;
}
return (
time === null || Math.abs(candidate.timestamp - time) <= PRIVATE_QUOTE_MAX_DRIFT_SECONDS
);
});
// QQ can truncate the quote. Unknown and prefix-only previews remain
// competing candidates; only contradictory known content is excluded.
const compatible = nearby.filter(
(candidate) => !text || !candidate.preview || candidate.preview.text.startsWith(text),
);
const bySequence = compatible.filter(
(candidate) =>
quote.sequence > 0 &&
(candidate.clientSequence === quote.sequence || candidate.sequence === quote.sequence),
);
if (bySequence.length > 0) {
return {
candidate: bySequence.length === 1 ? bySequence[0]! : null,
reason: bySequence.length === 1 ? 'sequence' : 'ambiguous',
};
}
if (quote.sentBySelf && time !== null) {
for (const window of TIME_WINDOWS) {
const matches = compatible.filter(
(candidate) => Math.abs(candidate.timestamp - time) <= window,
);
if (matches.length > 0) {
const match = matches.length === 1 ? matches[0]! : null;
const windowCount = nearby.filter(
(candidate) => Math.abs(candidate.timestamp - time) <= window,
).length;
// A missing body cannot confirm quoted text. When content is the
// only discriminator, a truncated/media preview cannot prove it.
const confirmed =
match &&
(!text ||
(match.preview &&
(windowCount === 1 ||
(match.preview.plain && match.preview.text === text))));
return {
candidate: confirmed ? match : null,
reason: confirmed ? 'time' : 'ambiguous',
};
}
}
}
return { candidate: null, reason: 'missing' };
}
const labels: Readonly<Record<string, string>> = {
image: '[图片]',
record: '[语音]',
video: '[视频]',
file: '[文件]',
face: '[表情]',
mface: '[表情]',
forward: '[聊天记录]',
json: '[卡片]',
xml: '[卡片]',
};
export function cachedQuotePreview(data: string | null): QuotePreview | null {
if (!data) {
return null;
}
const event = JSON.parse(data) as JsonObject;
if (typeof event.message === 'string') {
return event.message.includes('[CQ:')
? null
: { text: cqUnescape(event.message), plain: true };
}
if (!Array.isArray(event.message) || event.message.length === 0) {
return null;
}
const parts: string[] = [];
let plain = true;
for (const segment of event.message as JsonObject[]) {
const body = segment?.data as JsonObject | undefined;
if (segment?.type === 'text' && typeof body?.text === 'string') {
parts.push(body.text);
} else if (typeof segment?.type === 'string' && Object.hasOwn(labels, segment.type)) {
parts.push(typeof body?.summary === 'string' ? body.summary : labels[segment.type]!);
plain = false;
} else {
return null;
}
}
return { text: parts.join(''), plain };
}
export function messageQuotePreview(elements: readonly MessageElement[]): QuotePreview | null {
const parts: string[] = [];
let plain = true;
for (const element of elements) {
if (element.type === 'text') {
parts.push(element.text ?? '');
} else if (Object.hasOwn(labels, element.type)) {
parts.push(
'summary' in element && typeof element.summary === 'string'
? element.summary
: labels[element.type]!,
);
plain = false;
} else {
return null;
}
}
return parts.length > 0 ? { text: parts.join(''), plain } : null;
}
+26 -3
View File
@@ -38,12 +38,35 @@ export interface NetworkBase {
reportSelfMessage: boolean;
}
export interface HttpServerNetwork extends NetworkBase {
/**
* Inbound WebSocket frame cap, shared by the three adapters that read WebSocket
* frames: `wsServers`, `wsClients`, and `httpServers` with `enableWebSocket`.
* It is deliberately not part of {@link NetworkBase}: `httpClients` has no
* WebSocket transport, and a saved-but-ignored option is worse than none.
*/
export interface WsFrameLimitConfig {
/**
* Cap on one inbound WebSocket message, in bytes (all fragments included).
* Omitted means the transport default of 100 MiB
* (`DEFAULT_MAX_PAYLOAD_BYTES`).
*
* Frames larger than the cap close the connection with 1009. A OneBot peer
* that sends media inline has to fit the whole payload into one frame: at
* 44.1 kHz stereo 16-bit PCM (176 400 B/s), 100 MiB is ~445 s (7:26), so
* longer audio must arrive as a URL/file reference or be compressed (SILK).
* Raising this value raises peak memory by the frame size.
*/
maxPayloadBytes?: number;
}
export interface HttpServerNetwork extends NetworkBase, WsFrameLimitConfig {
host?: string;
port: number;
path?: string;
/** Accept OneBot WebSocket clients on the same HTTP listener. */
enableWebSocket?: boolean;
/** Serve OneBot events at <path>/_events, with bounded reconnect replay. */
enableSse?: boolean;
}
export interface HttpClientNetwork extends NetworkBase {
@@ -51,14 +74,14 @@ export interface HttpClientNetwork extends NetworkBase {
timeoutMs?: number;
}
export interface WsServerNetwork extends NetworkBase {
export interface WsServerNetwork extends NetworkBase, WsFrameLimitConfig {
host?: string;
port: number;
path?: string;
role?: WsRole;
}
export interface WsClientNetwork extends NetworkBase {
export interface WsClientNetwork extends NetworkBase, WsFrameLimitConfig {
url: string;
role?: WsRole;
reconnectIntervalMs?: number;
@@ -0,0 +1,28 @@
import { describe, expect, it, vi } from 'vitest';
import type { ApiActionContext } from '../src/api-handler';
import { actions } from '../src/actions/group-file';
describe('get_group_file_url storage selection', () => {
it.each([
{ busid: undefined, expected: undefined },
{ busid: null, expected: undefined },
{ busid: '', expected: undefined },
{ busid: 'invalid', expected: undefined },
{ busid: -1, expected: undefined },
{ busid: 102, expected: 102 },
{ busid: '104', expected: 104 },
{ busid: 0, expected: 0 },
])(
'passes an explicit valid type, otherwise lets the file cache select it (%j)',
async ({ busid, expected }) => {
const getUrl = vi.fn(async () => 'https://download.example.com/file');
const ctx = {
bridge: { apis: { groupFile: { getUrl } } },
} as unknown as ApiActionContext;
const action = actions.find((entry) => entry.names[0] === 'get_group_file_url')!;
const result = await action.toHandler(ctx)({ group_id: 12345, file_id: 'temp', busid });
expect(result).toMatchObject({ status: 'ok' });
expect(getUrl).toHaveBeenCalledExactlyOnceWith(12345, 'temp', expected);
},
);
});
@@ -8,10 +8,10 @@ import { describe, expect, it, vi } from 'vitest';
import { backfillReplyTarget } from '../src/modules/message-actions';
import {
GROUP_MESSAGE_EVENT,
PRIVATE_MESSAGE_EVENT,
PRIVATE_SENT_MESSAGE_EVENT,
PRIVATE_NT_MESSAGE_EVENT,
hashMessageIdInt32,
} from '../src/message-id';
import { createMessageIdResolver } from '../src/message-id-resolver';
const SELF = 10001;
@@ -19,7 +19,7 @@ const converterCtx = {
selfId: SELF,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
messageIdResolver: createMessageIdResolver({ resolvePrivateReplyMessageId: async () => null }),
mediaSegmentSink: null,
} as any;
@@ -28,6 +28,9 @@ function fakeStore(has = false) {
findEvent: vi.fn(() => (has ? ({ message_id: 1 } as any) : null)),
storeMeta: vi.fn(),
storeEvent: vi.fn(),
findMeta: vi.fn(async () => null),
resolvePrivateReplyMessageId: vi.fn(async () => null),
storeHistoryEvent: vi.fn(async () => true),
};
}
@@ -137,31 +140,29 @@ describe('backfillReplyTarget', () => {
expect(resolveUserUid).toHaveBeenCalledWith(448671521);
expect(getC2cLatestHistory).toHaveBeenCalledWith('u_friend', 20, SELF, 1700000101);
const targetId = hashMessageIdInt32(456, 448671521, PRIVATE_MESSAGE_EVENT);
expect(store.storeMeta).toHaveBeenCalledWith(
targetId,
expect.objectContaining({
sequence: 1456,
clientSequence: 456,
privateDirection: 'incoming',
sequenceAuthoritative: true,
}),
);
expect(store.storeEvent).toHaveBeenCalledWith(
const targetId = hashMessageIdInt32(1456, 448671521, PRIVATE_NT_MESSAGE_EVENT);
expect(store.storeHistoryEvent).toHaveBeenCalledWith(
targetId,
false,
448671521,
1456,
PRIVATE_MESSAGE_EVENT,
PRIVATE_NT_MESSAGE_EVENT,
expect.objectContaining({ message_id: targetId, message_type: 'private' }),
{ sequenceAuthoritative: true },
{
sequenceAuthoritative: true,
meta: expect.objectContaining({
sequence: 1456,
clientSequence: 456,
privateDirection: 'incoming',
sequenceAuthoritative: true,
}),
},
);
});
it('c2c: a bot self-sent quoted message is keyed under the peer (not self)', async () => {
// The fetched message was sent by us (senderUin = self) — it converts with
// user_id=self, but must still be findable under hash(seq, peer, private),
// which is what the incoming reply resolves to.
// user_id=self, but its canonical id still belongs to the peer conversation.
const store = fakeStore(false);
const getC2cLatestHistory = vi.fn(async () => [fetchedFriendMessage(456, SELF)]);
const ref = {
@@ -186,15 +187,18 @@ describe('backfillReplyTarget', () => {
await backfillReplyTarget(ref, event);
const targetId = hashMessageIdInt32(456, 448671521, PRIVATE_SENT_MESSAGE_EVENT);
expect(store.storeEvent).toHaveBeenCalledWith(
const targetId = hashMessageIdInt32(1456, 448671521, PRIVATE_NT_MESSAGE_EVENT);
expect(store.storeHistoryEvent).toHaveBeenCalledWith(
targetId,
false,
448671521,
1456,
PRIVATE_SENT_MESSAGE_EVENT,
PRIVATE_NT_MESSAGE_EVENT,
expect.objectContaining({ message_id: targetId }),
{ sequenceAuthoritative: true },
{
sequenceAuthoritative: true,
meta: expect.objectContaining({ privateDirection: 'outgoing' }),
},
);
});
@@ -225,15 +229,18 @@ describe('backfillReplyTarget', () => {
await backfillReplyTarget(ref, event);
const targetId = hashMessageIdInt32(456, peerUin, PRIVATE_MESSAGE_EVENT);
expect(store.storeEvent).toHaveBeenCalledWith(
const targetId = hashMessageIdInt32(1456, peerUin, PRIVATE_NT_MESSAGE_EVENT);
expect(store.storeHistoryEvent).toHaveBeenCalledWith(
targetId,
false,
peerUin,
1456,
PRIVATE_MESSAGE_EVENT,
PRIVATE_NT_MESSAGE_EVENT,
expect.objectContaining({ message_id: targetId, message_type: 'private' }),
{ sequenceAuthoritative: true },
{
sequenceAuthoritative: true,
meta: expect.objectContaining({ privateDirection: 'incoming' }),
},
);
});
+165
View File
@@ -148,6 +148,44 @@ describe('assertValidOneBotConfig', () => {
expect(() => assertValidOneBotConfig(ws)).toThrow(/reconnectIntervalMs/);
});
it('bounds maxPayloadBytes when one is configured', () => {
for (const invalid of [0, 1023, 2 * 1024 * 1024 * 1024 + 1, 1024.5, '104857600']) {
const config = makeDefaultOneBotConfig();
config.networks.wsServers[0].maxPayloadBytes = invalid as unknown as number;
expect(() => assertValidOneBotConfig(config), String(invalid)).toThrow(
/maxPayloadBytes/,
);
}
const accepted = makeDefaultOneBotConfig();
accepted.networks.wsServers[0].maxPayloadBytes = 1024;
expect(() => assertValidOneBotConfig(accepted)).not.toThrow();
// The third WebSocket-capable adapter: httpServers with the embedded WS.
const httpWs = makeDefaultOneBotConfig();
httpWs.networks.httpServers[0].enableWebSocket = true;
httpWs.networks.httpServers[0].maxPayloadBytes = 2048;
expect(() => assertValidOneBotConfig(httpWs)).not.toThrow();
});
it('rejects maxPayloadBytes on the pure HTTP client adapter', () => {
const config = makeDefaultOneBotConfig();
config.networks.httpClients.push({
name: 'mirror',
url: 'http://127.0.0.1:9000',
messageFormat: 'array',
reportSelfMessage: false,
});
// HttpPostAdapter has no WebSocket transport, so the value could only be
// saved and silently ignored.
(config.networks.httpClients[0] as unknown as Record<string, unknown>).maxPayloadBytes =
1024;
expect(() => assertValidOneBotConfig(config)).toThrow(
/maxPayloadBytes is only supported by WebSocket adapters/,
);
});
it('rejects server paths that cannot match a URL pathname', () => {
for (const invalidPath of ['api', '/api?token=x', '/api#fragment', ' /api']) {
const config = makeDefaultOneBotConfig();
@@ -365,6 +403,133 @@ describe('loadOneBotConfig', () => {
expect(reloaded.networks.httpClients[0].reportSelfMessage).toBe(true);
});
it('round-trips maxPayloadBytes (both directions) and omits it when unset', () => {
const uin = '10020';
const config = makeDefaultOneBotConfig();
config.networks.wsServers[0].maxPayloadBytes = 512 * 1024 * 1024;
config.networks.wsClients.push({
name: 'astrbot',
url: 'ws://127.0.0.1:6199/ws',
messageFormat: 'array',
reportSelfMessage: false,
maxPayloadBytes: 256 * 1024 * 1024,
});
saveOneBotConfig(uin, config);
const onDisk = JSON.parse(
fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8'),
);
expect(onDisk.networks.wsServers[0].maxPayloadBytes).toBe(512 * 1024 * 1024);
expect(onDisk.networks.wsClients[0].maxPayloadBytes).toBe(256 * 1024 * 1024);
// Unset adapters must not gain the key, so existing configs stay byte-stable.
expect(onDisk.networks.httpServers[0].maxPayloadBytes).toBeUndefined();
const reloaded = loadOneBotConfig(uin);
expect(reloaded.networks.wsServers[0].maxPayloadBytes).toBe(512 * 1024 * 1024);
expect(reloaded.networks.wsClients[0]!.maxPayloadBytes).toBe(256 * 1024 * 1024);
const prepared = prepareOneBotConfigForRestore(onDisk, 'per-uin');
const preparedNetworks = prepared.value.networks as {
wsClients: Array<Record<string, unknown>>;
};
expect(preparedNetworks.wsClients[0]!.maxPayloadBytes).toBe(256 * 1024 * 1024);
const junk = structuredClone(onDisk) as {
networks: { wsClients: Array<Record<string, unknown>> };
};
for (const value of [0, '268435456', 1024.5, null]) {
junk.networks.wsClients[0]!.maxPayloadBytes = value;
expect(() => prepareOneBotConfigForRestore(junk, 'per-uin')).toThrow(/maxPayloadBytes/);
}
});
it.each(['httpServers', 'wsServers', 'wsClients'] as const)(
'rejects invalid on-disk maxPayloadBytes for %s without rewriting the file',
(kind) => {
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
const file = path.join(dir, 'onebot_10023.json');
for (const value of [-1, 0, 1023, 1024.5, 2 * 1024 ** 3 + 1, '2048', null, true]) {
const raw = JSON.stringify({
mode: 'snapshot',
networks: {
[kind]: [
{
name: 'invalid-limit',
port: 3001,
url: 'ws://127.0.0.1:3001',
enableWebSocket: true,
maxPayloadBytes: value,
},
],
},
});
fs.writeFileSync(file, raw, 'utf8');
expect(() => loadOneBotConfig('10023'), String(value)).toThrow(/maxPayloadBytes/);
expect(fs.readFileSync(file, 'utf8')).toBe(raw);
}
},
);
it('persists maxPayloadBytes for httpServers and rejects it for httpClients', () => {
const uin = '10021';
const config = makeDefaultOneBotConfig();
config.networks.httpServers[0].enableWebSocket = true;
config.networks.httpServers[0].maxPayloadBytes = 4096;
saveOneBotConfig(uin, config);
const onDisk = JSON.parse(
fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8'),
);
expect(onDisk.networks.httpServers[0].maxPayloadBytes).toBe(4096);
expect(loadOneBotConfig(uin).networks.httpServers[0].maxPayloadBytes).toBe(4096);
expect(() => prepareOneBotConfigForRestore(onDisk, 'per-uin')).not.toThrow();
// A restore source that carries the key on a non-WS adapter is rejected
// rather than accepted into a config where it can never apply.
const withHttpClient = structuredClone(onDisk) as {
networks: { httpClients: Array<Record<string, unknown>> };
};
withHttpClient.networks.httpClients.push({
name: 'mirror',
url: 'http://127.0.0.1:9000',
maxPayloadBytes: 4096,
});
expect(() => prepareOneBotConfigForRestore(withHttpClient, 'per-uin')).toThrow(
/maxPayloadBytes is not supported/,
);
// A hand-written file must reject the same unsupported field instead
// of discarding it before the canonical validation runs.
const dir = path.join(tempDir, 'config');
fs.writeFileSync(
path.join(dir, 'onebot_10022.json'),
JSON.stringify({
mode: 'snapshot',
networks: {
httpServers: [],
httpClients: [
{
name: 'mirror',
url: 'http://127.0.0.1:9000',
messageFormat: 'array',
reportSelfMessage: false,
maxPayloadBytes: 4096,
},
],
wsServers: [],
wsClients: [],
},
}),
'utf8',
);
expect(() => loadOneBotConfig('10022')).toThrow(
/maxPayloadBytes is only supported by WebSocket adapters/,
);
});
it('replays a saved per-UIN snapshot without reviving deleted global adapters', () => {
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
@@ -180,6 +180,69 @@ function makeGroupRequest(overrides: Partial<GroupRequestInfo> = {}): GroupReque
};
}
describe('public contact profile output', () => {
const profile = {
sign: '',
age: 0,
level: 0,
sex: 'unknown' as const,
vipFlag: false,
svipFlag: false,
country: 'CN',
city: 'City',
email: '',
birthdayMonth: 2,
birthdayDay: 29,
privilegeIcons: {
open: [{ type: 1, iconUrl: 'normal', deluxeIconUrl: 'deluxe' }],
closed: [],
},
};
const expected = {
long_nick: '',
age: 0,
level: 0,
sex: 'unknown',
is_qq_vip: false,
is_vip: false,
country: 'CN',
city: 'City',
email: '',
birthday_month: 2,
birthday_day: 29,
privilege_icons: {
open: [{ type: 1, icon_url: 'normal', deluxe_icon_url: 'deluxe' }],
closed: [],
},
};
it('returns the same public fields for friends and stranger profiles without invented values', async () => {
const fetchFriendList = vi.fn(async () => [
{ ...makeFriend(123, 'Name'), categoryId: 0, profile },
]);
const bridge = fakeBridge({
fetchFriendList,
fetchUserProfile: vi.fn(async () => ({ ...makeProfile(123, 'Name'), profile })),
});
const friends = await getFriendList(bridge, true);
expect(friends[0]).toMatchObject({ user_id: 123, category_id: 0, ...expected });
expect(friends[0]).not.toHaveProperty('phone_num');
expect(friends[0]).not.toHaveProperty('birthday_year');
expect(fetchFriendList).toHaveBeenCalledWith({ withProfile: true });
expect(await getStrangerInfo(bridge, 123)).toMatchObject(expected);
});
it('does not mask explicit enrichment failures with cached friends', async () => {
const bridge = fakeBridge({
fetchFriendList: vi.fn().mockRejectedValue(new Error('profile failed')),
identity: fakeIdentity({ friends: [makeFriend(123, 'Cached')] }),
});
await expect(getFriendList(bridge, true)).rejects.toThrow('profile failed');
// The legacy ordinary-list cache behavior remains available.
expect((await getFriendList(bridge))[0]?.nickname).toBe('Cached');
});
});
// ─── Tests ───
describe('onebot/contact-actions / getLoginInfo', () => {
@@ -645,6 +708,29 @@ describe('onebot/contact-actions / getGroupMemberInfo', () => {
expect(out).toMatchObject({ user_id: 55, nickname: 'eve' });
});
it('retries a failed legacy card refresh and then reuses the confirmed empty card', async () => {
const fresh = makeMember(66, 'legacy', '');
let member: GroupMemberInfo = { ...fresh, card: undefined };
const fetchGroupMemberList = vi
.fn(async () => {
member = fresh;
return [fresh];
})
.mockRejectedValueOnce(new Error('roster offline'));
const bridge = fakeBridge({
fetchGroupMemberList,
identity: fakeIdentity({ findGroupMember: () => member }),
});
await expect(getGroupMemberInfo(bridge, 1200, 66)).rejects.toThrow('roster offline');
expect(await getGroupMemberInfo(bridge, 1200, 66)).toMatchObject({
nickname: 'legacy',
card: '',
});
expect(await getGroupMemberInfo(bridge, 1200, 66)).toMatchObject({ card: '' });
expect(fetchGroupMemberList).toHaveBeenCalledTimes(2);
expect(fetchGroupMemberList).toHaveBeenCalledWith(1200, { force: false });
});
it('refreshes a persisted member whose robot classification is unknown', async () => {
let member: GroupMemberInfo = { ...makeMember(66, 'legacy'), isRobot: undefined };
const fetchGroupMemberList = vi.fn(async () => {
@@ -970,6 +1056,98 @@ describe('onebot/contact-actions / getStrangerInfo', () => {
});
describe('onebot/contact-actions / getGroupSystemMessages', () => {
it('reports the invitee, inviter and reviewing operator independently (#643)', async () => {
const bridge = fakeBridge({
fetchGroupRequests: vi.fn(async (filtered: boolean) =>
filtered ? [] : [makeGroupRequest({ state: 2 })],
),
});
expect(await getGroupSystemMessages(bridge)).toEqual([
expect.objectContaining({
requester_uin: 123,
target_uin: 123,
target_nick: 'target',
target_status: 'known',
invitor_uin: 456,
invitor_nick: 'inviter',
invitor_status: 'known',
operator_uin: 789,
operator_nick: 'operator',
operator_status: 'known',
}),
]);
});
it('marks omitted actors unknown rather than claiming there was no inviter', async () => {
const bridge = fakeBridge({
fetchGroupRequests: vi.fn(async (filtered: boolean) =>
filtered
? []
: [
makeGroupRequest({
invitorUid: '',
invitorUin: 0,
invitorName: '',
operatorUid: '',
operatorUin: 0,
operatorName: '',
}),
],
),
});
expect(await getGroupSystemMessages(bridge)).toEqual([
expect.objectContaining({
invitor_uin: 0,
invitor_status: 'unknown',
operator_uin: 0,
operator_status: 'unknown',
}),
]);
});
it('resolves UID-only inviters and operators as well as the requester', async () => {
const fetchUserProfileByUid = vi.fn(async (uid: string) =>
makeProfile(uid === 'u_inviter' ? 456 : 789, uid),
);
const bridge = fakeBridge({
fetchGroupRequests: vi.fn(async (filtered: boolean) =>
filtered ? [] : [makeGroupRequest({ invitorUin: 0, operatorUin: 0 })],
),
fetchUserProfileByUid,
identity: fakeIdentity({ findUinByUid: () => null }),
});
expect(await getGroupSystemMessages(bridge)).toEqual([
expect.objectContaining({
invitor_uin: 456,
invitor_status: 'known',
operator_uin: 789,
operator_status: 'known',
}),
]);
expect(fetchUserProfileByUid.mock.calls.map(([uid]) => uid).sort()).toEqual([
'u_inviter',
'u_operator',
]);
});
it.each(['invitor', 'operator'] as const)(
'propagates %s lookup failures instead of reporting absence',
async (role) => {
const bridge = fakeBridge({
fetchGroupRequests: vi.fn(async (filtered: boolean) =>
filtered ? [] : [makeGroupRequest({ [`${role}Uin`]: 0 })],
),
fetchUserProfileByUid: vi.fn(async () => {
throw new Error('profile offline');
}),
identity: fakeIdentity({ findUinByUid: () => null }),
});
await expect(getGroupSystemMessages(bridge)).rejects.toThrow(
`failed to resolve ${role} UIN`,
);
},
);
it('reads both request inboxes with the requested per-inbox count', async () => {
const fetchGroupRequests = vi.fn(async (filtered: boolean) =>
filtered
@@ -1064,6 +1242,8 @@ describe('onebot/contact-actions / getGroupSystemMessages', () => {
expect.objectContaining({
requester_uin: 45_678,
requester_nick: 'inviter',
target_uin: 10_001,
target_nick: 'bot',
invitor_uin: 45_678,
invitor_nick: 'inviter',
}),
+25 -2
View File
@@ -112,6 +112,28 @@ describe('convertEvent — message kinds', () => {
expect(out!.message_id).toBe(PEER_UIN + 1);
});
it.each([makeFriendMessage(PEER_UIN), makeTempMessage(PEER_UIN)])(
'exposes only QQ-marked auto replies in $kind',
async (event) => {
const manual = await convertEvent(bareCtx(), {
...event,
elements: [{ type: 'text', text: '[自动回复] 稍后联系' }],
});
const automatic = await convertEvent(bareCtx(), { ...event, autoReply: true });
expect(manual).toMatchObject({
message: [{ type: 'text', data: { text: '[自动回复] 稍后联系' } }],
raw_message: '&#91;自动回复&#93; 稍后联系',
});
expect(manual).not.toHaveProperty('auto_reply');
expect(automatic).toMatchObject({
auto_reply: true,
message: [{ type: 'text', data: { text: 'hi' } }],
raw_message: 'hi',
});
},
);
it('group_message peer → post_type "message", sub_type "normal", group_id set', async () => {
const out = await convertEvent(bareCtx(), makeGroupMessage(PEER_UIN));
expect(out!.post_type).toBe('message');
@@ -673,10 +695,11 @@ describe('convertEvent — message elements', () => {
PRIVATE_SENT_MESSAGE_EVENT,
1234,
[{ type: 'text', text: 'quoted text' }],
undefined,
]);
});
it('reply: replySeq=0 -> id "0", no resolver call', async () => {
it('reply: replySeq=0 is omitted without calling the resolver', async () => {
let resolverCalls = 0;
const seg = await segment(
{ type: 'reply', replySeq: 0 },
@@ -687,7 +710,7 @@ describe('convertEvent — message elements', () => {
},
},
);
expect((seg.data as Record<string, unknown>).id).toBe('0');
expect(seg).toBeUndefined();
expect(resolverCalls).toBe(0);
});
+7 -2
View File
@@ -343,7 +343,11 @@ describe('registerEventPipeline', () => {
message: {
responseHead: {
fromUin: SELF_ID,
grp: { groupUin: GROUP_ID, memberCard: 'self', groupName: 'test group' },
grp: {
groupUin: GROUP_ID,
memberCard: Buffer.from('self'),
groupName: 'test group',
},
},
contentHead: {
msgType: 82,
@@ -615,9 +619,10 @@ describe('registerEventPipeline', () => {
const backfillGate = new Promise<void>((resolve) => {
releaseBackfill = resolve;
});
vi.mocked(backfillReplyTarget).mockImplementationOnce(async () => {
vi.mocked(backfillReplyTarget).mockImplementationOnce(async (_ref, event) => {
markBackfillStarted();
await backfillGate;
return event;
});
const isPrivateMessageRecalled = vi
.fn()
+56 -4
View File
@@ -828,6 +828,56 @@ describe('extended-actions / get_essence_msg_list', () => {
});
describe('extended-actions / get_friends_with_category', () => {
it('forwards explicit enrichment and uses the same public field names', async () => {
const fetchFriendCategories = vi.fn(async () => [
{
categoryId: 0,
categoryName: 'Friends',
memberCount: 1,
sortId: 0,
friends: [
{
uin: 10001,
uid: 'u1',
nickname: 'Name',
remark: '',
profile: {
sign: '',
age: 0,
vipFlag: false,
privilegeIcons: { open: [], closed: [] },
},
},
],
},
]);
const handler = makeHandler(fakeCtx(fakeBridge({ fetchFriendCategories })));
expect(
await handler.handle('get_friends_with_category', { with_profile: true }),
).toMatchObject({
status: 'ok',
data: [
{
buddyList: [
{
user_id: 10001,
category_id: 0,
long_nick: '',
age: 0,
is_qq_vip: false,
privilege_icons: { open: [], closed: [] },
},
],
},
],
});
expect(fetchFriendCategories).toHaveBeenCalledWith({ withProfile: true });
expect(
await handler.handle('get_friends_with_category', { with_profile: 'invalid' }),
).toMatchObject({ status: 'failed' });
expect(fetchFriendCategories).toHaveBeenCalledOnce();
});
it('returns the exact categorized friend contract', async () => {
const fetchFriendCategories = vi.fn(async () => [
{
@@ -848,7 +898,7 @@ describe('extended-actions / get_friends_with_category', () => {
categoryId: 7,
categoryName: 'Work',
categoryMbCount: 1,
buddyList: [{ user_id: 10001, nickname: 'Alice', remark: 'A' }],
buddyList: [{ user_id: 10001, nickname: 'Alice', remark: 'A', category_id: 7 }],
},
]);
});
@@ -1250,7 +1300,7 @@ function fakeFilteredRequest(overrides: Partial<GroupRequestInfo> = {}): GroupRe
operatorName: 'op',
sequence: 42,
state: 1,
eventType: 7,
eventType: 1,
comment: 'pls',
filtered: true,
...overrides,
@@ -1260,7 +1310,9 @@ function fakeFilteredRequest(overrides: Partial<GroupRequestInfo> = {}): GroupRe
describe('extended-actions / get_group_ignored_notifies', () => {
it('maps filtered fetchGroupRequests(true) into the napcat shape', async () => {
const fetchGroupRequests = vi.fn(async (filtered: boolean) =>
filtered ? [fakeFilteredRequest()] : [],
filtered
? [fakeFilteredRequest(), fakeFilteredRequest({ sequence: 43, eventType: 7 })]
: [],
);
const bridge = fakeBridge({ fetchGroupRequests: fetchGroupRequests as any });
const h = makeHandler(fakeCtx(bridge));
@@ -1279,7 +1331,7 @@ describe('extended-actions / get_group_ignored_notifies', () => {
actor: 8888,
invitor_uin: 7777,
invitor_nick: 'inviter',
flag: 'slreq:1:42:999:7:1',
flag: 'slreq:1:42:999:1:1',
},
]);
});
Loaded 100 of 234 files, more files were not shown because too many files have changed in this diff. Show more