Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9faec0e28 | ||
|
|
4a10f38743 | ||
|
|
a1688a33b0 | ||
|
|
45c3a6841a | ||
|
|
2b63f375fc | ||
|
|
0fa912a32e | ||
|
|
5f1700fc1b | ||
|
|
54038c775a | ||
|
|
c15ecd0402 | ||
|
|
f79187f36a | ||
|
|
24ec8a7eba | ||
|
|
3773106425 | ||
|
|
f65880b164 | ||
|
|
8d9f44b6b0 | ||
|
|
bd40ac3522 | ||
|
|
60733aacab | ||
|
|
a2ce3b2c19 | ||
|
|
7882081bdb | ||
|
|
f1ef07544d |
No files matched your search
@@ -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` 通过
|
||||
|
||||
@@ -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}`);
|
||||
};
|
||||
@@ -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'],
|
||||
);
|
||||
});
|
||||
@@ -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 });
|
||||
@@ -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,14 @@ 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.
|
||||
- **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 +121,8 @@ 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.
|
||||
|
||||
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
@@ -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 —— 这个项目能走多远,取决于你们每一个人。❄️
|
||||
|
||||
|
||||
+3
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "2.3.1",
|
||||
"version": "2.3.4",
|
||||
"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,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "2.3.1",
|
||||
"version": "2.3.4",
|
||||
"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).",
|
||||
|
||||
@@ -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,6 +111,11 @@ 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 detecting = false;
|
||||
private lastDetectFailure = '';
|
||||
@@ -184,6 +197,7 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
unload(): Promise<HookProcessInfo> {
|
||||
this.cancelConnectAttempt?.();
|
||||
return this.traceCommand('unload', () => this.unloadInternal());
|
||||
}
|
||||
|
||||
@@ -197,19 +211,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 +256,7 @@ export class HookSession extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
this.cancelConnectAttempt?.();
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
@@ -248,6 +270,7 @@ export class HookSession extends EventEmitter {
|
||||
this.pid,
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
]);
|
||||
this.stopInitialConnectionWatch();
|
||||
this.tearDownClient();
|
||||
this.injected = false;
|
||||
this.injectResult = null;
|
||||
@@ -292,6 +315,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 +398,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 +435,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 +465,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 +545,11 @@ export class HookSession extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.initialConnectionError) {
|
||||
this.setStatus('error', this.initialConnectionError);
|
||||
return;
|
||||
}
|
||||
|
||||
this.setStatus(
|
||||
statusFor({
|
||||
injected: this.injected,
|
||||
@@ -529,6 +573,8 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
this.startInitialConnectionWatch();
|
||||
|
||||
if (this.client?.isClosed) {
|
||||
this.tearDownClient();
|
||||
}
|
||||
@@ -627,15 +673,26 @@ 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;
|
||||
this.hasConnected = true;
|
||||
this.stopInitialConnectionWatch();
|
||||
this.initialConnectionError = '';
|
||||
const loginState = client.getLoginState();
|
||||
|
||||
// handleLoginState owns the connected+loggedIn → 'online' (+ login
|
||||
@@ -659,11 +716,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 +748,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 +844,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 +859,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 +890,7 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
private tearDownClient(preserveRuntimeFailure = false): void {
|
||||
this.cancelConnectAttempt?.();
|
||||
this.stopLoginReconcile();
|
||||
this.resetReceiveWatch();
|
||||
const client = this.client;
|
||||
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/common",
|
||||
"version": "2.3.1",
|
||||
"version": "2.3.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/core",
|
||||
"version": "2.3.1",
|
||||
"version": "2.3.4",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { GroupInviteTracker } from '@snowluma/protocol/group-invite-tracker';
|
||||
import { isSelfGroupInvitation } from '@snowluma/protocol/qq-info';
|
||||
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
|
||||
import {
|
||||
FetchFriendListPage,
|
||||
@@ -43,6 +44,7 @@ import type {
|
||||
FriendInfo,
|
||||
GroupMemberInfo,
|
||||
GroupRequestInfo,
|
||||
PublicProfileFields,
|
||||
QQGroupInfo,
|
||||
UserProfileInfo,
|
||||
} from '@snowluma/protocol/qq-info';
|
||||
@@ -93,6 +95,13 @@ function normalizeGroupRequestSequence(
|
||||
}
|
||||
|
||||
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,6 +120,15 @@ 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) {}
|
||||
|
||||
@@ -176,7 +194,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 +290,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[]]),
|
||||
);
|
||||
@@ -607,7 +698,7 @@ export class ContactsApi {
|
||||
|
||||
return subType === 'add'
|
||||
? request.eventType === 1 && request.targetUid === uid
|
||||
: (request.eventType === 2 || request.eventType === 22) &&
|
||||
: (isSelfGroupInvitation(request) || request.eventType === 22) &&
|
||||
request.invitorUid === uid &&
|
||||
request.targetUid === invitedUid;
|
||||
}) ?? null
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) },
|
||||
],
|
||||
},
|
||||
},
|
||||
@@ -478,8 +478,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 +508,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 +535,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 },
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
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();
|
||||
});
|
||||
|
||||
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('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');
|
||||
});
|
||||
});
|
||||
@@ -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: '所有人可见' };
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/mcp",
|
||||
"version": "2.3.1",
|
||||
"version": "2.3.4",
|
||||
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -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": "好友"
|
||||
@@ -6440,7 +6622,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 +6649,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 +6848,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": "扩展"
|
||||
@@ -11241,6 +11605,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 +12819,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 +12832,7 @@
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"desc": "主页或推荐列表返回的完整动态,保留所有原始字段"
|
||||
"desc": "主页、详情或推荐列表返回的完整动态,保留所有原始字段"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
@@ -12408,7 +12842,7 @@
|
||||
"feed": {
|
||||
"type": "object",
|
||||
"additionalProperties": true,
|
||||
"description": "主页或推荐列表返回的完整动态,保留所有原始字段"
|
||||
"description": "主页、详情或推荐列表返回的完整动态,保留所有原始字段"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -12807,6 +13241,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 +13417,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 +13429,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 +21503,7 @@
|
||||
},
|
||||
{
|
||||
"category": "空间",
|
||||
"count": 28
|
||||
"count": 29
|
||||
},
|
||||
{
|
||||
"category": "系统表情",
|
||||
|
||||
@@ -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": "好友"
|
||||
@@ -6443,7 +6625,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 +6652,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 +6851,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": "扩展"
|
||||
@@ -11244,6 +11608,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 +12822,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 +12835,7 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"desc": "主页或推荐列表返回的完整动态,保留所有原始字段"
|
||||
"desc": "主页、详情或推荐列表返回的完整动态,保留所有原始字段"
|
||||
}
|
||||
],
|
||||
"invariants": [],
|
||||
@@ -12411,7 +12845,7 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"feed": {
|
||||
"type": "object",
|
||||
"additionalProperties": true,
|
||||
"description": "主页或推荐列表返回的完整动态,保留所有原始字段"
|
||||
"description": "主页、详情或推荐列表返回的完整动态,保留所有原始字段"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -12810,6 +13244,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 +13420,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 +13432,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 +21507,7 @@ export const CATEGORIES: CatalogCategory[] = [
|
||||
},
|
||||
{
|
||||
"category": "空间",
|
||||
"count": 28
|
||||
"count": 29
|
||||
},
|
||||
{
|
||||
"category": "系统表情",
|
||||
|
||||
@@ -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.
|
||||
@@ -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`.
|
||||
@@ -0,0 +1,28 @@
|
||||
# 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.
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/onebot",
|
||||
"version": "2.3.1",
|
||||
"version": "2.3.4",
|
||||
"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>'`.",
|
||||
|
||||
@@ -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'],
|
||||
};
|
||||
@@ -21,6 +21,8 @@ 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,
|
||||
@@ -2647,7 +2649,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 +2663,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),
|
||||
),
|
||||
})),
|
||||
);
|
||||
},
|
||||
|
||||
@@ -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: '自定义账号标识(仅查到资料时返回)' },
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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[]>;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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))) {
|
||||
|
||||
@@ -100,7 +100,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),
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -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,
|
||||
@@ -49,9 +55,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;
|
||||
@@ -205,27 +210,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(
|
||||
@@ -618,217 +618,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 +997,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(
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from '@snowluma/protocol/dataline/device-contacts';
|
||||
import {
|
||||
formatGroupRequestFlag,
|
||||
isSelfGroupInvitation,
|
||||
type GroupMemberInfo,
|
||||
type GroupRequestInfo,
|
||||
type UserProfileInfo,
|
||||
@@ -14,6 +15,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 +51,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)));
|
||||
@@ -393,6 +402,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 +456,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) {
|
||||
@@ -573,11 +589,12 @@ async function resolveRequesterUins(
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/** Join request (7) or invite that still needs an admin (5 / mapped 22). */
|
||||
/** Join requests, self invitations, and invitations awaiting administrator approval. */
|
||||
function isJoinOrInviteNotify(notifyType: number | undefined): boolean {
|
||||
return (
|
||||
notifyType === undefined ||
|
||||
notifyType === 1 ||
|
||||
notifyType === 2 ||
|
||||
notifyType === 5 ||
|
||||
notifyType === 7 ||
|
||||
notifyType === 22
|
||||
@@ -589,7 +606,7 @@ function groupRequestActor(request: GroupRequestInfo): {
|
||||
uin: number;
|
||||
name: string;
|
||||
} {
|
||||
if (request.notifyType === 1) {
|
||||
if (isSelfGroupInvitation(request)) {
|
||||
return {
|
||||
uid: request.invitorUid,
|
||||
uin: request.invitorUin,
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
@@ -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).
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { GroupRequestHandle, GroupRequestInfo } from '@snowluma/protocol/qq-info';
|
||||
import {
|
||||
isSelfGroupInvitation,
|
||||
type GroupRequestHandle,
|
||||
type GroupRequestInfo,
|
||||
} from '@snowluma/protocol/qq-info';
|
||||
|
||||
const log = createLogger('OneBot.Request');
|
||||
|
||||
@@ -265,7 +269,7 @@ export async function handleGroupAddRequest(
|
||||
|
||||
if (
|
||||
notice &&
|
||||
(request.eventType !== 2 ||
|
||||
(!isSelfGroupInvitation(request) ||
|
||||
(request.targetUin > 0 && request.targetUin !== Number(bridge.identity.uin)) ||
|
||||
(request.targetUid &&
|
||||
bridge.identity.selfUid &&
|
||||
@@ -282,6 +286,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,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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' }),
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -673,10 +673,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 +688,7 @@ describe('convertEvent — message elements', () => {
|
||||
},
|
||||
},
|
||||
);
|
||||
expect((seg.data as Record<string, unknown>).id).toBe('0');
|
||||
expect(seg).toBeUndefined();
|
||||
expect(resolverCalls).toBe(0);
|
||||
});
|
||||
|
||||
|
||||
@@ -615,9 +615,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()
|
||||
|
||||
@@ -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 }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1,9 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { ApiActionContext } from '../src/api-handler';
|
||||
import { actions } from '../src/actions/friend';
|
||||
|
||||
const getStrangerInfo = actions.find((action) => action.names[0] === 'get_stranger_info');
|
||||
|
||||
describe('get_friend_list profile option', () => {
|
||||
it('defaults off, validates the option and forwards explicit enrichment', async () => {
|
||||
const action = actions.find((entry) => entry.names[0] === 'get_friend_list')!;
|
||||
const getFriendList = vi.fn(async () => []);
|
||||
const handler = action.toHandler({ getFriendList } as unknown as ApiActionContext);
|
||||
await handler({});
|
||||
expect(getFriendList).toHaveBeenLastCalledWith(false);
|
||||
await handler({ with_profile: true });
|
||||
expect(getFriendList).toHaveBeenLastCalledWith(true);
|
||||
expect(await handler({ with_profile: 'invalid' })).toMatchObject({ status: 'failed' });
|
||||
expect(getFriendList).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
await action.toHandler({} as ApiActionContext)({ with_profile: true }),
|
||||
).toMatchObject({ status: 'failed', wording: 'friend profile provider unavailable' });
|
||||
});
|
||||
});
|
||||
|
||||
if (!getStrangerInfo) {
|
||||
throw new Error('get_stranger_info action missing');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { Bridge } from '@snowluma/core/bridge';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { MSG_PUSH_CMD } from '@snowluma/protocol/msg-push';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { PushMsg } from '@snowluma/proto-defs/message';
|
||||
import type { GroupInvite } from '@snowluma/proto-defs/notify';
|
||||
import type { OidbBase, OidbSvcTrpcTcp0x10C0Response } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbGroupRequestAction } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { getGroupSystemMessages } from '../src/modules/contact-actions';
|
||||
import { handleGroupAddRequest } from '../src/modules/request-actions';
|
||||
|
||||
const bridges: Bridge[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(bridges.splice(0).map((bridge) => bridge.dispose()));
|
||||
});
|
||||
|
||||
function setup(filtered = false, overrides: { targetUid?: string; state?: number } = {}) {
|
||||
const bridge = new Bridge(IdentityService.memory('10001'));
|
||||
bridges.push(bridge);
|
||||
bridge.identity.setSelfProfile({
|
||||
uin: 10001,
|
||||
uid: 'u_self',
|
||||
nickname: 'bot',
|
||||
remark: '',
|
||||
qid: '',
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
sign: '',
|
||||
avatar: '',
|
||||
level: 0,
|
||||
qidianMasterFlag: 0,
|
||||
qidianCrewFlag: 0,
|
||||
qidianCrewFlag2: 0,
|
||||
});
|
||||
bridge.identity.rememberRequestIdentity({ groupId: 999, uid: 'u_self', uin: 10001 });
|
||||
bridge.identity.rememberRequestIdentity({ groupId: 999, uid: 'u_inviter', uin: 456 });
|
||||
const operateTransInfo = Uint8Array.from([8, 42, 16, 231, 7, 24, 2]);
|
||||
const record = {
|
||||
sequence: 42n,
|
||||
eventType: 2,
|
||||
state: overrides.state ?? 1,
|
||||
group: { groupUin: 999, groupName: 'group' },
|
||||
target: { uid: overrides.targetUid ?? 'u_self', name: 'bot' },
|
||||
invitor: { uid: 'u_inviter', name: 'inviter' },
|
||||
operateTransInfo,
|
||||
};
|
||||
const send = vi.spyOn(bridge, 'sendRawPacket').mockImplementation(async (cmd) => {
|
||||
let responseData = Buffer.alloc(0);
|
||||
|
||||
if (cmd.startsWith('OidbSvcTrpcTcp.0x10c0_')) {
|
||||
responseData = Buffer.from(
|
||||
protobuf_encode<OidbBase<OidbSvcTrpcTcp0x10C0Response>>({
|
||||
body: { requests: cmd.endsWith(filtered ? '_2' : '_1') ? [record] : [] },
|
||||
}),
|
||||
);
|
||||
} else if (!cmd.startsWith('OidbSvcTrpcTcp.0x10c8_')) {
|
||||
throw new Error(`unexpected request: ${cmd}`);
|
||||
}
|
||||
|
||||
return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
|
||||
});
|
||||
const flags: string[] = [];
|
||||
bridge.events.on('group_invite', (event) => flags.push(event.flag));
|
||||
const notice = () =>
|
||||
bridge.onPacket({
|
||||
pid: 1,
|
||||
uin: '10001',
|
||||
serviceCmd: MSG_PUSH_CMD,
|
||||
seqId: 1,
|
||||
retCode: 0,
|
||||
fromClient: false,
|
||||
body: Buffer.from(
|
||||
protobuf_encode<PushMsg>({
|
||||
message: {
|
||||
contentHead: { msgType: 87, timestamp: 1 },
|
||||
body: {
|
||||
msgContent: protobuf_encode<GroupInvite>({
|
||||
groupUin: 999,
|
||||
invitorUid: 'u_inviter',
|
||||
}),
|
||||
},
|
||||
},
|
||||
status: 0,
|
||||
}),
|
||||
),
|
||||
});
|
||||
return { bridge, send, flags, notice, operateTransInfo };
|
||||
}
|
||||
|
||||
describe('non-friend group invitations', () => {
|
||||
it.each([
|
||||
{ approve: true, filtered: false },
|
||||
{ approve: false, filtered: true },
|
||||
])('handles an emitted flag through the real codecs: %j', async ({ approve, filtered }) => {
|
||||
const { bridge, send, flags, notice, operateTransInfo } = setup(filtered);
|
||||
await notice();
|
||||
expect(flags).toEqual(['invite:999:u_inviter']);
|
||||
await handleGroupAddRequest(bridge, flags[0]!, approve, '');
|
||||
const approval = send.mock.calls.find(([cmd]) => cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'))!;
|
||||
expect(approval[0]).toBe(`OidbSvcTrpcTcp.0x10c8_${filtered ? 2 : 1}`);
|
||||
const wire = protobuf_decode<OidbBase<OidbGroupRequestAction>>(approval[1]);
|
||||
expect(wire.body).toMatchObject({
|
||||
accept: approve ? 1 : 2,
|
||||
body: { sequence: 42n, groupUin: 999, eventType: 10, message: ' ', operateTransInfo },
|
||||
});
|
||||
expect(
|
||||
await bridge.apis.contacts.resolveGroupJoinRequest(
|
||||
999,
|
||||
'u_inviter',
|
||||
'invite',
|
||||
'u_self',
|
||||
),
|
||||
).toMatchObject({ notifyType: 2, eventType: 10 });
|
||||
});
|
||||
|
||||
it('lists the inviter and returns a flag that can approve the same invitation', async () => {
|
||||
const { bridge, send, operateTransInfo } = setup();
|
||||
const rows = await getGroupSystemMessages(bridge);
|
||||
expect(rows).toEqual([
|
||||
expect.objectContaining({
|
||||
group_id: 999,
|
||||
requester_uin: 456,
|
||||
requester_nick: 'inviter',
|
||||
checked: false,
|
||||
flag: 'slreq:1:42:999:10:0',
|
||||
}),
|
||||
]);
|
||||
await handleGroupAddRequest(bridge, String(rows[0]!.flag), true, '');
|
||||
const approval = send.mock.calls.find(([cmd]) => cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'))!;
|
||||
const wire = protobuf_decode<OidbBase<OidbGroupRequestAction>>(approval[1]);
|
||||
expect(wire.body?.body).toMatchObject({ eventType: 10, operateTransInfo });
|
||||
});
|
||||
|
||||
it.each([{ targetUid: 'u_other' }, { state: 2 }])(
|
||||
'rejects a mismatched or processed invitation: %j',
|
||||
async (overrides) => {
|
||||
const { bridge, send, flags, notice } = setup(false, overrides);
|
||||
await notice();
|
||||
await expect(handleGroupAddRequest(bridge, flags[0]!, true, '')).rejects.toThrow(
|
||||
'matching group request not found',
|
||||
);
|
||||
expect(send.mock.calls.some(([cmd]) => cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'))).toBe(
|
||||
false,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -219,7 +219,7 @@ describe('group request events', () => {
|
||||
expect(received).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([22, 2])(
|
||||
it.each([22, 2, 10])(
|
||||
'cannot use a self-invitation flag to approve another account joining the group (type %i)',
|
||||
async (eventType) => {
|
||||
const { bridge, received, fetchRequests } = setup();
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import http, { type IncomingMessage } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { HttpServerAdapter } from '../src/network/http-server-adapter';
|
||||
import type { NetworkAdapterContext } from '../src/network/adapter';
|
||||
import { buildDispatchPayload } from '../src/event-filter';
|
||||
import type { HttpServerNetwork, JsonObject } from '../src/types';
|
||||
|
||||
const adapters: HttpServerAdapter[] = [];
|
||||
const responses: IncomingMessage[] = [];
|
||||
|
||||
async function start(overrides: Partial<HttpServerNetwork> = {}, uin = '10001') {
|
||||
const config: HttpServerNetwork = {
|
||||
name: 'sse',
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
path: '/api',
|
||||
enableSse: true,
|
||||
accessToken: 'test-secret',
|
||||
...overrides,
|
||||
};
|
||||
const api = {
|
||||
isAcceptingActions: true,
|
||||
isStreamAction: () => false,
|
||||
handle: vi.fn(async () => ({ status: 'ok', retcode: 0, data: { self_id: uin } })),
|
||||
};
|
||||
const adapter = new HttpServerAdapter(config.name, config, {
|
||||
uin,
|
||||
api,
|
||||
buildLifecycleEvent: (subType: string) => ({
|
||||
self_id: uin,
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'lifecycle',
|
||||
sub_type: subType,
|
||||
}),
|
||||
buildHeartbeatEvent: () => ({
|
||||
self_id: uin,
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'heartbeat',
|
||||
}),
|
||||
} as unknown as NetworkAdapterContext);
|
||||
adapters.push(adapter);
|
||||
await adapter.open();
|
||||
const port = ((adapter as unknown as { server: http.Server }).server.address() as AddressInfo)
|
||||
.port;
|
||||
const request = (
|
||||
path = '/api/_events?access_token=test-secret',
|
||||
headers: Record<string, string> = {},
|
||||
method = 'GET',
|
||||
): Promise<IncomingMessage> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const req = http.request(
|
||||
{ hostname: '127.0.0.1', port, path, headers, method },
|
||||
(res) => {
|
||||
responses.push(res);
|
||||
// A stream closed intentionally by the test/server can be aborted.
|
||||
res.on('error', () => undefined);
|
||||
resolve(res);
|
||||
},
|
||||
);
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
|
||||
const emit = (id: number, postType = 'message') => {
|
||||
const event: JsonObject = {
|
||||
self_id: uin,
|
||||
post_type: postType,
|
||||
message_id: id,
|
||||
message: [{ type: 'text', data: { text: `line\n${id}` } }],
|
||||
raw_message: `line\n${id}`,
|
||||
};
|
||||
adapter.onEvent(event, buildDispatchPayload(event));
|
||||
};
|
||||
|
||||
return { adapter, config, request, emit, api };
|
||||
}
|
||||
|
||||
function collect(response: IncomingMessage) {
|
||||
let text = '';
|
||||
response.setEncoding('utf8');
|
||||
response.on('data', (chunk: string) => {
|
||||
text += chunk;
|
||||
});
|
||||
const frames = () =>
|
||||
text
|
||||
.split('\n\n')
|
||||
.filter((frame) => frame.includes('data: '))
|
||||
.map((frame) => {
|
||||
const id = /^id: (.+)$/m.exec(frame)?.[1];
|
||||
const data = JSON.parse(/^data: (.+)$/m.exec(frame)![1]) as JsonObject;
|
||||
return { id, data };
|
||||
});
|
||||
return { frames, text: () => text };
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
responses.splice(0).forEach((res) => res.destroy());
|
||||
await Promise.all(adapters.splice(0).map((adapter) => adapter.close()));
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('HTTP OneBot SSE', () => {
|
||||
it('shares HTTP actions and prefix, authenticates all supported token forms, and frames events', async () => {
|
||||
const { adapter, request, emit, api } = await start();
|
||||
expect((await request('/wrong/_events?access_token=test-secret')).statusCode).toBe(404);
|
||||
expect((await request('/api/_events')).statusCode).toBe(401);
|
||||
expect((await request('/api/_events?access_token=wrong')).statusCode).toBe(401);
|
||||
expect((await request(undefined, {}, 'POST')).statusCode).toBe(405);
|
||||
const streams = [];
|
||||
|
||||
for (const [path, headers] of [
|
||||
['/api/_events?access_token=test-secret', {}],
|
||||
['/api/_events', { authorization: 'Bearer test-secret' }],
|
||||
['/api/_events', { authorization: 'test-secret' }],
|
||||
] as Array<[string, Record<string, string>]>) {
|
||||
const res = await request(path, headers);
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers['content-type']).toContain('text/event-stream');
|
||||
expect(res.headers['cache-control']).toBe('no-cache, no-transform');
|
||||
expect(res.headers['x-accel-buffering']).toBe('no');
|
||||
streams.push(collect(res));
|
||||
}
|
||||
|
||||
emit(1);
|
||||
emit(2, 'message_sent');
|
||||
emit(3);
|
||||
await vi.waitFor(() =>
|
||||
expect(streams.every((stream) => stream.frames().length === 5)).toBe(true),
|
||||
);
|
||||
expect(
|
||||
streams[0]
|
||||
.frames()
|
||||
.slice(3)
|
||||
.map((frame) => frame.data.message_id),
|
||||
).toEqual([1, 3]);
|
||||
expect(streams[0].frames()[3].data.message).toEqual([
|
||||
{ type: 'text', data: { text: 'line\n1' } },
|
||||
]);
|
||||
expect(streams[0].text()).toContain('retry: 3000\n\n');
|
||||
const action = await request('/api/get_status', { authorization: 'test-secret' }, 'POST');
|
||||
expect(action.statusCode).toBe(200);
|
||||
expect(api.handle).toHaveBeenCalledWith('get_status', {});
|
||||
expect(adapter.describeStatus().detail).toContain('SSE 3 个客户端');
|
||||
});
|
||||
|
||||
it('replays exactly the missing events and maintains report format and self-message policy', async () => {
|
||||
const { request, emit } = await start({ messageFormat: 'string', reportSelfMessage: true });
|
||||
const initial = await request();
|
||||
const first = collect(initial);
|
||||
emit(1);
|
||||
await vi.waitFor(() => expect(first.frames()).toHaveLength(4));
|
||||
const cursor = first.frames()[3].id!;
|
||||
initial.destroy();
|
||||
emit(2, 'message_sent');
|
||||
emit(3);
|
||||
const resumed = collect(await request(undefined, { 'Last-Event-ID': cursor }));
|
||||
await vi.waitFor(() => expect(resumed.frames()).toHaveLength(5));
|
||||
expect(
|
||||
resumed
|
||||
.frames()
|
||||
.slice(0, 2)
|
||||
.map((frame) => frame.data.message_id),
|
||||
).toEqual([2, 3]);
|
||||
expect(resumed.frames()[0].data.message).toBe('line\n2');
|
||||
expect(resumed.frames()[0].data.post_type).toBe('message_sent');
|
||||
});
|
||||
|
||||
it('rejects expired, malformed, future and other-account cursors without silently losing events', async () => {
|
||||
const first = await start();
|
||||
const second = await start({}, '10002');
|
||||
const stream = collect(await first.request());
|
||||
await vi.waitFor(() => expect(stream.frames()).toHaveLength(3));
|
||||
const cursor = stream.frames()[0].id!;
|
||||
const header = { 'Last-Event-ID': cursor };
|
||||
expect((await second.request(undefined, header)).statusCode).toBe(409);
|
||||
expect((await first.request(undefined, { 'Last-Event-ID': 'broken' })).statusCode).toBe(
|
||||
400,
|
||||
);
|
||||
expect(
|
||||
(await first.request(undefined, { 'Last-Event-ID': cursor.replace(/:0$/, ':99') }))
|
||||
.statusCode,
|
||||
).toBe(409);
|
||||
|
||||
for (let i = 0; i < 257; i += 1) {
|
||||
first.emit(i);
|
||||
}
|
||||
|
||||
expect((await first.request(undefined, header)).statusCode).toBe(409);
|
||||
// A new subscription remains possible after explicit resynchronization.
|
||||
expect((await first.request()).statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('revokes live streams on token/report policy changes and closes without waiting on SSE', async () => {
|
||||
const { adapter, config, request } = await start();
|
||||
const res = await request();
|
||||
const closed = new Promise<void>((resolve) => res.once('close', resolve));
|
||||
await adapter.reload({ ...config, accessToken: 'rotated' });
|
||||
await closed;
|
||||
expect((await request()).statusCode).toBe(401);
|
||||
const next = await request('/api/_events?access_token=rotated');
|
||||
const changed = new Promise<void>((resolve) => next.once('close', resolve));
|
||||
await adapter.reload({ ...config, accessToken: 'rotated', reportSelfMessage: true });
|
||||
await changed;
|
||||
const last = await request('/api/_events?access_token=rotated');
|
||||
const ended = new Promise<void>((resolve) => last.once('close', resolve));
|
||||
await adapter.close();
|
||||
await ended;
|
||||
expect(adapter.describeStatus().status).toBe('disabled');
|
||||
});
|
||||
|
||||
it('is opt-in and can be enabled/disabled live without replacing the HTTP listener', async () => {
|
||||
const { adapter, config, request } = await start({ enableSse: false });
|
||||
expect((await request()).statusCode).toBe(404);
|
||||
await adapter.reload({ ...config, enableSse: true });
|
||||
const stream = await request();
|
||||
expect(stream.statusCode).toBe(200);
|
||||
const closed = new Promise<void>((resolve) => stream.once('close', resolve));
|
||||
await adapter.reload(config);
|
||||
await closed;
|
||||
expect((await request()).statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('sends comment heartbeats and releases their timer when the client leaves', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
|
||||
const { adapter, request } = await start();
|
||||
const res = await request();
|
||||
const stream = collect(res);
|
||||
await vi.waitFor(() => expect(stream.frames()).toHaveLength(3));
|
||||
await vi.advanceTimersByTimeAsync(15_000);
|
||||
await vi.waitFor(() => expect(stream.text()).toContain(': ping\n\n'));
|
||||
res.destroy();
|
||||
await vi.waitFor(() => expect(adapter.describeStatus().detail).toContain('SSE 0 个客户端'));
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -10,44 +10,75 @@ import {
|
||||
saveOneBotConfig,
|
||||
} from '../src/config';
|
||||
|
||||
describe('HTTP server WebSocket configuration', () => {
|
||||
let previousCwd: string;
|
||||
let tempDir: string;
|
||||
describe.each(['enableWebSocket', 'enableSse'] as const)(
|
||||
'HTTP server %s configuration',
|
||||
(switchName) => {
|
||||
let previousCwd: string;
|
||||
let tempDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
previousCwd = process.cwd();
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-http-ws-config-'));
|
||||
process.chdir(tempDir);
|
||||
});
|
||||
beforeEach(() => {
|
||||
previousCwd = process.cwd();
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-http-ws-config-'));
|
||||
process.chdir(tempDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('persists the opt-in switch through save and load', () => {
|
||||
const config = makeDefaultOneBotConfig();
|
||||
expect(config.networks.httpServers[0].enableWebSocket).toBe(false);
|
||||
config.networks.httpServers[0].enableWebSocket = true;
|
||||
it('persists the opt-in switch through save and load', () => {
|
||||
const config = makeDefaultOneBotConfig();
|
||||
expect(config.networks.httpServers[0][switchName]).toBe(false);
|
||||
config.networks.httpServers[0][switchName] = true;
|
||||
|
||||
saveOneBotConfig('10001', config);
|
||||
saveOneBotConfig('10001', config);
|
||||
|
||||
const onDisk = JSON.parse(
|
||||
fs.readFileSync(path.join(tempDir, 'config', 'onebot_10001.json'), 'utf8'),
|
||||
) as { networks: { httpServers: Array<{ enableWebSocket?: boolean }> } };
|
||||
expect(onDisk.networks.httpServers[0].enableWebSocket).toBe(true);
|
||||
expect(loadOneBotConfig('10001').networks.httpServers[0].enableWebSocket).toBe(true);
|
||||
});
|
||||
const onDisk = JSON.parse(
|
||||
fs.readFileSync(path.join(tempDir, 'config', 'onebot_10001.json'), 'utf8'),
|
||||
) as {
|
||||
networks: {
|
||||
httpServers: Array<{ enableWebSocket?: boolean; enableSse?: boolean }>;
|
||||
};
|
||||
};
|
||||
expect(onDisk.networks.httpServers[0][switchName]).toBe(true);
|
||||
expect(loadOneBotConfig('10001').networks.httpServers[0][switchName]).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects non-boolean values at public save and restore boundaries', () => {
|
||||
const config = makeDefaultOneBotConfig();
|
||||
(config.networks.httpServers[0] as unknown as Record<string, unknown>).enableWebSocket =
|
||||
'yes';
|
||||
expect(() => assertValidOneBotConfig(config)).toThrow(/enableWebSocket must be a boolean/);
|
||||
it('rejects non-boolean values at public save and restore boundaries', () => {
|
||||
const config = makeDefaultOneBotConfig();
|
||||
(config.networks.httpServers[0] as unknown as Record<string, unknown>)[switchName] =
|
||||
'yes';
|
||||
expect(() => assertValidOneBotConfig(config)).toThrow(
|
||||
`${switchName} must be a boolean`,
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
prepareOneBotConfigForRestore(
|
||||
{
|
||||
expect(() =>
|
||||
prepareOneBotConfigForRestore(
|
||||
{
|
||||
networks: {
|
||||
httpServers: [
|
||||
{
|
||||
name: 'http',
|
||||
host: '127.0.0.1',
|
||||
port: 3000,
|
||||
path: '/',
|
||||
[switchName]: 'yes',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
'per-uin',
|
||||
),
|
||||
).toThrow(`${switchName} must be a boolean`);
|
||||
});
|
||||
|
||||
it('fails fast when a hand-written config contains a non-boolean switch', () => {
|
||||
fs.mkdirSync(path.join(tempDir, 'config'), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(tempDir, 'config', 'onebot_10002.json'),
|
||||
JSON.stringify({
|
||||
mode: 'snapshot',
|
||||
networks: {
|
||||
httpServers: [
|
||||
{
|
||||
@@ -55,40 +86,18 @@ describe('HTTP server WebSocket configuration', () => {
|
||||
host: '127.0.0.1',
|
||||
port: 3000,
|
||||
path: '/',
|
||||
enableWebSocket: 'yes',
|
||||
[switchName]: 'yes',
|
||||
},
|
||||
],
|
||||
httpClients: [],
|
||||
wsServers: [],
|
||||
wsClients: [],
|
||||
},
|
||||
},
|
||||
'per-uin',
|
||||
),
|
||||
).toThrow(/enableWebSocket must be a boolean/);
|
||||
});
|
||||
}),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
it('fails fast when a hand-written config contains a non-boolean switch', () => {
|
||||
fs.mkdirSync(path.join(tempDir, 'config'), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(tempDir, 'config', 'onebot_10002.json'),
|
||||
JSON.stringify({
|
||||
mode: 'snapshot',
|
||||
networks: {
|
||||
httpServers: [
|
||||
{
|
||||
name: 'http',
|
||||
host: '127.0.0.1',
|
||||
port: 3000,
|
||||
path: '/',
|
||||
enableWebSocket: 'yes',
|
||||
},
|
||||
],
|
||||
httpClients: [],
|
||||
wsServers: [],
|
||||
wsClients: [],
|
||||
},
|
||||
}),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
expect(() => loadOneBotConfig('10002')).toThrow(/enableWebSocket must be a boolean/);
|
||||
});
|
||||
});
|
||||
expect(() => loadOneBotConfig('10002')).toThrow(`${switchName} must be a boolean`);
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import type { IncomingMessage, ServerResponse } from 'node:http';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { HttpSseConnections } from '../src/network/http-sse-connections';
|
||||
import { buildDispatchPayload } from '../src/event-filter';
|
||||
|
||||
class Response extends EventEmitter {
|
||||
writableLength = 0;
|
||||
destroyed = false;
|
||||
blocked = false;
|
||||
throwOnWrite = false;
|
||||
readonly frames: string[] = [];
|
||||
writeHead = vi.fn();
|
||||
flushHeaders = vi.fn();
|
||||
write(text: string): boolean {
|
||||
if (this.throwOnWrite) {
|
||||
throw new Error('test write failure');
|
||||
}
|
||||
|
||||
this.frames.push(text);
|
||||
return !this.blocked;
|
||||
}
|
||||
destroy(): void {
|
||||
this.destroyed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
end = vi.fn();
|
||||
}
|
||||
|
||||
describe('SSE bounded buffers', () => {
|
||||
it('pauses until drain, disconnects only the overflowing peer, and bounds replay by bytes', () => {
|
||||
const owner = new HttpSseConnections(
|
||||
{ name: 'bounded', port: 0 },
|
||||
createLogger('SseTest'),
|
||||
() => ['{}'],
|
||||
);
|
||||
const request = {
|
||||
headers: {},
|
||||
socket: { setTimeout: vi.fn() },
|
||||
} as unknown as IncomingMessage;
|
||||
const slow = new Response();
|
||||
const fast = new Response();
|
||||
owner.accept(request, slow as unknown as ServerResponse);
|
||||
owner.accept(request, fast as unknown as ServerResponse);
|
||||
const cursor = /^id: (.+)$/m.exec(fast.frames[1])![1];
|
||||
slow.blocked = true;
|
||||
owner.onEvent(buildDispatchPayload({ index: 1 }));
|
||||
owner.onEvent(buildDispatchPayload({ index: 2 }));
|
||||
expect(slow.frames).toHaveLength(3);
|
||||
slow.blocked = false;
|
||||
slow.emit('drain');
|
||||
expect(slow.frames).toHaveLength(4);
|
||||
slow.blocked = true;
|
||||
owner.onEvent(buildDispatchPayload({ index: 3 }));
|
||||
|
||||
for (let index = 4; index < 8; index += 1) {
|
||||
owner.onEvent(buildDispatchPayload({ index, text: 'x'.repeat(3 * 1024 * 1024) }));
|
||||
}
|
||||
|
||||
expect(slow.destroyed).toBe(true);
|
||||
expect(fast.destroyed).toBe(false);
|
||||
expect(fast.frames.at(-1)).toContain('"index":7');
|
||||
expect(owner.connectionCount).toBe(1);
|
||||
const expired = new Response();
|
||||
owner.accept(
|
||||
{ ...request, headers: { 'last-event-id': cursor } } as IncomingMessage,
|
||||
expired as unknown as ServerResponse,
|
||||
);
|
||||
expect(expired.writeHead).toHaveBeenCalledWith(409, expect.anything());
|
||||
owner.close('test finished');
|
||||
expect(fast.destroyed).toBe(true);
|
||||
expect(owner.connectionCount).toBe(0);
|
||||
});
|
||||
|
||||
it('reports a synchronous write failure and continues serving other clients', () => {
|
||||
const log = createLogger('SseTest');
|
||||
const warning = vi.spyOn(log, 'warn');
|
||||
const owner = new HttpSseConnections({ name: 'errors', port: 0 }, log, () => ['{}']);
|
||||
const request = {
|
||||
headers: {},
|
||||
socket: { setTimeout: vi.fn() },
|
||||
} as unknown as IncomingMessage;
|
||||
const failed = new Response();
|
||||
const healthy = new Response();
|
||||
owner.accept(request, failed as unknown as ServerResponse);
|
||||
owner.accept(request, healthy as unknown as ServerResponse);
|
||||
failed.throwOnWrite = true;
|
||||
owner.onEvent(buildDispatchPayload({ index: 1 }));
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
expect.stringContaining('SSE write failed'),
|
||||
'errors',
|
||||
'test write failure',
|
||||
);
|
||||
expect(failed.destroyed).toBe(true);
|
||||
expect(healthy.frames.at(-1)).toContain('"index":1');
|
||||
owner.close('test finished');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
// The native WebSocket addon is not built in a plain checkout, so the
|
||||
// transport is faked (same pattern as network-bootstrap-meta.test.ts). These
|
||||
// tests pin the config → transport wiring for `maxPayloadBytes`: the value must
|
||||
// reach both WebSocketServer and WebSocket, an unset value must leave the
|
||||
// transport default alone, and changing it must rebind/reconnect because the
|
||||
// cap is fixed when the socket is created.
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { FakeWebSocket, FakeWebSocketServer, clientInstances, clientOptions, servers } = vi.hoisted(
|
||||
() => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const { EventEmitter } = require('node:events') as typeof import('node:events');
|
||||
const clientInstances: FakeWebSocket[] = [];
|
||||
const clientOptions: unknown[] = [];
|
||||
const servers: FakeWebSocketServer[] = [];
|
||||
|
||||
class FakeWebSocket extends EventEmitter {
|
||||
public readyState = 1;
|
||||
constructor(
|
||||
public readonly url = '',
|
||||
options?: unknown,
|
||||
) {
|
||||
super();
|
||||
clientInstances.push(this);
|
||||
clientOptions.push(options);
|
||||
}
|
||||
send(): void {}
|
||||
close(): void {
|
||||
this.readyState = 3;
|
||||
}
|
||||
terminate(): void {
|
||||
this.readyState = 3;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeWebSocketServer extends EventEmitter {
|
||||
public closed = false;
|
||||
constructor(public readonly options?: unknown) {
|
||||
super();
|
||||
servers.push(this);
|
||||
}
|
||||
close(cb?: (error?: Error) => void): void {
|
||||
this.closed = true;
|
||||
cb?.();
|
||||
}
|
||||
}
|
||||
|
||||
return { FakeWebSocket, FakeWebSocketServer, clientInstances, clientOptions, servers };
|
||||
},
|
||||
);
|
||||
|
||||
vi.mock('@snowluma/websocket', () => ({
|
||||
WebSocket: FakeWebSocket,
|
||||
WebSocketServer: FakeWebSocketServer,
|
||||
}));
|
||||
|
||||
import type { NetworkAdapterContext } from '../src/network/adapter';
|
||||
import { HttpServerAdapter } from '../src/network/http-server-adapter';
|
||||
import { WsClientAdapter } from '../src/network/ws-client-adapter';
|
||||
import { WsServerAdapter } from '../src/network/ws-server-adapter';
|
||||
import type { HttpServerNetwork, WsClientNetwork, WsServerNetwork } from '../src/types';
|
||||
|
||||
function ctx(): NetworkAdapterContext {
|
||||
return {
|
||||
uin: '10001',
|
||||
api: { processStreamRequest: async () => {}, isAcceptingActions: true } as never,
|
||||
buildLifecycleEvent: () => ({ post_type: 'meta_event' }),
|
||||
buildHeartbeatEvent: () => ({ post_type: 'meta_event' }),
|
||||
};
|
||||
}
|
||||
|
||||
function serverConfig(over: Partial<WsServerNetwork> = {}): WsServerNetwork {
|
||||
return {
|
||||
name: 'ws-in',
|
||||
enabled: true,
|
||||
host: '127.0.0.1',
|
||||
port: 3001,
|
||||
path: '/',
|
||||
role: 'Universal',
|
||||
accessToken: '',
|
||||
maxPayloadBytes: undefined,
|
||||
...over,
|
||||
} as WsServerNetwork;
|
||||
}
|
||||
|
||||
function clientConfig(over: Partial<WsClientNetwork> = {}): WsClientNetwork {
|
||||
return {
|
||||
name: 'ws-out',
|
||||
enabled: true,
|
||||
url: 'ws://127.0.0.1:6199/ws',
|
||||
role: 'Universal',
|
||||
reconnectIntervalMs: 1000,
|
||||
maxPayloadBytes: undefined,
|
||||
...over,
|
||||
} as WsClientNetwork;
|
||||
}
|
||||
|
||||
async function openServer(adapter: WsServerAdapter): Promise<void> {
|
||||
const opening = adapter.open();
|
||||
servers[servers.length - 1]!.emit('listening');
|
||||
await opening;
|
||||
}
|
||||
|
||||
describe('WsServerAdapter — maxPayloadBytes wiring', () => {
|
||||
beforeEach(() => {
|
||||
servers.length = 0;
|
||||
});
|
||||
|
||||
it('forwards the configured cap to the WebSocketServer', async () => {
|
||||
const adapter = new WsServerAdapter(
|
||||
'ws-in',
|
||||
serverConfig({ maxPayloadBytes: 262_144_000 }),
|
||||
ctx(),
|
||||
);
|
||||
await openServer(adapter);
|
||||
|
||||
expect(servers[0]!.options).toMatchObject({ maxPayload: 262_144_000 });
|
||||
await adapter.close();
|
||||
});
|
||||
|
||||
it('leaves the transport default in place when the cap is unset', async () => {
|
||||
const adapter = new WsServerAdapter('ws-in', serverConfig(), ctx());
|
||||
await openServer(adapter);
|
||||
|
||||
expect((servers[0]!.options as { maxPayload?: number }).maxPayload).toBeUndefined();
|
||||
await adapter.close();
|
||||
});
|
||||
|
||||
it('rebinds when only maxPayloadBytes changes', async () => {
|
||||
const adapter = new WsServerAdapter(
|
||||
'ws-in',
|
||||
serverConfig({ maxPayloadBytes: 1024 }),
|
||||
ctx(),
|
||||
);
|
||||
await openServer(adapter);
|
||||
|
||||
const reloading = adapter.reload(serverConfig({ maxPayloadBytes: 2048 }));
|
||||
await vi.waitFor(() => expect(servers).toHaveLength(2));
|
||||
servers[1]!.emit('listening');
|
||||
expect(await reloading).toBe(1); // NetworkReloadType.Reopened
|
||||
|
||||
expect(servers[1]!.options).toMatchObject({ maxPayload: 2048 });
|
||||
expect(servers[0]!.closed).toBe(true);
|
||||
await adapter.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('WsClientAdapter — maxPayloadBytes wiring', () => {
|
||||
beforeEach(() => {
|
||||
clientInstances.length = 0;
|
||||
clientOptions.length = 0;
|
||||
});
|
||||
|
||||
it('forwards the configured cap to the WebSocket client', () => {
|
||||
const adapter = new WsClientAdapter(
|
||||
'ws-out',
|
||||
clientConfig({ maxPayloadBytes: 524_288_000 }),
|
||||
ctx(),
|
||||
);
|
||||
adapter.open();
|
||||
|
||||
expect(clientOptions[0]).toMatchObject({ maxPayload: 524_288_000 });
|
||||
adapter.forceClose();
|
||||
});
|
||||
|
||||
it('leaves the transport default in place when the cap is unset', () => {
|
||||
const adapter = new WsClientAdapter('ws-out', clientConfig(), ctx());
|
||||
adapter.open();
|
||||
|
||||
expect((clientOptions[0] as { maxPayload?: number }).maxPayload).toBeUndefined();
|
||||
adapter.forceClose();
|
||||
});
|
||||
|
||||
it('reconnects when only maxPayloadBytes changes', async () => {
|
||||
const adapter = new WsClientAdapter(
|
||||
'ws-out',
|
||||
clientConfig({ maxPayloadBytes: 1024 }),
|
||||
ctx(),
|
||||
);
|
||||
adapter.open();
|
||||
const first = clientInstances[0]!;
|
||||
first.emit('open');
|
||||
|
||||
// The old socket's close event fires after the new one exists; the
|
||||
// adapter ignores it (#97), so the reconnect must come from reload().
|
||||
await adapter.reload(clientConfig({ maxPayloadBytes: 4096 }));
|
||||
|
||||
expect(clientInstances).toHaveLength(2);
|
||||
expect(clientOptions[1]).toMatchObject({ maxPayload: 4096 });
|
||||
adapter.forceClose();
|
||||
});
|
||||
});
|
||||
|
||||
// The third place that reads WebSocket frames: the WebSocket server embedded in
|
||||
// an HTTP listener. It has no fake-specific seam beyond the WebSocketServer mock,
|
||||
// so these cases run the real HTTP listener on an ephemeral port.
|
||||
describe('HttpServerAdapter (embedded WebSocket) — maxPayloadBytes wiring', () => {
|
||||
beforeEach(() => {
|
||||
servers.length = 0;
|
||||
});
|
||||
|
||||
function httpConfig(over: Partial<HttpServerNetwork> = {}): HttpServerNetwork {
|
||||
return {
|
||||
name: 'http-in',
|
||||
enabled: true,
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
path: '/',
|
||||
enableWebSocket: true,
|
||||
accessToken: '',
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
maxPayloadBytes: undefined,
|
||||
...over,
|
||||
} as HttpServerNetwork;
|
||||
}
|
||||
|
||||
it('forwards the configured cap to the embedded WebSocketServer', async () => {
|
||||
const adapter = new HttpServerAdapter(
|
||||
'http-in',
|
||||
httpConfig({ maxPayloadBytes: 131_072 }),
|
||||
ctx(),
|
||||
);
|
||||
await adapter.open();
|
||||
|
||||
expect(servers[0]!.options).toMatchObject({ maxPayload: 131_072 });
|
||||
await adapter.close();
|
||||
});
|
||||
|
||||
it('leaves the transport default in place when the cap is unset', async () => {
|
||||
const adapter = new HttpServerAdapter('http-in', httpConfig(), ctx());
|
||||
await adapter.open();
|
||||
|
||||
expect((servers[0]!.options as { maxPayload?: number }).maxPayload).toBeUndefined();
|
||||
await adapter.close();
|
||||
});
|
||||
|
||||
it('rebinds when only maxPayloadBytes changes', async () => {
|
||||
const adapter = new HttpServerAdapter(
|
||||
'http-in',
|
||||
httpConfig({ maxPayloadBytes: 1024 }),
|
||||
ctx(),
|
||||
);
|
||||
await adapter.open();
|
||||
|
||||
const reloading = adapter.reload(httpConfig({ maxPayloadBytes: 2048 }));
|
||||
await vi.waitFor(() => expect(servers).toHaveLength(2));
|
||||
expect(await reloading).toBe(1); // NetworkReloadType.Reopened
|
||||
expect(servers[1]!.options).toMatchObject({ maxPayload: 2048 });
|
||||
await adapter.close();
|
||||
});
|
||||
|
||||
it('does not rebind for a cap change while the adapter has no WebSocket transport', async () => {
|
||||
const adapter = new HttpServerAdapter(
|
||||
'http-in',
|
||||
httpConfig({ enableWebSocket: false, maxPayloadBytes: 1024 }),
|
||||
ctx(),
|
||||
);
|
||||
await adapter.open();
|
||||
expect(servers).toHaveLength(0); // no WS server without the opt-in
|
||||
|
||||
const reloading = adapter.reload(
|
||||
httpConfig({ enableWebSocket: false, maxPayloadBytes: 2048 }),
|
||||
);
|
||||
expect(await reloading).toBe(0); // NetworkReloadType.Normal: listener untouched
|
||||
await adapter.close();
|
||||
});
|
||||
});
|
||||
@@ -5,50 +5,17 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { convertFriendMessage } from '../src/event-converter/to-message';
|
||||
import {
|
||||
hashMessageIdInt32,
|
||||
PRIVATE_MESSAGE_EVENT,
|
||||
PRIVATE_NT_MESSAGE_EVENT,
|
||||
PRIVATE_SENT_MESSAGE_EVENT,
|
||||
} from '../src/message-id';
|
||||
import { MessageStore } from '../src/message-store';
|
||||
import { createMessageIdResolver as productionResolver } from '../src/message-id-resolver';
|
||||
import type { ConverterContext } from '../src/event-converter';
|
||||
import type { FriendMessage } from '@snowluma/protocol/events';
|
||||
|
||||
const SELF_ID = 3961840894;
|
||||
const PEER_ID = 2705892349;
|
||||
|
||||
function productionResolver(store: MessageStore): ConverterContext['messageIdResolver'] {
|
||||
return async (isGroup, sessionId, sequence, eventName, timestamp, replyElements) => {
|
||||
const resolvedEventName = eventName || (isGroup ? 'group_message' : 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,
|
||||
);
|
||||
|
||||
if (storedId !== null) {
|
||||
return storedId;
|
||||
}
|
||||
}
|
||||
|
||||
return hashMessageIdInt32(
|
||||
sequence,
|
||||
sessionId,
|
||||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT
|
||||
? PRIVATE_NT_MESSAGE_EVENT
|
||||
: resolvedEventName,
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
describe('private reply id matches send receipt (#417, #433)', () => {
|
||||
let dir: string;
|
||||
let store: MessageStore;
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { FriendMessage, MessageElement } from '@snowluma/protocol/events';
|
||||
import { convertFriendMessage } from '../src/event-converter/to-message';
|
||||
import { resolveReplyId } from '../src/event-converter/utils';
|
||||
import type { ConverterContext } from '../src/event-converter';
|
||||
import {
|
||||
hashMessageIdInt32,
|
||||
PRIVATE_NT_MESSAGE_EVENT,
|
||||
privateMessageEventName,
|
||||
} from '../src/message-id';
|
||||
import { createMessageIdResolver } from '../src/message-id-resolver';
|
||||
import { MessageStore } from '../src/message-store';
|
||||
import { backfillReplyTarget } from '../src/modules/message-actions';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import { registerEventPipeline } from '../src/event-pipeline';
|
||||
import type { OneBotInstanceContext } from '../src/instance-context';
|
||||
import type { JsonObject } from '../src/types';
|
||||
|
||||
const self = 10001;
|
||||
const peer = 20002;
|
||||
const time = 1_700_000_000;
|
||||
const quoted = [{ type: 'text', text: 'actual quoted text' }] satisfies MessageElement[];
|
||||
|
||||
describe('private quote identity (#618)', () => {
|
||||
let dir: string;
|
||||
let store: MessageStore;
|
||||
let converter: ConverterContext;
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = await fs.mkdtemp(path.join(os.tmpdir(), 'snowluma-quote-'));
|
||||
store = new MessageStore(path.join(dir, 'messages.db'));
|
||||
await store.initialization;
|
||||
converter = {
|
||||
selfId: self,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
messageIdResolver: createMessageIdResolver(store),
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await store.close();
|
||||
await fs.rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function save(
|
||||
sequence: number,
|
||||
clientSequence: number,
|
||||
timestamp: number,
|
||||
text: string,
|
||||
outgoing = true,
|
||||
targetId = peer,
|
||||
): Promise<number> {
|
||||
const id = hashMessageIdInt32(sequence, targetId, PRIVATE_NT_MESSAGE_EVENT);
|
||||
await store.storeMeta(id, {
|
||||
isGroup: false,
|
||||
targetId,
|
||||
sequence,
|
||||
sequenceAuthoritative: true,
|
||||
eventName: PRIVATE_NT_MESSAGE_EVENT,
|
||||
clientSequence,
|
||||
privateDirection: outgoing ? 'outgoing' : 'incoming',
|
||||
timestamp,
|
||||
random: sequence,
|
||||
});
|
||||
await store.storeEvent(id, false, targetId, sequence, PRIVATE_NT_MESSAGE_EVENT, {
|
||||
time: timestamp,
|
||||
post_type: outgoing ? 'message_sent' : 'message',
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
user_id: outgoing ? self : targetId,
|
||||
message: [{ type: 'text', data: { text } }],
|
||||
});
|
||||
return id;
|
||||
}
|
||||
|
||||
function message(replySeq = 444, replyTime = time): FriendMessage {
|
||||
return {
|
||||
kind: 'friend_message',
|
||||
selfUin: self,
|
||||
senderUin: peer,
|
||||
peerUin: peer,
|
||||
senderNick: 'peer',
|
||||
time: time + 2,
|
||||
msgSeq: 900,
|
||||
clientSeq: 900,
|
||||
ntMsgSeq: 9900,
|
||||
sequenceAuthoritative: true,
|
||||
msgId: 55,
|
||||
elements: [
|
||||
{ type: 'reply', replySeq, replyTime, replySenderUin: self, replyElements: quoted },
|
||||
{ type: 'text', text: 'new reply' },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function historyRef(history: FriendMessage[] = []) {
|
||||
const getC2cLatestHistory = vi.fn(async () => history);
|
||||
const ref = {
|
||||
selfId: self,
|
||||
converterCtx: converter,
|
||||
messageStore: store,
|
||||
bridge: {
|
||||
resolveUserUid: vi.fn(async () => 'u_peer'),
|
||||
apis: { message: { getC2cLatestHistory } },
|
||||
},
|
||||
} as unknown as Parameters<typeof backfillReplyTarget>[0];
|
||||
return { ref, getC2cLatestHistory };
|
||||
}
|
||||
|
||||
it.each([-3600, 3600])(
|
||||
'rejects a conversation-sequence match %i seconds away from the quote',
|
||||
async (delta) => {
|
||||
const unrelated = await save(444, 1111, time + delta, 'unrelated text');
|
||||
const target = await save(500, 2222, time, 'actual quoted text');
|
||||
expect(await store.resolvePrivateReplyMessageId(peer, 444, true, time, quoted)).toBe(
|
||||
target,
|
||||
);
|
||||
expect((await store.findEvent(unrelated))?.message).toEqual([
|
||||
{ type: 'text', data: { text: 'unrelated text' } },
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it('does not let an older reused client sequence override the quoted time and text', async () => {
|
||||
await save(100, 444, time - 3600, 'old message');
|
||||
const target = await save(500, 2222, time, 'actual quoted text');
|
||||
expect(await store.resolvePrivateReplyMessageId(peer, 444, true, time, quoted)).toBe(
|
||||
target,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects even a sole same-second candidate when its text contradicts the quote', async () => {
|
||||
await save(300, 3333, time, 'different text');
|
||||
expect(await store.resolvePrivateReplyMessageId(peer, 9999, true, time, quoted)).toBeNull();
|
||||
});
|
||||
|
||||
it('does not prefer one sequence namespace when both identify different compatible messages', async () => {
|
||||
await save(100, 444, time, 'same');
|
||||
await save(444, 2222, time, 'same');
|
||||
expect(await store.resolvePrivateReplyMessageId(peer, 444, true, time)).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps reused sequences ambiguous when the quote has no usable timestamp', async () => {
|
||||
await save(100, 444, time - 3600, 'old');
|
||||
await save(500, 444, time, 'new');
|
||||
expect(await store.resolvePrivateReplyMessageId(peer, 444, true)).toBeNull();
|
||||
});
|
||||
|
||||
it('uses quoted content to check a nearby-time candidate too', async () => {
|
||||
await save(300, 3333, time - 2, 'different text');
|
||||
expect(await store.resolvePrivateReplyMessageId(peer, 9999, true, time, quoted)).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps peer and sender direction isolated when matching by time', async () => {
|
||||
await save(300, 444, time, 'actual quoted text', false);
|
||||
await save(300, 444, time, 'actual quoted text', true, 30003);
|
||||
expect(await store.resolvePrivateReplyMessageId(peer, 444, true, time, quoted)).toBeNull();
|
||||
});
|
||||
|
||||
it('preserves an explicitly unresolved quote instead of using its raw sequence', async () => {
|
||||
expect(await resolveReplyId(false, peer, 8888, () => 0)).toBe(0);
|
||||
});
|
||||
|
||||
it('omits an unresolved reply identifier while retaining the live message and its stable id', async () => {
|
||||
const json = await convertFriendMessage(converter, message());
|
||||
expect(json.message_id).toBe(hashMessageIdInt32(9900, peer, PRIVATE_NT_MESSAGE_EVENT));
|
||||
expect(json.message).toEqual([{ type: 'text', data: { text: 'new reply' } }]);
|
||||
});
|
||||
|
||||
it('uses the canonical history id after backfill instead of a hash of the quote sequence', async () => {
|
||||
const fetched: FriendMessage = {
|
||||
kind: 'friend_message',
|
||||
selfUin: self,
|
||||
senderUin: self,
|
||||
peerUin: peer,
|
||||
senderNick: 'self',
|
||||
time,
|
||||
msgSeq: 444,
|
||||
clientSeq: 444,
|
||||
ntMsgSeq: 500,
|
||||
sequenceAuthoritative: true,
|
||||
msgId: 77,
|
||||
elements: quoted,
|
||||
};
|
||||
const { ref, getC2cLatestHistory } = historyRef([fetched]);
|
||||
const event = message();
|
||||
const prepared = await backfillReplyTarget(ref, event);
|
||||
const json = await convertFriendMessage(converter, prepared as FriendMessage);
|
||||
const target = hashMessageIdInt32(500, peer, PRIVATE_NT_MESSAGE_EVENT);
|
||||
expect(getC2cLatestHistory).toHaveBeenCalledExactlyOnceWith('u_peer', 20, self, time + 1);
|
||||
expect(json.message).toEqual([
|
||||
{ type: 'reply', data: { id: String(target) } },
|
||||
{ type: 'text', data: { text: 'new reply' } },
|
||||
]);
|
||||
expect((await store.findEvent(target))?.message_id).toBe(target);
|
||||
expect(
|
||||
await store.findEvent(hashMessageIdInt32(444, peer, PRIVATE_NT_MESSAGE_EVENT)),
|
||||
).toBeNull();
|
||||
expect(event.elements[0]).not.toHaveProperty('replyMessageId');
|
||||
});
|
||||
|
||||
it('does not store an invented private message when history cannot identify the target', async () => {
|
||||
const { ref } = historyRef();
|
||||
const event = message();
|
||||
const prepared = await backfillReplyTarget(ref, event);
|
||||
const json = await convertFriendMessage(converter, prepared as FriendMessage);
|
||||
expect(json.message).toEqual([{ type: 'text', data: { text: 'new reply' } }]);
|
||||
expect(
|
||||
await store.findEvent(hashMessageIdInt32(444, peer, PRIVATE_NT_MESSAGE_EVENT)),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ hasContent: true, ntMsgSeq: 9900 },
|
||||
{ hasContent: false, ntMsgSeq: 9900 },
|
||||
{ hasContent: true, ntMsgSeq: 0 },
|
||||
{ hasContent: false, ntMsgSeq: 0 },
|
||||
])(
|
||||
'never resolves a same-second self-sent reply to itself: %j',
|
||||
async ({ hasContent, ntMsgSeq }) => {
|
||||
const event = { ...message(9999), senderUin: self, time, ntMsgSeq };
|
||||
|
||||
if (!hasContent && event.elements[0]?.type === 'reply') {
|
||||
event.elements[0].replyElements = undefined;
|
||||
}
|
||||
|
||||
const eventName = privateMessageEventName(true, ntMsgSeq > 0);
|
||||
const currentId = hashMessageIdInt32(ntMsgSeq || event.msgSeq, peer, eventName);
|
||||
await store.storeMeta(currentId, {
|
||||
isGroup: false,
|
||||
targetId: peer,
|
||||
sequence: event.ntMsgSeq!,
|
||||
sequenceAuthoritative: ntMsgSeq > 0,
|
||||
clientSequence: event.clientSeq!,
|
||||
eventName,
|
||||
privateDirection: 'outgoing',
|
||||
random: event.msgId,
|
||||
timestamp: time,
|
||||
});
|
||||
const directlyConverted = await convertFriendMessage(converter, event);
|
||||
expect(directlyConverted.message).toEqual([
|
||||
{ type: 'text', data: { text: 'new reply' } },
|
||||
]);
|
||||
const { ref } = historyRef([event]);
|
||||
const prepared = await backfillReplyTarget(ref, event);
|
||||
const json = await convertFriendMessage(converter, prepared as FriendMessage);
|
||||
expect(json.message).toEqual([{ type: 'text', data: { text: 'new reply' } }]);
|
||||
expect(await store.findEvent(currentId)).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it('does not use a bodyless time-only candidate to confirm known quoted content', async () => {
|
||||
await store.storeMeta(-55, {
|
||||
isGroup: false,
|
||||
targetId: peer,
|
||||
sequence: 300,
|
||||
sequenceAuthoritative: true,
|
||||
clientSequence: 100,
|
||||
eventName: PRIVATE_NT_MESSAGE_EVENT,
|
||||
privateDirection: 'outgoing',
|
||||
random: 1,
|
||||
timestamp: time,
|
||||
});
|
||||
expect(await store.resolvePrivateReplyMessageId(peer, 444, true, time, quoted)).toBeNull();
|
||||
});
|
||||
|
||||
it('does not fetch history for an already verified cached target', async () => {
|
||||
const target = await save(500, 444, time, 'actual quoted text');
|
||||
const { ref, getC2cLatestHistory } = historyRef();
|
||||
const prepared = await backfillReplyTarget(ref, message());
|
||||
const json = await convertFriendMessage(converter, prepared as FriendMessage);
|
||||
expect((json.message as JsonObject[])[0]).toEqual({
|
||||
type: 'reply',
|
||||
data: { id: String(target) },
|
||||
});
|
||||
expect(getC2cLatestHistory).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keys outgoing history without a peer field under the requested conversation', async () => {
|
||||
const fetched: FriendMessage = {
|
||||
...message(),
|
||||
peerUin: undefined,
|
||||
senderUin: self,
|
||||
time,
|
||||
msgSeq: 444,
|
||||
clientSeq: 444,
|
||||
ntMsgSeq: 500,
|
||||
elements: quoted,
|
||||
};
|
||||
const { ref } = historyRef([fetched]);
|
||||
const prepared = await backfillReplyTarget(ref, message());
|
||||
const json = await convertFriendMessage(converter, prepared as FriendMessage);
|
||||
const target = hashMessageIdInt32(500, peer, PRIVATE_NT_MESSAGE_EVENT);
|
||||
expect((json.message as JsonObject[])[0]).toEqual({
|
||||
type: 'reply',
|
||||
data: { id: String(target) },
|
||||
});
|
||||
expect((await store.findEvent(target))?.target_id).toBe(peer);
|
||||
expect(
|
||||
await store.findEvent(hashMessageIdInt32(500, self, PRIVATE_NT_MESSAGE_EVENT)),
|
||||
).toBeNull();
|
||||
expect(fetched.peerUin).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ senderUin: peer },
|
||||
{ peerUin: 30003 },
|
||||
{ selfUin: 30003 },
|
||||
{ elements: [{ type: 'text', text: 'different text' }] satisfies MessageElement[] },
|
||||
{ time: time - 3600 },
|
||||
])('rejects incompatible server history: %j', async (override) => {
|
||||
const fetched: FriendMessage = {
|
||||
...message(),
|
||||
senderUin: self,
|
||||
time,
|
||||
msgSeq: 444,
|
||||
clientSeq: 444,
|
||||
ntMsgSeq: 500,
|
||||
elements: quoted,
|
||||
...override,
|
||||
};
|
||||
const { ref } = historyRef([fetched]);
|
||||
const prepared = await backfillReplyTarget(ref, message());
|
||||
const json = await convertFriendMessage(converter, prepared as FriendMessage);
|
||||
expect(json.message).toEqual([{ type: 'text', data: { text: 'new reply' } }]);
|
||||
expect(
|
||||
await store.findEvent(hashMessageIdInt32(500, peer, PRIVATE_NT_MESSAGE_EVENT)),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('does not restore or reference a recalled target returned by server history', async () => {
|
||||
await store.recordPrivateRecall(peer, 444, true, time + 1);
|
||||
const fetched: FriendMessage = {
|
||||
...message(),
|
||||
senderUin: self,
|
||||
time,
|
||||
msgSeq: 444,
|
||||
clientSeq: 444,
|
||||
ntMsgSeq: 500,
|
||||
elements: quoted,
|
||||
};
|
||||
const { ref } = historyRef([fetched]);
|
||||
const prepared = await backfillReplyTarget(ref, message());
|
||||
const json = await convertFriendMessage(converter, prepared as FriendMessage);
|
||||
expect(json.message).toEqual([{ type: 'text', data: { text: 'new reply' } }]);
|
||||
expect(
|
||||
await store.findEvent(hashMessageIdInt32(500, peer, PRIVATE_NT_MESSAGE_EVENT)),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('preserves the live message on a history fetch failure without inventing a target', async () => {
|
||||
const { ref, getC2cLatestHistory } = historyRef();
|
||||
getC2cLatestHistory.mockRejectedValueOnce(new Error('isolated history transport failure'));
|
||||
const prepared = await backfillReplyTarget(ref, message());
|
||||
const json = await convertFriendMessage(converter, prepared as FriendMessage);
|
||||
expect(json.message).toEqual([{ type: 'text', data: { text: 'new reply' } }]);
|
||||
expect(getC2cLatestHistory).toHaveBeenCalledOnce();
|
||||
expect(await store.listSessionEvents(false, peer)).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps a verified legacy negative id when filling its missing body from quoted content', async () => {
|
||||
const target = -12345;
|
||||
await store.storeMeta(target, {
|
||||
isGroup: false,
|
||||
targetId: peer,
|
||||
sequence: 500,
|
||||
sequenceAuthoritative: true,
|
||||
clientSequence: 444,
|
||||
eventName: PRIVATE_NT_MESSAGE_EVENT,
|
||||
privateDirection: 'outgoing',
|
||||
random: 7,
|
||||
timestamp: time,
|
||||
});
|
||||
const { ref } = historyRef();
|
||||
const prepared = await backfillReplyTarget(ref, message());
|
||||
const json = await convertFriendMessage(converter, prepared as FriendMessage);
|
||||
expect((json.message as JsonObject[])[0]).toEqual({
|
||||
type: 'reply',
|
||||
data: { id: String(target) },
|
||||
});
|
||||
expect((await store.findEvent(target))?.message).toEqual([
|
||||
{ type: 'text', data: { text: 'actual quoted text' } },
|
||||
]);
|
||||
});
|
||||
|
||||
it('does not overwrite an old identity when history reuses its client sequence with a different server sequence', async () => {
|
||||
const oldId = -12345;
|
||||
await store.storeMeta(oldId, {
|
||||
isGroup: false,
|
||||
targetId: peer,
|
||||
sequence: 499,
|
||||
sequenceAuthoritative: true,
|
||||
clientSequence: 444,
|
||||
eventName: PRIVATE_NT_MESSAGE_EVENT,
|
||||
privateDirection: 'outgoing',
|
||||
random: 7,
|
||||
timestamp: time - 1,
|
||||
});
|
||||
const fetched: FriendMessage = {
|
||||
...message(),
|
||||
senderUin: self,
|
||||
time,
|
||||
msgSeq: 444,
|
||||
clientSeq: 444,
|
||||
ntMsgSeq: 500,
|
||||
elements: quoted,
|
||||
};
|
||||
const { ref } = historyRef([fetched]);
|
||||
const prepared = await backfillReplyTarget(ref, message());
|
||||
const json = await convertFriendMessage(converter, prepared as FriendMessage);
|
||||
const target = hashMessageIdInt32(500, peer, PRIVATE_NT_MESSAGE_EVENT);
|
||||
expect((json.message as JsonObject[])[0]).toEqual({
|
||||
type: 'reply',
|
||||
data: { id: String(target) },
|
||||
});
|
||||
expect(await store.findEvent(oldId)).toBeNull();
|
||||
expect((await store.findMeta(oldId))?.sequence).toBe(499);
|
||||
expect((await store.findEvent(target))?.message_id).toBe(target);
|
||||
});
|
||||
|
||||
it('dispatches only after canonical backfill is available to an immediate get_msg', async () => {
|
||||
const fetched: FriendMessage = {
|
||||
...message(),
|
||||
senderUin: self,
|
||||
time,
|
||||
msgSeq: 444,
|
||||
clientSeq: 444,
|
||||
ntMsgSeq: 500,
|
||||
elements: quoted,
|
||||
};
|
||||
const { ref } = historyRef([fetched]);
|
||||
const bus = new BridgeEventBus();
|
||||
const dispatched: JsonObject[] = [];
|
||||
const targets: Array<JsonObject | null> = [];
|
||||
const ctx = {
|
||||
...ref,
|
||||
uin: String(self),
|
||||
bridge: { ...ref.bridge, events: bus },
|
||||
cacheMessageMeta: store.storeMeta.bind(store),
|
||||
dispatchEvent: async (json: JsonObject) => {
|
||||
dispatched.push(json);
|
||||
const reply = (json.message as JsonObject[]).find(
|
||||
(segment) => segment.type === 'reply',
|
||||
);
|
||||
targets.push(await store.findEvent(Number((reply?.data as JsonObject)?.id)));
|
||||
},
|
||||
} as unknown as OneBotInstanceContext;
|
||||
const handle = registerEventPipeline(ctx);
|
||||
|
||||
try {
|
||||
await bus.emit(message());
|
||||
expect(dispatched).toHaveLength(1);
|
||||
const target = hashMessageIdInt32(500, peer, PRIVATE_NT_MESSAGE_EVENT);
|
||||
expect((dispatched[0]!.message as JsonObject[])[0]).toEqual({
|
||||
type: 'reply',
|
||||
data: { id: String(target) },
|
||||
});
|
||||
expect(targets[0]?.message_id).toBe(target);
|
||||
} finally {
|
||||
handle.stop();
|
||||
await handle.drain();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -40,6 +40,13 @@ const cases: {
|
||||
args: [10001, 'cursor'],
|
||||
readOnly: true,
|
||||
},
|
||||
{
|
||||
action: 'get_qzone_feed_detail',
|
||||
method: 'getFeedDetail',
|
||||
params: { tid: '1127000000f1536501000000' },
|
||||
args: ['1127000000f1536501000000'],
|
||||
readOnly: true,
|
||||
},
|
||||
{
|
||||
action: 'get_qzone_share_ark',
|
||||
method: 'getShareArk',
|
||||
@@ -317,6 +324,13 @@ describe('qzone public actions', () => {
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ action: 'get_qzone_feed_detail', params: {} },
|
||||
{ action: 'get_qzone_feed_detail', params: { tid: '' } },
|
||||
{ action: 'get_qzone_feed_detail', params: { tid: 'T1' } },
|
||||
{ action: 'get_qzone_feed_detail', params: { tid: [] } },
|
||||
{ action: 'get_qzone_feed_detail', params: { tid: 'g'.repeat(24) } },
|
||||
{ action: 'get_qzone_feed_detail', params: { tid: 'a'.repeat(25) } },
|
||||
{ action: 'get_qzone_feed_detail', params: { tid: '1127000000f1536501000000\n' } },
|
||||
{ action: 'get_qzone_public_feeds', params: { cursor: '' } },
|
||||
{ action: 'get_qzone_public_feeds', params: { cursor: 'a'.repeat(65537) } },
|
||||
{ action: 'get_qzone_public_feed_detail', params: {} },
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { actionParams } from '../../sdk/tests/fixtures/action-contracts';
|
||||
import { actions as extended } from '../src/actions/extended';
|
||||
import { actions as friend } from '../src/actions/friend';
|
||||
import { actions as albums } from '../src/actions/group-album';
|
||||
import { actions as groupAdmin } from '../src/actions/group-admin';
|
||||
import { actions as qzone } from '../src/actions/qzone';
|
||||
@@ -9,6 +10,7 @@ import { actions as streamDownload } from '../src/actions/stream-download';
|
||||
import { actions as streamFile } from '../src/actions/stream-file';
|
||||
|
||||
const actions = [
|
||||
...friend,
|
||||
...extended,
|
||||
...albums,
|
||||
...groupAdmin,
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { Readable } from 'node:stream';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
createReverseWebSocketServer,
|
||||
type SnowLumaReverseWebSocketServer,
|
||||
} from '../../sdk/src/node/index';
|
||||
import { WsClientAdapter } from '../src/network/ws-client-adapter';
|
||||
import { buildDispatchPayload } from '../src/event-filter';
|
||||
import { okResponse, type JsonObject, type WsRole } from '../src/types';
|
||||
import type { ApiActionContext } from '../src/api-handler';
|
||||
import { actions as uploadActions, __test as uploadTest } from '../src/actions/stream-file';
|
||||
import { actions as downloadActions } from '../src/actions/stream-download';
|
||||
import { createCompiledTestHandler, testAction } from './helpers/compiled-action-handler';
|
||||
|
||||
describe('SDK reverse server against the real OneBot reverse adapter', () => {
|
||||
const adapters: WsClientAdapter[] = [];
|
||||
let server: SnowLumaReverseWebSocketServer | undefined;
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(adapters.splice(0).map((adapter) => adapter.close()));
|
||||
await server?.close();
|
||||
|
||||
for (const key of uploadTest.uploads.keys()) {
|
||||
uploadTest.cleanupUpload(key, true);
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['universal', 'split'] as const)(
|
||||
'%s carries events, actions and complete binary streams',
|
||||
async (mode) => {
|
||||
server = createReverseWebSocketServer({
|
||||
port: 0,
|
||||
accessToken: 'integration-test',
|
||||
selfIds: ['10001'],
|
||||
});
|
||||
const errors = vi.fn();
|
||||
server.on('error', errors);
|
||||
await server.listen();
|
||||
const { port } = server.address as AddressInfo;
|
||||
const api = createCompiledTestHandler({} as ApiActionContext, [
|
||||
...uploadActions,
|
||||
...downloadActions,
|
||||
testAction('sdk_ping', () => okResponse({ pong: true })),
|
||||
]);
|
||||
const roles: WsRole[] = mode === 'universal' ? ['Universal'] : ['Api', 'Event'];
|
||||
|
||||
for (const role of roles) {
|
||||
const adapter = new WsClientAdapter(
|
||||
`reverse-${role}`,
|
||||
{
|
||||
name: `reverse-${role}`,
|
||||
url: `ws://127.0.0.1:${port}/onebot/v11/ws`,
|
||||
accessToken: 'integration-test',
|
||||
role,
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
},
|
||||
{
|
||||
uin: '10001',
|
||||
api,
|
||||
buildLifecycleEvent: (subType) => ({
|
||||
self_id: 10001,
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'lifecycle',
|
||||
sub_type: subType,
|
||||
}),
|
||||
buildHeartbeatEvent: () => ({
|
||||
self_id: 10001,
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'heartbeat',
|
||||
}),
|
||||
},
|
||||
);
|
||||
adapters.push(adapter);
|
||||
adapter.open();
|
||||
}
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(server!.getClient('10001')?.canCallActions).toBe(true);
|
||||
expect(server!.getClient('10001')?.canReceiveEvents).toBe(true);
|
||||
expect(adapters.every((adapter) => adapter.describeStatus().status === 'ok')).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
const client = server.getClient('10001')!;
|
||||
expect(await client.raw('sdk_ping')).toEqual({ pong: true });
|
||||
const seen = vi.fn();
|
||||
client.on('event', seen);
|
||||
const received = client.waitForMessage((event) => event.message_id === -42, {
|
||||
timeoutMs: 1000,
|
||||
});
|
||||
const event: JsonObject = {
|
||||
self_id: 10001,
|
||||
time: 1,
|
||||
post_type: 'message',
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
user_id: 20001,
|
||||
message_id: -42,
|
||||
message: [{ type: 'text', data: { text: 'wire test' } }],
|
||||
raw_message: 'wire test',
|
||||
};
|
||||
|
||||
for (const adapter of adapters) {
|
||||
const own = { ...event, post_type: 'message_sent' };
|
||||
adapter.onEvent(own, buildDispatchPayload(own));
|
||||
adapter.onEvent(event, buildDispatchPayload(event));
|
||||
}
|
||||
|
||||
expect((await received).message_id).toBe(-42);
|
||||
expect(seen.mock.calls.some(([event]) => event.post_type === 'message_sent')).toBe(
|
||||
false,
|
||||
);
|
||||
const bytes = Buffer.from('reverse transport binary stream\n'.repeat(3000));
|
||||
const sha256 = createHash('sha256').update(bytes).digest('hex');
|
||||
const uploaded = await client.uploadFileStream(Readable.from([bytes]), {
|
||||
fileSize: bytes.length,
|
||||
chunkSize: 8192,
|
||||
filename: 'reverse.bin',
|
||||
expectedSha256: sha256,
|
||||
fileRetention: 0,
|
||||
});
|
||||
const chunks: Uint8Array[] = [];
|
||||
const stream = client.downloadFileStream({
|
||||
file: uploaded.file_path,
|
||||
chunk_size: 4096,
|
||||
});
|
||||
|
||||
while (true) {
|
||||
const next = await stream.next();
|
||||
|
||||
if (next.done) {
|
||||
expect(next.value.total_bytes).toBe(bytes.length);
|
||||
break;
|
||||
}
|
||||
|
||||
chunks.push(next.value);
|
||||
}
|
||||
|
||||
expect(Buffer.concat(chunks)).toEqual(bytes);
|
||||
expect(errors).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/proto-defs",
|
||||
"version": "2.3.1",
|
||||
"version": "2.3.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",
|
||||
@@ -20,6 +20,10 @@
|
||||
"types": "./src/collection.ts",
|
||||
"default": "./src/collection.ts"
|
||||
},
|
||||
"./qzone": {
|
||||
"types": "./src/qzone.ts",
|
||||
"default": "./src/qzone.ts"
|
||||
},
|
||||
"./dataline": {
|
||||
"types": "./src/dataline.ts",
|
||||
"default": "./src/dataline.ts"
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
|
||||
export type * from './action.js';
|
||||
export type * from './collection.js';
|
||||
export type * from './qzone.js';
|
||||
export type * from './element.js';
|
||||
// NOTE: `highway.ts` intentionally NOT re-exported here — see note above.
|
||||
export type * from './longmsg.js';
|
||||
|
||||
@@ -277,6 +277,26 @@ export interface OidbUserInfoResponseBody {
|
||||
export interface OidbUserInfoResponse {
|
||||
body?: pb<1, OidbUserInfoResponseBody>;
|
||||
}
|
||||
|
||||
// Profile property 107 contains separate opened and closed privilege lists.
|
||||
// The two icon URLs are independent fields, not a oneof.
|
||||
export interface OidbProfilePrivilege {
|
||||
type?: pb<1, int_32>;
|
||||
level?: pb<4, int_32>;
|
||||
flag?: pb<5, int_32>;
|
||||
iconUrl?: pb<6, bytes>;
|
||||
deluxeIconUrl?: pb<7, bytes>;
|
||||
jumpUrl?: pb<8, bytes>;
|
||||
isBig?: pb<9, int_32>;
|
||||
}
|
||||
export interface OidbProfilePrivilegeLists {
|
||||
jumpUrl?: pb<2, bytes>;
|
||||
open?: pb_repeated<3, OidbProfilePrivilege>;
|
||||
closed?: pb_repeated<4, OidbProfilePrivilege>;
|
||||
}
|
||||
export interface OidbProfilePrivileges {
|
||||
lists?: pb<3, OidbProfilePrivilegeLists>;
|
||||
}
|
||||
export interface AvatarInfo {
|
||||
url?: pb<5, string>;
|
||||
}
|
||||
|
||||
@@ -32,10 +32,16 @@ export interface OidbEmpty {}
|
||||
// Oidb.0xFD4_1 Friend list
|
||||
export interface OidbFriendProperty {
|
||||
code?: pb<1, uint_32>;
|
||||
value?: pb<2, string>;
|
||||
value?: pb<2, bytes>;
|
||||
}
|
||||
|
||||
export interface OidbFriendNumberProperty {
|
||||
key?: pb<1, uint_32>;
|
||||
value?: pb<2, int_32>;
|
||||
}
|
||||
|
||||
export interface OidbFriendLayer1 {
|
||||
numberProperties?: pb_repeated<1, OidbFriendNumberProperty>;
|
||||
properties?: pb_repeated<2, OidbFriendProperty>;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { int_64, pb, pb_optional } from '@snowluma/proton';
|
||||
|
||||
/** Personal-space emotion identity carried in GetFeedDetail's base64 ugc_id. */
|
||||
export interface QzoneEmotionUgcId {
|
||||
appId: pb<1, int_64>;
|
||||
uin: pb<2, int_64>;
|
||||
publishTime: pb<3, int_64>;
|
||||
// These empty fields have explicit presence in the upstream identifier.
|
||||
field4: pb_optional<4, string>;
|
||||
field5: pb_optional<5, string>;
|
||||
field6: pb<6, string>;
|
||||
tid: pb<8, string>;
|
||||
}
|
||||
@@ -35,3 +35,26 @@ excluding cached uploads, before drawing performance conclusions.
|
||||
Regression tests use isolated transports and cover concurrency bounds,
|
||||
out-of-order acknowledgements, a stalled early chunk, retry exhaustion, backpressure
|
||||
and cleanup. They do not establish real QQ delivery or upload throughput.
|
||||
|
||||
## Media download limits
|
||||
|
||||
Two deployment-wide knobs bound HTTP media downloads in `highway/utils.ts`. They are
|
||||
environment variables rather than per-account OneBot settings because every caller
|
||||
reaches the same download engine (`loadBinarySource` / `stageSourceToDisk`):
|
||||
|
||||
```sh
|
||||
# One HTTP attempt, in milliseconds. Default 60000.
|
||||
SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS=180000
|
||||
# Cap on one binary source buffered in memory, in bytes. Default 1073741824 (1 GiB).
|
||||
SNOWLUMA_MAX_BINARY_DOWNLOAD_BYTES=2147483648
|
||||
```
|
||||
|
||||
Both default to their previous hardcoded values, so an unconfigured deployment
|
||||
behaves exactly as before. Invalid values are logged and ignored, falling back to the
|
||||
default. Callers that already pass an explicit ceiling keep it: group/private files
|
||||
and flash transfer still use 4 GiB, and inline `base64://` / `data:` flash sources
|
||||
keep the 1 GiB buffered-load ceiling.
|
||||
|
||||
`SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS` is not related to
|
||||
`SNOWLUMA_DOWNLOAD_FILE_TIMEOUT_MS` (used by the `download_file` OneBot action): the
|
||||
former bounds highway media downloads, the latter the action's own file staging.
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/protocol",
|
||||
"version": "2.3.1",
|
||||
"version": "2.3.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
|
||||
/** Default timeout for one HTTP media download attempt (ms). */
|
||||
export const DEFAULT_HTTP_DOWNLOAD_TIMEOUT_MS = 60_000;
|
||||
|
||||
/** Default cap on one binary load that is buffered in memory (bytes). */
|
||||
export const DEFAULT_MAX_BINARY_DOWNLOAD_BYTES = 1024 * 1024 * 1024;
|
||||
|
||||
/** Node's timer ceiling; a larger value would be silently clamped anyway. */
|
||||
const MAX_TIMER_MS = 2_147_483_647;
|
||||
|
||||
/**
|
||||
* Deliberate ceiling for the configurable cap. It is not a Node limit (Node 24
|
||||
* reports `buffer.constants.MAX_LENGTH` as `Number.MAX_SAFE_INTEGER`); buffering a
|
||||
* single download larger than this is not a realistic media source and would
|
||||
* exhaust the process long before it completes.
|
||||
*/
|
||||
const MAX_BINARY_DOWNLOAD_BYTES = 4 * 1024 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Timeout for one HTTP media download attempt.
|
||||
*
|
||||
* Deployment-wide rather than per-adapter because every caller reaches this
|
||||
* through the same download engine (`loadBinarySource` / `stageSourceToDisk`),
|
||||
* and it is configured the same way as the other transport timeouts
|
||||
* (`SNOWLUMA_PACKET_TIMEOUT_MS`, `SNOWLUMA_HOOK_ACK_TIMEOUT_MS`) instead of
|
||||
* growing the per-account OneBot config surface.
|
||||
*
|
||||
* The 60 s default is generous for images but tight for a large media file over
|
||||
* a slow link, where the abort is reported as a generic fetch failure.
|
||||
*
|
||||
* Not to be confused with `SNOWLUMA_DOWNLOAD_FILE_TIMEOUT_MS`, which bounds the
|
||||
* `download_file` OneBot action's own staging.
|
||||
*/
|
||||
export function httpDownloadTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {
|
||||
return positiveIntEnv('SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS', DEFAULT_HTTP_DOWNLOAD_TIMEOUT_MS, {
|
||||
env,
|
||||
max: MAX_TIMER_MS,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Cap on one binary source loaded fully into memory.
|
||||
*
|
||||
* Applies to the helpers whose size bound is implicit (image, voice, avatar,
|
||||
* custom face, group-notice image). Callers that pass their own ceiling — group
|
||||
* files, flash transfer, video — keep it, so raising this never lifts those.
|
||||
*/
|
||||
export function maxBinaryDownloadBytes(env: NodeJS.ProcessEnv = process.env): number {
|
||||
return positiveIntEnv('SNOWLUMA_MAX_BINARY_DOWNLOAD_BYTES', DEFAULT_MAX_BINARY_DOWNLOAD_BYTES, {
|
||||
env,
|
||||
max: MAX_BINARY_DOWNLOAD_BYTES,
|
||||
});
|
||||
}
|
||||
@@ -2,6 +2,11 @@ import { createHash } from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import {
|
||||
DEFAULT_MAX_BINARY_DOWNLOAD_BYTES,
|
||||
httpDownloadTimeoutMs,
|
||||
maxBinaryDownloadBytes,
|
||||
} from './download-settings';
|
||||
|
||||
export interface LoadedBinary {
|
||||
bytes: Uint8Array;
|
||||
@@ -16,8 +21,12 @@ export interface LoadedBinary {
|
||||
* directly and enforces its own cap via `MAX_VIDEO_SIZE`. Group/private
|
||||
* file uploads override this via `FILE_UPLOAD_MAX_BYTES` because QQ's
|
||||
* file protocol legitimately supports up to 4 GiB.
|
||||
*
|
||||
* The effective default is `SNOWLUMA_MAX_BINARY_DOWNLOAD_BYTES` (see
|
||||
* `download-settings`); this constant is the documented 1 GiB floor reused by
|
||||
* the static flash-transfer ceiling below.
|
||||
*/
|
||||
const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB
|
||||
const DEFAULT_MAX_BINARY_SIZE = DEFAULT_MAX_BINARY_DOWNLOAD_BYTES;
|
||||
/** Hard ceiling QQ's file protocol supports — used by group/private files. */
|
||||
export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
|
||||
/** Local / HTTP flash sources. Official fileset max is unknown; reuse the
|
||||
@@ -27,7 +36,6 @@ export const FLASH_TRANSFER_MAX_BYTES = FILE_UPLOAD_MAX_BYTES;
|
||||
/** Inline `base64://` / `data:` flash sources still decode into RAM inside
|
||||
* `stageSourceToDisk`, so they keep the 1 GiB buffered-load ceiling. */
|
||||
export const FLASH_TRANSFER_INLINE_MAX_BYTES = DEFAULT_MAX_BINARY_SIZE;
|
||||
const FETCH_TIMEOUT_MS = 60_000;
|
||||
|
||||
/**
|
||||
* Browser-like User-Agent for remote media downloads. Many image / CDN
|
||||
@@ -152,11 +160,11 @@ export interface DownloadSink<T> {
|
||||
/**
|
||||
* Shared HTTP download engine for both the buffered and the disk-streaming
|
||||
* paths — the single owner of the observable download behavior: browser UA +
|
||||
* Accept, redirect follow, 60s timeout, incremental `maxBytes` enforcement
|
||||
* (declared Content-Length AND streamed total, `noRetry`-tagged), and one
|
||||
* Referer retry on a non-size failure. Bytes are delivered chunk-by-chunk to a
|
||||
* caller-provided sink so the same length-checking transport feeds either RAM
|
||||
* or disk.
|
||||
* Accept, redirect follow, the configurable download timeout, incremental
|
||||
* `maxBytes` enforcement (declared Content-Length AND streamed total,
|
||||
* `noRetry`-tagged), and one Referer retry on a non-size failure. Bytes are
|
||||
* delivered chunk-by-chunk to a caller-provided sink so the same
|
||||
* length-checking transport feeds either RAM or disk.
|
||||
*/
|
||||
export async function downloadHttp<T>(
|
||||
source: string,
|
||||
@@ -170,7 +178,7 @@ export async function downloadHttp<T>(
|
||||
const resp = await fetch(source, {
|
||||
headers,
|
||||
redirect: 'follow',
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
signal: AbortSignal.timeout(httpDownloadTimeoutMs()),
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
@@ -261,7 +269,7 @@ export async function downloadHttp<T>(
|
||||
export async function loadBinarySource(
|
||||
source: string,
|
||||
resourceName: string,
|
||||
maxBytes: number = DEFAULT_MAX_BINARY_SIZE,
|
||||
maxBytes: number = maxBinaryDownloadBytes(),
|
||||
): Promise<LoadedBinary> {
|
||||
if (!source) {
|
||||
throw new Error(`${resourceName} source is empty`);
|
||||
|
||||
@@ -14,6 +14,7 @@ import type { OidbFriendListRequest } from '@snowluma/proto-defs/oidb-actions/ba
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { FriendInfo } from '../../qq-info';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
import { decodePublicProfile, PUBLIC_PROFILE_KEYS } from './public-profile';
|
||||
|
||||
export interface FriendListPageEntry {
|
||||
friend: FriendInfo;
|
||||
@@ -33,8 +34,9 @@ export interface FriendListPage {
|
||||
cookie?: Uint8Array;
|
||||
}
|
||||
|
||||
function friendProperties(raw: OidbFriend): Map<number, string> {
|
||||
const props = new Map<number, string>();
|
||||
function friendProperties(raw: OidbFriend) {
|
||||
const props = new Map<number, Uint8Array>();
|
||||
const numbers = new Map<number, number>();
|
||||
|
||||
for (const additional of raw.additional ?? []) {
|
||||
if ((additional.type ?? 0) !== 1 || !additional.layer1) {
|
||||
@@ -42,22 +44,31 @@ function friendProperties(raw: OidbFriend): Map<number, string> {
|
||||
}
|
||||
|
||||
for (const property of additional.layer1.properties ?? []) {
|
||||
props.set(property.code ?? 0, property.value ?? '');
|
||||
props.set(property.code ?? 0, property.value ?? new Uint8Array(0));
|
||||
}
|
||||
|
||||
for (const property of additional.layer1.numberProperties ?? []) {
|
||||
numbers.set(property.key ?? 0, property.value ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
return props;
|
||||
return { props, numbers };
|
||||
}
|
||||
|
||||
function mapFriend(raw: OidbFriend): FriendListPageEntry {
|
||||
const props = friendProperties(raw);
|
||||
const { props, numbers } = friendProperties(raw);
|
||||
const profile = decodePublicProfile(props, numbers);
|
||||
return {
|
||||
categoryId: raw.customGroup ?? 0,
|
||||
friend: {
|
||||
uin: raw.uin ?? 0,
|
||||
uid: raw.uid ?? '',
|
||||
nickname: props.get(20002) ?? String(raw.uin ?? 0),
|
||||
remark: props.get(103) ?? '',
|
||||
nickname: props.has(20002)
|
||||
? Buffer.from(props.get(20002)!).toString('utf8')
|
||||
: String(raw.uin ?? 0),
|
||||
remark: Buffer.from(props.get(103) ?? []).toString('utf8'),
|
||||
categoryId: raw.customGroup ?? 0,
|
||||
...(Object.keys(profile).length ? { profile } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -80,7 +91,12 @@ export namespace FetchFriendListPage {
|
||||
field6: 1,
|
||||
field7: 0x7fffffff,
|
||||
body: [
|
||||
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
|
||||
{
|
||||
type: 1,
|
||||
number: {
|
||||
numbers: [...new Set([103, 102, 20002, 27394, ...PUBLIC_PROFILE_KEYS])],
|
||||
},
|
||||
},
|
||||
{ type: 4, number: { numbers: [100, 101, 102] } },
|
||||
],
|
||||
field10002: [13578, 13579, 13573, 13572, 13568],
|
||||
|
||||
@@ -24,12 +24,30 @@ import type {
|
||||
import type { UserProfileInfo } from '../../qq-info';
|
||||
import { applyBirthday, applyOnlineStatus, applyProfileDetails } from './fetch-user-profile';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
import { decodePublicProfile, PUBLIC_PROFILE_KEYS } from './public-profile';
|
||||
|
||||
const REQUESTED_KEYS = [
|
||||
20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037, 41756,
|
||||
41757, 42241,
|
||||
20002,
|
||||
27394,
|
||||
20009,
|
||||
20031,
|
||||
101,
|
||||
103,
|
||||
102,
|
||||
20020,
|
||||
20003,
|
||||
20026,
|
||||
105,
|
||||
27372,
|
||||
27406,
|
||||
20037,
|
||||
41756,
|
||||
41757,
|
||||
42241,
|
||||
// 企点标志(QQ 企点 / 企业版 QQ 账号):员工号实测为 1,普通账号为 0
|
||||
40410, 42031,
|
||||
40410,
|
||||
42031,
|
||||
...PUBLIC_PROFILE_KEYS,
|
||||
];
|
||||
|
||||
export namespace FetchUserProfileByUid {
|
||||
@@ -47,7 +65,7 @@ export namespace FetchUserProfileByUid {
|
||||
|
||||
export const serialize = (_ctx: Deps, p: Params): OidbUserInfoByUidRequest => ({
|
||||
uid: p.uid,
|
||||
keys: REQUESTED_KEYS.map((k) => ({ key: k })),
|
||||
keys: [...new Set(REQUESTED_KEYS)].map((k) => ({ key: k })),
|
||||
});
|
||||
|
||||
export const deserialize = (_ctx: Deps, body: OidbUserInfoResponse): UserProfileInfo => {
|
||||
@@ -110,6 +128,12 @@ export namespace FetchUserProfileByUid {
|
||||
applyOnlineStatus(info, bytesMap, numMap);
|
||||
applyProfileDetails(info, numMap);
|
||||
applyBirthday(info, bytesMap);
|
||||
const profile = decodePublicProfile(bytesMap, numMap);
|
||||
|
||||
if (Object.keys(profile).length > 0) {
|
||||
info.profile = profile;
|
||||
}
|
||||
|
||||
// 企点标志:40410 / 42031,服务器仅在返回时才出现(普通账号缺省 → 0)
|
||||
info.qidianMasterFlag = numMap.get(42031) ?? 0;
|
||||
info.qidianCrewFlag = numMap.get(40410) ?? 0;
|
||||
|
||||
@@ -29,6 +29,7 @@ import type {
|
||||
import type { UserProfileInfo } from '../../qq-info';
|
||||
import { unpackStatusWord } from '../extras/get-stranger-status';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
import { decodeMembership, decodePublicProfile, PUBLIC_PROFILE_KEYS } from './public-profile';
|
||||
|
||||
export function applyOnlineStatus(
|
||||
info: UserProfileInfo,
|
||||
@@ -63,27 +64,7 @@ export function applyProfileDetails(info: UserProfileInfo, numMap: Map<number, n
|
||||
info.regTime = registered;
|
||||
}
|
||||
|
||||
const flags = numMap.get(41756);
|
||||
|
||||
if (flags !== undefined) {
|
||||
info.vipFlag = (flags & 1) !== 0;
|
||||
info.yearVipFlag = (flags & 2) !== 0;
|
||||
info.svipFlag = (flags & 0x100) !== 0;
|
||||
}
|
||||
|
||||
const level = numMap.get(41757);
|
||||
|
||||
if (level !== undefined) {
|
||||
const mask = level & 0xfff;
|
||||
|
||||
if (mask !== 0) {
|
||||
info.vipLevel = 33 - Math.clz32(mask);
|
||||
} else if (info.vipFlag || info.yearVipFlag || info.svipFlag || numMap.get(42241) === 1) {
|
||||
info.vipLevel = 1;
|
||||
} else if (flags !== undefined && numMap.has(42241)) {
|
||||
info.vipLevel = 0;
|
||||
}
|
||||
}
|
||||
Object.assign(info, decodeMembership(numMap));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -120,10 +101,27 @@ export function applyBirthday(info: UserProfileInfo, bytesMap: Map<number, Uint8
|
||||
}
|
||||
|
||||
const REQUESTED_KEYS = [
|
||||
20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037, 41756,
|
||||
41757, 42241,
|
||||
20002,
|
||||
27394,
|
||||
20009,
|
||||
20031,
|
||||
101,
|
||||
103,
|
||||
102,
|
||||
20020,
|
||||
20003,
|
||||
20026,
|
||||
105,
|
||||
27372,
|
||||
27406,
|
||||
20037,
|
||||
41756,
|
||||
41757,
|
||||
42241,
|
||||
// 企点标志(QQ 企点 / 企业版 QQ 账号):员工号实测为 1,普通账号为 0
|
||||
40410, 42031,
|
||||
40410,
|
||||
42031,
|
||||
...PUBLIC_PROFILE_KEYS,
|
||||
];
|
||||
|
||||
export namespace FetchUserProfile {
|
||||
@@ -139,7 +137,7 @@ export namespace FetchUserProfile {
|
||||
|
||||
export const serialize = (_ctx: Deps, p: Params): OidbUserInfoRequest => ({
|
||||
uin: p.uin,
|
||||
keys: REQUESTED_KEYS.map((k) => ({ key: k })),
|
||||
keys: [...new Set(REQUESTED_KEYS)].map((k) => ({ key: k })),
|
||||
});
|
||||
|
||||
/** Defaults the response uin to `requestedUin` because the server
|
||||
@@ -154,6 +152,10 @@ export namespace FetchUserProfile {
|
||||
throw new Error('user info response body missing');
|
||||
}
|
||||
|
||||
if (requestedUin > 0 && body.body.uin != null && body.body.uin !== requestedUin) {
|
||||
throw new Error('profile response does not match the requested account');
|
||||
}
|
||||
|
||||
const info: UserProfileInfo = {
|
||||
uin: body.body.uin ?? requestedUin,
|
||||
uid: body.body.uid ?? '',
|
||||
@@ -209,6 +211,12 @@ export namespace FetchUserProfile {
|
||||
applyOnlineStatus(info, bytesMap, numMap);
|
||||
applyProfileDetails(info, numMap);
|
||||
applyBirthday(info, bytesMap);
|
||||
const profile = decodePublicProfile(bytesMap, numMap);
|
||||
|
||||
if (Object.keys(profile).length > 0) {
|
||||
info.profile = profile;
|
||||
}
|
||||
|
||||
// 企点标志:40410 / 42031,服务器仅在返回时才出现(普通账号缺省 → 0)
|
||||
info.qidianMasterFlag = numMap.get(42031) ?? 0;
|
||||
info.qidianCrewFlag = numMap.get(40410) ?? 0;
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import { protobuf_decode, protobuf_getUnknownFields } from '@snowluma/proton';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
OidbProfilePrivileges,
|
||||
OidbProfilePrivilege,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { ProfilePrivilege, PublicProfileFields } from '../../qq-info';
|
||||
|
||||
// Shared by the roster and both profile request forms.
|
||||
export const PUBLIC_PROFILE_KEYS = [
|
||||
102, 105, 107, 20003, 20004, 20020, 20009, 20011, 20016, 20021, 20031, 20037, 41756, 41757,
|
||||
42241,
|
||||
];
|
||||
const log = createLogger('Protocol.Profile');
|
||||
|
||||
function text(value: Uint8Array, code: number): string {
|
||||
try {
|
||||
return new TextDecoder('utf-8', { fatal: true }).decode(value);
|
||||
} catch (cause) {
|
||||
throw new Error(`invalid UTF-8 in profile property ${code}`, { cause });
|
||||
}
|
||||
}
|
||||
|
||||
export function decodeBirthday(
|
||||
raw: Uint8Array,
|
||||
): Pick<PublicProfileFields, 'birthdayYear' | 'birthdayMonth' | 'birthdayDay'> {
|
||||
if (raw.length !== 4) {
|
||||
throw new Error('invalid birthday length in profile property 20031');
|
||||
}
|
||||
|
||||
const year = (raw[0]! << 8) | raw[1]!;
|
||||
const month = raw[2]!;
|
||||
const day = raw[3]!;
|
||||
|
||||
if (month === 0 && day === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const date = new Date(0);
|
||||
date.setUTCFullYear(year || 2000, month - 1, day);
|
||||
|
||||
if (year > 9999 || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) {
|
||||
throw new Error('invalid date in profile property 20031');
|
||||
}
|
||||
|
||||
return {
|
||||
...(year > 0 ? { birthdayYear: year } : {}),
|
||||
birthdayMonth: month,
|
||||
birthdayDay: day,
|
||||
};
|
||||
}
|
||||
|
||||
function privilege(entry: OidbProfilePrivilege): ProfilePrivilege {
|
||||
checkKnownFields(entry, [1, 4, 5, 6, 7, 8, 9]);
|
||||
return {
|
||||
...(entry.type != null ? { type: entry.type } : {}),
|
||||
...(entry.level != null ? { level: entry.level } : {}),
|
||||
...(entry.flag != null ? { flag: entry.flag } : {}),
|
||||
...(entry.isBig != null ? { isBig: entry.isBig } : {}),
|
||||
...(entry.jumpUrl != null ? { jumpUrl: text(entry.jumpUrl, 107) } : {}),
|
||||
...(entry.iconUrl != null ? { iconUrl: text(entry.iconUrl, 107) } : {}),
|
||||
...(entry.deluxeIconUrl != null ? { deluxeIconUrl: text(entry.deluxeIconUrl, 107) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function checkKnownFields(value: unknown, tags: readonly number[]): void {
|
||||
for (const field of protobuf_getUnknownFields(value)) {
|
||||
if (tags.includes(field.fieldNumber)) {
|
||||
throw new Error(`unexpected wire type for privilege field ${field.fieldNumber}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function decodeMembership(
|
||||
numbers: ReadonlyMap<number, number>,
|
||||
): Pick<PublicProfileFields, 'vipFlag' | 'yearVipFlag' | 'svipFlag' | 'vipLevel'> {
|
||||
const result: Pick<PublicProfileFields, 'vipFlag' | 'yearVipFlag' | 'svipFlag' | 'vipLevel'> =
|
||||
{};
|
||||
const flags = numbers.get(41756);
|
||||
|
||||
if (flags !== undefined) {
|
||||
result.vipFlag = (flags & 1) !== 0;
|
||||
result.yearVipFlag = (flags & 2) !== 0;
|
||||
result.svipFlag = (flags & 0x100) !== 0;
|
||||
}
|
||||
|
||||
const level = numbers.get(41757);
|
||||
|
||||
if (level !== undefined) {
|
||||
const mask = level & 0xfff;
|
||||
|
||||
if (mask !== 0) {
|
||||
result.vipLevel = 33 - Math.clz32(mask);
|
||||
} else if (
|
||||
result.vipFlag ||
|
||||
result.yearVipFlag ||
|
||||
result.svipFlag ||
|
||||
numbers.get(42241) === 1
|
||||
) {
|
||||
result.vipLevel = 1;
|
||||
} else if (flags !== undefined && numbers.has(42241)) {
|
||||
result.vipLevel = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function decodePublicProfile(
|
||||
bytes: ReadonlyMap<number, Uint8Array>,
|
||||
numbers: ReadonlyMap<number, number>,
|
||||
): PublicProfileFields {
|
||||
const result: PublicProfileFields = {};
|
||||
|
||||
for (const [code, field] of [
|
||||
[102, 'sign'],
|
||||
[20011, 'email'],
|
||||
[20016, 'phoneNum'],
|
||||
[20003, 'country'],
|
||||
[20004, 'province'],
|
||||
[20020, 'city'],
|
||||
[20021, 'college'],
|
||||
] as const) {
|
||||
const value = bytes.get(code);
|
||||
|
||||
if (value !== undefined) {
|
||||
result[field] = text(value, code);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [code, field] of [
|
||||
[20037, 'age'],
|
||||
[105, 'level'],
|
||||
] as const) {
|
||||
const value = numbers.get(code);
|
||||
|
||||
if (value !== undefined && Number.isInteger(value) && value >= 0) {
|
||||
result[field] = value;
|
||||
}
|
||||
}
|
||||
|
||||
const sex = numbers.get(20009);
|
||||
|
||||
if (sex !== undefined) {
|
||||
result.sex = sex === 1 ? 'male' : sex === 2 ? 'female' : 'unknown';
|
||||
}
|
||||
|
||||
const birthday = bytes.get(20031);
|
||||
|
||||
if (birthday !== undefined && birthday.length > 0) {
|
||||
// Keep the existing optional-birthday behavior, but make malformed
|
||||
// upstream values diagnosable without recording personal data.
|
||||
try {
|
||||
Object.assign(result, decodeBirthday(birthday));
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
'birthday unavailable: bytes=%d error=%s',
|
||||
birthday.length,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Object.assign(result, decodeMembership(numbers));
|
||||
|
||||
const icons = bytes.get(107);
|
||||
|
||||
if (icons !== undefined) {
|
||||
try {
|
||||
const decoded = protobuf_decode<OidbProfilePrivileges>(icons);
|
||||
checkKnownFields(decoded, [3]);
|
||||
|
||||
if (!decoded.lists) {
|
||||
// The client treats an absent list body as unavailable, not
|
||||
// as a returned list containing zero entries.
|
||||
return result;
|
||||
}
|
||||
|
||||
checkKnownFields(decoded.lists, [2, 3, 4]);
|
||||
|
||||
result.privilegeIcons = {
|
||||
...(decoded.lists.jumpUrl != null
|
||||
? { jumpUrl: text(decoded.lists.jumpUrl, 107) }
|
||||
: {}),
|
||||
open: (decoded.lists.open ?? []).map(privilege),
|
||||
closed: (decoded.lists.closed ?? []).map(privilege),
|
||||
};
|
||||
} catch (cause) {
|
||||
throw new Error('invalid privilege data in profile property 107', { cause });
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import type { BridgeEventBus } from './event-bus';
|
||||
import type { QQEventVariant } from './events';
|
||||
import type { GroupInviteTracker } from './group-invite-tracker';
|
||||
import type { IdentityService } from './identity-service';
|
||||
import { formatGroupRequestFlag, type GroupRequestInfo } from './qq-info';
|
||||
import { formatGroupRequestFlag, isSelfGroupInvitation, type GroupRequestInfo } from './qq-info';
|
||||
|
||||
const moduleLog = createLogger('Bridge');
|
||||
const moduleEventLog = createLogger('Event');
|
||||
@@ -564,7 +564,7 @@ export class IncomingPacketPipeline {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (request.eventType === 2) {
|
||||
if (isSelfGroupInvitation(request)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,39 @@
|
||||
export interface ProfilePrivilege {
|
||||
type?: number;
|
||||
level?: number;
|
||||
flag?: number;
|
||||
isBig?: number;
|
||||
jumpUrl?: string;
|
||||
iconUrl?: string;
|
||||
deluxeIconUrl?: string;
|
||||
}
|
||||
|
||||
/** Only fields actually supplied by the profile service; absent values stay absent. */
|
||||
export interface PublicProfileFields {
|
||||
sign?: string;
|
||||
sex?: 'male' | 'female' | 'unknown';
|
||||
age?: number;
|
||||
level?: number;
|
||||
birthdayYear?: number;
|
||||
birthdayMonth?: number;
|
||||
birthdayDay?: number;
|
||||
phoneNum?: string;
|
||||
email?: string;
|
||||
country?: string;
|
||||
province?: string;
|
||||
city?: string;
|
||||
college?: string;
|
||||
vipFlag?: boolean;
|
||||
svipFlag?: boolean;
|
||||
yearVipFlag?: boolean;
|
||||
vipLevel?: number;
|
||||
privilegeIcons?: {
|
||||
jumpUrl?: string;
|
||||
open: ProfilePrivilege[];
|
||||
closed: ProfilePrivilege[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface UserProfileInfo {
|
||||
uin: number;
|
||||
uid: string;
|
||||
@@ -12,6 +48,7 @@ export interface UserProfileInfo {
|
||||
* Already requested in `fetchUserProfile` keys[]; LagrangeV2
|
||||
* `FetchStrangerService.cs` confirms `// Level`. */
|
||||
level: number;
|
||||
profile?: PublicProfileFields;
|
||||
regTime?: number;
|
||||
/**
|
||||
* 生日 — OIDB 0xFE1_2 bytes-property key 20031。
|
||||
@@ -46,6 +83,8 @@ export interface FriendInfo {
|
||||
uid: string;
|
||||
nickname: string;
|
||||
remark: string;
|
||||
categoryId?: number;
|
||||
profile?: PublicProfileFields;
|
||||
}
|
||||
|
||||
export interface FriendCategoryInfo {
|
||||
@@ -121,6 +160,12 @@ export interface GroupRequestInfo {
|
||||
operateTransInfo?: Uint8Array;
|
||||
}
|
||||
|
||||
/** Invitations handled by the invited account, rather than a group administrator.
|
||||
* Notification types 1 and 2 use different approval discriminators. */
|
||||
export function isSelfGroupInvitation(request: Pick<GroupRequestInfo, 'eventType'>): boolean {
|
||||
return request.eventType === 2 || request.eventType === 10;
|
||||
}
|
||||
|
||||
/** Approval tuple required by OIDB 0x10C8. The OneBot flag is opaque to
|
||||
* clients, but carrying the complete tuple makes delayed handling stateless. */
|
||||
export type GroupRequestHandle = Pick<
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { JsonObject } from '@snowluma/common/json';
|
||||
import type { QzoneEmotionUgcId } from '@snowluma/proto-defs/qzone';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
|
||||
export type QzonePublicContent = string | JsonObject[];
|
||||
@@ -15,6 +17,13 @@ export interface QzoneShareArk extends JsonObject {
|
||||
notice: string | null;
|
||||
}
|
||||
|
||||
export interface QzoneFeedDetail extends JsonObject {
|
||||
/** Original cells, ready to pass to getQzoneShareArk when sharing is allowed. */
|
||||
feed: JsonObject;
|
||||
/** Upstream comment continuation; null when the server supplies none. */
|
||||
attach_info: string | null;
|
||||
}
|
||||
|
||||
interface HomeFeedCursor {
|
||||
version: 1;
|
||||
kind: 'home';
|
||||
@@ -238,6 +247,63 @@ export async function getQzoneHomeFeeds(
|
||||
return { ...data, feeds, has_more: data.has_more, next_cursor: nextCursor };
|
||||
}
|
||||
|
||||
export async function getQzoneFeedDetail(
|
||||
cookies: Record<string, string>,
|
||||
tid: string,
|
||||
): Promise<QzoneFeedDetail> {
|
||||
if (tid.length !== 24 || !/^[0-9a-f]{24}$/i.test(tid)) {
|
||||
throw new Error('空间说说 tid 必须是 24 位十六进制编号');
|
||||
}
|
||||
|
||||
const feedId = tid.toLowerCase();
|
||||
const identity = Buffer.from(feedId, 'hex');
|
||||
// Personal-space tids carry the author and creation time as little-endian
|
||||
// uint32 words. Use the actual time rather than guessing an ignored field.
|
||||
const ugcId = protobuf_encode<QzoneEmotionUgcId>({
|
||||
appId: 311n,
|
||||
uin: BigInt(identity.readUInt32LE(0)),
|
||||
publishTime: BigInt(identity.readUInt32LE(4)),
|
||||
field4: '',
|
||||
field5: '',
|
||||
field6: '0',
|
||||
tid: feedId,
|
||||
});
|
||||
const data = await request(cookies, reader, 'GetFeedDetail', '0x97b1_1', {
|
||||
union_id: {
|
||||
feed_id: feedId,
|
||||
ugc_id: Buffer.from(ugcId).toString('base64'),
|
||||
adv_id: null,
|
||||
},
|
||||
feed_action_domain_type: 1,
|
||||
from_page: 1,
|
||||
});
|
||||
const wrapper = data.feed;
|
||||
|
||||
if (!isObject(wrapper) || !isObject(wrapper.feed)) {
|
||||
throw new Error('qzone GetFeedDetail 响应缺少完整动态 feed.feed');
|
||||
}
|
||||
|
||||
const feed = wrapper.feed;
|
||||
const common = feed.cell_common;
|
||||
const unionId = isObject(common) ? common.union_id : undefined;
|
||||
|
||||
if (
|
||||
!isObject(unionId) ||
|
||||
typeof unionId.feed_id !== 'string' ||
|
||||
unionId.feed_id.toLowerCase() !== feedId
|
||||
) {
|
||||
throw new Error('qzone GetFeedDetail 返回的动态编号与请求不符');
|
||||
}
|
||||
|
||||
if (data.attach_info != null && typeof data.attach_info !== 'string') {
|
||||
throw new Error('qzone GetFeedDetail 评论游标格式异常');
|
||||
}
|
||||
|
||||
// Match homepage feeds: remove only the item wrapper, retaining every cell
|
||||
// (especially the opaque sharing fields) and the remaining response metadata.
|
||||
return { ...data, feed, attach_info: data.attach_info ?? null };
|
||||
}
|
||||
|
||||
export async function getQzoneShareArk(
|
||||
cookies: Record<string, string>,
|
||||
feed: JsonObject,
|
||||
@@ -272,7 +338,7 @@ export async function getQzoneShareArk(
|
||||
typeof feed.cell_feed_transfer !== 'string' ||
|
||||
!feed.cell_feed_transfer
|
||||
) {
|
||||
throw new Error('空间动态缺少分享信息,请传入主页或推荐列表返回的完整动态');
|
||||
throw new Error('空间动态缺少分享信息,请传入主页、详情或推荐列表返回的完整动态');
|
||||
}
|
||||
|
||||
const data = await request(cookies, 'trpc.qq.share.Service', 'CreateShare', '0x9409_1', {
|
||||
@@ -286,7 +352,7 @@ export async function getQzoneShareArk(
|
||||
},
|
||||
});
|
||||
|
||||
if (data.err !== undefined) {
|
||||
if (data.err !== undefined && data.err !== null) {
|
||||
if (
|
||||
!isObject(data.err) ||
|
||||
(data.err.code !== undefined && typeof data.err.code !== 'number')
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
DEFAULT_HTTP_DOWNLOAD_TIMEOUT_MS,
|
||||
DEFAULT_MAX_BINARY_DOWNLOAD_BYTES,
|
||||
httpDownloadTimeoutMs,
|
||||
maxBinaryDownloadBytes,
|
||||
} from '../src/highway/download-settings';
|
||||
import { downloadHttp } from '../src/highway/utils';
|
||||
|
||||
const memorySink = (): {
|
||||
write: () => void;
|
||||
done: () => undefined;
|
||||
discard: () => void;
|
||||
} => ({ write: () => undefined, done: () => undefined, discard: () => undefined });
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('highway download settings', () => {
|
||||
it('keeps the documented defaults when nothing is configured', () => {
|
||||
expect(httpDownloadTimeoutMs({})).toBe(60_000);
|
||||
expect(maxBinaryDownloadBytes({})).toBe(1024 * 1024 * 1024);
|
||||
expect(DEFAULT_HTTP_DOWNLOAD_TIMEOUT_MS).toBe(60_000);
|
||||
expect(DEFAULT_MAX_BINARY_DOWNLOAD_BYTES).toBe(1024 * 1024 * 1024);
|
||||
});
|
||||
|
||||
it('reads both knobs from the environment', () => {
|
||||
expect(httpDownloadTimeoutMs({ SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS: '180000' })).toBe(
|
||||
180_000,
|
||||
);
|
||||
expect(
|
||||
maxBinaryDownloadBytes({ SNOWLUMA_MAX_BINARY_DOWNLOAD_BYTES: String(2 ** 31) }),
|
||||
).toBe(2 ** 31);
|
||||
});
|
||||
|
||||
it('ignores unusable values instead of failing the download', () => {
|
||||
expect(httpDownloadTimeoutMs({ SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS: '0' })).toBe(60_000);
|
||||
expect(httpDownloadTimeoutMs({ SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS: 'soon' })).toBe(60_000);
|
||||
expect(maxBinaryDownloadBytes({ SNOWLUMA_MAX_BINARY_DOWNLOAD_BYTES: '-5' })).toBe(
|
||||
DEFAULT_MAX_BINARY_DOWNLOAD_BYTES,
|
||||
);
|
||||
});
|
||||
|
||||
it('feeds the configured timeout into the fetch signal', async () => {
|
||||
vi.stubEnv('SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS', '1234');
|
||||
const timeoutSpy = vi.spyOn(AbortSignal, 'timeout');
|
||||
const fetchStub = vi.fn(
|
||||
async () => new Response(new Uint8Array([1, 2, 3]), { status: 200 }),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchStub);
|
||||
|
||||
await downloadHttp('https://example.test/media.bin', 'media', 1024, memorySink);
|
||||
|
||||
expect(timeoutSpy).toHaveBeenCalledWith(1234);
|
||||
expect(fetchStub).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -63,10 +63,18 @@ describe('FetchFriendListPage namespace', () => {
|
||||
expect(out.nextUin).toBeUndefined();
|
||||
});
|
||||
|
||||
it('emits the verbatim property request list (codes 100/101/102/103/20002/27394)', () => {
|
||||
it('requests basic identity and public profiles in the same roster page', () => {
|
||||
const out = FetchFriendListPage.serialize({} as any, {}) as any;
|
||||
expect(out.body).toEqual([
|
||||
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
|
||||
{
|
||||
type: 1,
|
||||
number: {
|
||||
numbers: [
|
||||
103, 102, 20002, 27394, 105, 107, 20003, 20004, 20020, 20009, 20011,
|
||||
20016, 20021, 20031, 20037, 41756, 41757, 42241,
|
||||
],
|
||||
},
|
||||
},
|
||||
{ type: 4, number: { numbers: [100, 101, 102] } },
|
||||
]);
|
||||
});
|
||||
@@ -92,8 +100,8 @@ describe('FetchFriendListPage namespace', () => {
|
||||
type: 1,
|
||||
layer1: {
|
||||
properties: [
|
||||
{ code: 20002, value: 'Alice' },
|
||||
{ code: 103, value: 'A' },
|
||||
{ code: 20002, value: Buffer.from('Alice') },
|
||||
{ code: 103, value: Buffer.from('A') },
|
||||
],
|
||||
},
|
||||
},
|
||||
@@ -114,7 +122,13 @@ describe('FetchFriendListPage namespace', () => {
|
||||
entries: [
|
||||
{
|
||||
categoryId: 7,
|
||||
friend: { uin: 10001, uid: 'u1', nickname: 'Alice', remark: 'A' },
|
||||
friend: {
|
||||
uin: 10001,
|
||||
uid: 'u1',
|
||||
nickname: 'Alice',
|
||||
remark: 'A',
|
||||
categoryId: 7,
|
||||
},
|
||||
},
|
||||
],
|
||||
categories: [
|
||||
@@ -138,7 +152,7 @@ describe('FetchFriendListPage namespace', () => {
|
||||
entries: [
|
||||
{
|
||||
categoryId: 0,
|
||||
friend: { uin: 0, uid: '', nickname: '0', remark: '' },
|
||||
friend: { uin: 0, uid: '', nickname: '0', remark: '', categoryId: 0 },
|
||||
},
|
||||
],
|
||||
categories: [],
|
||||
|
||||
@@ -51,6 +51,7 @@ function makeSender() {
|
||||
describe('FetchGroupRequests namespace', () => {
|
||||
it('maps native list notification types to 0x10C8 operation types', () => {
|
||||
expect(groupRequestOperationType(1)).toBe(2);
|
||||
expect(groupRequestOperationType(2)).toBe(10);
|
||||
expect(groupRequestOperationType(7)).toBe(1);
|
||||
expect(groupRequestOperationType(17)).toBe(100);
|
||||
expect(groupRequestOperationType(5)).toBe(22);
|
||||
|
||||
@@ -99,6 +99,7 @@ describe('FetchUserProfile namespace', () => {
|
||||
yearVipFlag: !!(flags & 2),
|
||||
svipFlag: !!(flags & 0x100),
|
||||
vipLevel: level,
|
||||
profile: { vipLevel: level },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase, OidbSvcTrpcTcp0xFD4_1Response } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbUserInfoResponse } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { FetchFriendListPage } from '../../../src/oidb-services/contacts/fetch-friend-list-page';
|
||||
import { FetchUserProfile } from '../../../src/oidb-services/contacts/fetch-user-profile';
|
||||
import { FetchUserProfileByUid } from '../../../src/oidb-services/contacts/fetch-user-profile-by-uid';
|
||||
import { decodePublicProfile } from '../../../src/oidb-services/contacts/public-profile';
|
||||
|
||||
// Synthetic wire fixture, independent of the privilege schema: top-level tag 3;
|
||||
// body tags 2 (jump), 3 (open), 4 (closed); both entry URLs are present.
|
||||
const icons = Buffer.from(
|
||||
'1a2c1204636172641a1e08022000280032066e6f726d616c3a0664656c75786542046a756d704801220408032001',
|
||||
'hex',
|
||||
);
|
||||
const bytes = [
|
||||
{ code: 102, value: Buffer.from('') },
|
||||
{ code: 20011, value: Buffer.from('mail@example.test') },
|
||||
{ code: 20016, value: Buffer.from('') },
|
||||
{ code: 20003, value: Buffer.from('中国') },
|
||||
{ code: 20004, value: Buffer.from('省份') },
|
||||
{ code: 20020, value: Buffer.from('城市') },
|
||||
{ code: 20005, value: Buffer.from('邮编') },
|
||||
{ code: 20021, value: Buffer.from('学校') },
|
||||
{ code: 20031, value: Uint8Array.from([0, 0, 2, 29]) },
|
||||
{ code: 107, value: icons },
|
||||
];
|
||||
const numbers = [
|
||||
[20037, 0],
|
||||
[105, 0],
|
||||
[20009, 2],
|
||||
[41756, 0],
|
||||
[41757, 0],
|
||||
[42241, 0],
|
||||
] as const;
|
||||
|
||||
function sender(responseData: Uint8Array) {
|
||||
return {
|
||||
sendRawPacket: vi.fn(async () => ({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(responseData),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
describe('public contact profiles', () => {
|
||||
it.each(['roster', 'uin', 'uid'])(
|
||||
'preserves presence and privilege lists through the %s wire codec',
|
||||
async (form) => {
|
||||
let profile;
|
||||
|
||||
if (form === 'roster') {
|
||||
const page = await FetchFriendListPage.invoke(
|
||||
sender(
|
||||
protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>({
|
||||
body: {
|
||||
friends: [
|
||||
{
|
||||
uin: 10001,
|
||||
customGroup: 0,
|
||||
additional: [
|
||||
{
|
||||
type: 1,
|
||||
layer1: {
|
||||
properties: bytes,
|
||||
numberProperties: numbers.map(
|
||||
([key, value]) => ({ key, value }),
|
||||
),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
),
|
||||
{},
|
||||
);
|
||||
expect(page.entries[0]?.friend.categoryId).toBe(0);
|
||||
profile = page.entries[0]?.friend.profile;
|
||||
} else {
|
||||
const deps = sender(
|
||||
protobuf_encode<OidbBase<OidbUserInfoResponse>>({
|
||||
body: {
|
||||
body: {
|
||||
uin: 10001,
|
||||
uid: 'u_test',
|
||||
properties: {
|
||||
bytesProperties: bytes,
|
||||
numberProperties: numbers.map(([number1, number2]) => ({
|
||||
number1,
|
||||
number2,
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const user =
|
||||
form === 'uin'
|
||||
? await FetchUserProfile.invoke(deps, { uin: 10001 })
|
||||
: await FetchUserProfileByUid.invoke(deps, { uid: 'u_test' });
|
||||
profile = user.profile;
|
||||
}
|
||||
|
||||
expect(profile).toEqual({
|
||||
sign: '',
|
||||
age: 0,
|
||||
level: 0,
|
||||
sex: 'female',
|
||||
email: 'mail@example.test',
|
||||
phoneNum: '',
|
||||
country: '中国',
|
||||
province: '省份',
|
||||
city: '城市',
|
||||
college: '学校',
|
||||
birthdayMonth: 2,
|
||||
birthdayDay: 29,
|
||||
vipFlag: false,
|
||||
svipFlag: false,
|
||||
yearVipFlag: false,
|
||||
vipLevel: 0,
|
||||
privilegeIcons: {
|
||||
jumpUrl: 'card',
|
||||
open: [
|
||||
{
|
||||
type: 2,
|
||||
level: 0,
|
||||
flag: 0,
|
||||
iconUrl: 'normal',
|
||||
deluxeIconUrl: 'deluxe',
|
||||
jumpUrl: 'jump',
|
||||
isBig: 1,
|
||||
},
|
||||
],
|
||||
closed: [{ type: 3, level: 1 }],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('distinguishes missing, unavailable and explicitly empty icon lists', () => {
|
||||
expect(decodePublicProfile(new Map(), new Map())).toEqual({});
|
||||
expect(decodePublicProfile(new Map([[107, Buffer.alloc(0)]]), new Map())).toEqual({});
|
||||
expect(decodePublicProfile(new Map([[107, Buffer.from([0x1a, 0])]]), new Map())).toEqual({
|
||||
privilegeIcons: { open: [], closed: [] },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects truncated icons and invalid text without returning successful empty data', () => {
|
||||
expect(() =>
|
||||
decodePublicProfile(new Map([[107, Buffer.from([0x1a, 0xff])]]), new Map()),
|
||||
).toThrow('invalid privilege data');
|
||||
expect(() =>
|
||||
decodePublicProfile(new Map([[107, Buffer.from([0x18, 0])]]), new Map()),
|
||||
).toThrow('invalid privilege data');
|
||||
expect(() =>
|
||||
decodePublicProfile(new Map([[107, Buffer.from('1a041a020a00', 'hex')]]), new Map()),
|
||||
).toThrow('invalid privilege data');
|
||||
expect(() =>
|
||||
decodePublicProfile(new Map([[20011, Buffer.from([0xff])]]), new Map()),
|
||||
).toThrow('invalid UTF-8');
|
||||
});
|
||||
|
||||
it('rejects a profile response belonging to a different requested account', async () => {
|
||||
const deps = sender(
|
||||
protobuf_encode<OidbBase<OidbUserInfoResponse>>({ body: { body: { uin: 10002 } } }),
|
||||
);
|
||||
await expect(FetchUserProfile.invoke(deps, { uin: 10001 })).rejects.toThrow(
|
||||
'does not match',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { getQzoneFeedDetail, getQzoneShareArk } from '../../src/web/qzone-public';
|
||||
import { RequestUtil, getBknFromCookie } from '../../src/web/request-util';
|
||||
|
||||
const cookies = { p_skey: 'fixture', uin: 'o20002' };
|
||||
// Synthetic post: author 10001, Unix time 1700000000, sequence word 1.
|
||||
const tid = '1127000000f1536501000000';
|
||||
const ugcId = 'CLcCEJFOGIDiz6oGIgAqADIBMEIYMTEyNzAwMDAwMGYxNTM2NTAxMDAwMDAw';
|
||||
const feed = {
|
||||
cell_common: { domain_type: 1, union_id: { feed_id: tid, ugc_id: ugcId }, operate_mask: 0 },
|
||||
cell_summary: { summary: 'Fixture post' },
|
||||
cell_pic: { pics: [{ url: 'https://example.com/one.png' }, { future_image: true }] },
|
||||
cell_video: { opaque_video: 'preserved' },
|
||||
cell_comment: { comments: [{ id: '9007199254740993', unknown: true }] },
|
||||
cell_operation: {
|
||||
share_outside: {
|
||||
share_access_resource: { busi_id: 'qzone_feed', resource_id: 'resource' },
|
||||
},
|
||||
},
|
||||
cell_feed_transfer: 'original-transfer',
|
||||
cell_future: { nested: [null, '18446744073709551615', { preserved: true }] },
|
||||
};
|
||||
const detail = {
|
||||
feed: { feed },
|
||||
attach_info: 'opaque-comment-continuation',
|
||||
contribute_bar: null,
|
||||
future_detail_field: { preserved: true },
|
||||
};
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
describe('Qzone feed detail by tid', () => {
|
||||
it.each([tid, tid.toUpperCase()])(
|
||||
'requests the personal-space detail with the encoded identity (%s)',
|
||||
async (input) => {
|
||||
const request = vi
|
||||
.spyOn(RequestUtil, 'HttpGetJson')
|
||||
.mockResolvedValue({ retcode: 0, data: detail });
|
||||
const result = await getQzoneFeedDetail(cookies, input);
|
||||
|
||||
expect(result).toEqual({ ...detail, feed });
|
||||
expect(result.feed).toBe(feed);
|
||||
expect(request).toHaveBeenCalledExactlyOnceWith(
|
||||
`https://h5.qzone.qq.com/http2rpc/gotrpc/v1/trpc.qzone.feeds_reader.FeedsReader/GetFeedDetail?g_tk=${getBknFromCookie(cookies)}`,
|
||||
'POST',
|
||||
{
|
||||
union_id: { feed_id: tid, ugc_id: ugcId, adv_id: null },
|
||||
feed_action_domain_type: 1,
|
||||
from_page: 1,
|
||||
},
|
||||
expect.objectContaining({
|
||||
Cookie: 'p_skey=fixture; uin=o20002',
|
||||
'Content-Type': 'application/json',
|
||||
'x-oidb': JSON.stringify({
|
||||
uint32_command: '0x97b1',
|
||||
uint32_service_type: '1',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps the author and time unsigned and emits the explicit empty identity fields', async () => {
|
||||
const highTid = 'ffffffffffffffff01000000';
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
retcode: 0,
|
||||
data: { feed: { feed: { cell_common: { union_id: { feed_id: highTid } } } } },
|
||||
});
|
||||
|
||||
await getQzoneFeedDetail(cookies, highTid);
|
||||
const body = request.mock.calls[0]![2] as { union_id: { ugc_id: string } };
|
||||
// Independent wire vector: app 311; two uint32-max values encoded as
|
||||
// positive int64; present empty strings in fields 4 and 5; field 8 tid.
|
||||
expect(Buffer.from(body.union_id.ugc_id, 'base64').toString('hex')).toBe(
|
||||
'08b70210ffffffff0f18ffffffff0f22002a003201304218' +
|
||||
'666666666666666666666666666666663031303030303030',
|
||||
);
|
||||
});
|
||||
|
||||
it.each([undefined, null, ''])(
|
||||
'preserves an empty or absent upstream comment cursor (%s)',
|
||||
async (attach_info) => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
retcode: 0,
|
||||
data: { ...detail, attach_info },
|
||||
});
|
||||
|
||||
expect((await getQzoneFeedDetail(cookies, tid)).attach_info).toBe(attach_info ?? null);
|
||||
expect(request).toHaveBeenCalledOnce();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(['', 'T1', 'g'.repeat(24), 'a'.repeat(23), 'a'.repeat(25), `${tid}\n`, ` ${tid}`])(
|
||||
'rejects unsupported or malformed post IDs before requesting (%j)',
|
||||
async (input) => {
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson');
|
||||
|
||||
await expect(getQzoneFeedDetail(cookies, input)).rejects.toThrow('24 位十六进制');
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{},
|
||||
{ feed: null },
|
||||
{ feed: [] },
|
||||
{ feed: { feed: [] } },
|
||||
{ feed: { feed: {} } },
|
||||
{ feed: { feed: { cell_common: { union_id: { feed_id: 'other' } } } } },
|
||||
{ ...detail, attach_info: {} },
|
||||
])('rejects incomplete, mismatched or malformed details (%#)', async (data) => {
|
||||
const request = vi
|
||||
.spyOn(RequestUtil, 'HttpGetJson')
|
||||
.mockResolvedValue({ retcode: 0, data });
|
||||
|
||||
await expect(getQzoneFeedDetail(cookies, tid)).rejects.toThrow('GetFeedDetail');
|
||||
expect(request).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('propagates access and transport failures without a second request', async () => {
|
||||
const request = vi
|
||||
.spyOn(RequestUtil, 'HttpGetJson')
|
||||
.mockResolvedValueOnce({ retcode: 10023, message: '无权限访问' })
|
||||
.mockRejectedValueOnce(new Error('network down'));
|
||||
|
||||
await expect(getQzoneFeedDetail(cookies, tid)).rejects.toThrow('10023 无权限访问');
|
||||
expect(request).toHaveBeenCalledTimes(1);
|
||||
await expect(getQzoneFeedDetail(cookies, tid)).rejects.toThrow('network down');
|
||||
expect(request).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('passes the returned feed straight to card generation without rebuilding sharing data', async () => {
|
||||
const ark = '{ "app": "com.tencent.tuwen.lua", "fixture": true }';
|
||||
const request = vi
|
||||
.spyOn(RequestUtil, 'HttpGetJson')
|
||||
.mockResolvedValueOnce({ retcode: 0, data: detail })
|
||||
.mockResolvedValueOnce({ retcode: 0, data: { template_data: ark } });
|
||||
const result = await getQzoneFeedDetail(cookies, tid);
|
||||
|
||||
await expect(getQzoneShareArk(cookies, result.feed)).resolves.toEqual({
|
||||
ark,
|
||||
requires_confirmation: false,
|
||||
notice: null,
|
||||
});
|
||||
expect(request).toHaveBeenCalledTimes(2);
|
||||
expect(request).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.stringContaining('/trpc.qq.share.Service/CreateShare?g_tk='),
|
||||
'POST',
|
||||
{
|
||||
info: {
|
||||
busi_id: 'qzone_feed',
|
||||
resource_id: 'resource',
|
||||
template: 'ark_busi_select',
|
||||
busi_data: 'original-transfer',
|
||||
plat: 1,
|
||||
target: 3,
|
||||
},
|
||||
},
|
||||
expect.any(Object),
|
||||
);
|
||||
});
|
||||
|
||||
it('can read a share-restricted feed while preserving the share refusal', async () => {
|
||||
const restrictedFeed = {
|
||||
...feed,
|
||||
cell_common: { ...feed.cell_common, operate_mask: 1 << 17 },
|
||||
};
|
||||
const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
|
||||
retcode: 0,
|
||||
data: { feed: { feed: restrictedFeed } },
|
||||
});
|
||||
const result = await getQzoneFeedDetail(cookies, tid);
|
||||
|
||||
expect(result.feed).toBe(restrictedFeed);
|
||||
await expect(getQzoneShareArk(cookies, result.feed)).rejects.toThrow('不支持分享');
|
||||
expect(request).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -62,6 +62,26 @@ describe('Qzone share card', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('preserves a successful card when the upstream business error is null', async () => {
|
||||
const card = '{ "app": "com.tencent.miniapp.lua", "view": "miniapp" }';
|
||||
const req = request({
|
||||
template_data: card,
|
||||
err: null,
|
||||
info: {
|
||||
busi_data: Buffer.from(
|
||||
JSON.stringify({ err_code: 0, err_msg: '', need_break: false, tips: {} }),
|
||||
).toString('base64'),
|
||||
},
|
||||
});
|
||||
|
||||
await expect(getQzoneShareArk(cookies, feed)).resolves.toEqual({
|
||||
ark: card,
|
||||
requires_confirmation: false,
|
||||
notice: null,
|
||||
});
|
||||
expect(req).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('rejects unavailable sharing and incomplete feeds before requesting a card', async () => {
|
||||
const req = request({ template_data: ark });
|
||||
await expect(
|
||||
@@ -77,6 +97,11 @@ describe('Qzone share card', () => {
|
||||
it.each([
|
||||
[{ err: { code: 3, msg: '参数错误' }, template_data: ark }, '3 参数错误'],
|
||||
[{ err: { code: '0' }, template_data: ark }, '业务响应异常'],
|
||||
[{ err: false, template_data: ark }, '业务响应异常'],
|
||||
[{ err: 0, template_data: ark }, '业务响应异常'],
|
||||
[{ err: '', template_data: ark }, '业务响应异常'],
|
||||
[{ err: [], template_data: ark }, '业务响应异常'],
|
||||
[{ err: null }, '未返回卡片'],
|
||||
[{}, '未返回卡片'],
|
||||
[{ template_data: '[]' }, '卡片格式异常'],
|
||||
[{ template_data: ark, info: { busi_data: '!' } }, '提示编码异常'],
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/proton",
|
||||
"version": "2.3.1",
|
||||
"version": "2.3.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl with edge-case fixes applied.",
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user