Compare commits
117 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
744f25fd9b | ||
|
|
22bde5d949 | ||
|
|
ca61e6039f | ||
|
|
9df7b7524b | ||
|
|
0cb5daed5e | ||
|
|
f2ea3354f8 | ||
|
|
efcbf988b2 | ||
|
|
a341fa4b15 | ||
|
|
8bea681aa2 | ||
|
|
84f4cde85e | ||
|
|
6c8866b108 | ||
|
|
f2ade5603f | ||
|
|
87f7bd8c54 | ||
|
|
9edc255a02 | ||
|
|
7425cfae20 | ||
|
|
1b80487119 | ||
|
|
43b63e9a75 | ||
|
|
b0612d8d12 | ||
|
|
e031cd4108 | ||
|
|
b6b433af98 | ||
|
|
ae1ec3be0e | ||
|
|
33bebb4446 | ||
|
|
bab5aafd91 | ||
|
|
e44e4ced17 | ||
|
|
f452c657ed | ||
|
|
1cd838e7a1 | ||
|
|
a8f460499b | ||
|
|
a977228a09 | ||
|
|
e9faec0e28 | ||
|
|
4a10f38743 | ||
|
|
a1688a33b0 | ||
|
|
45c3a6841a | ||
|
|
2b63f375fc | ||
|
|
0fa912a32e | ||
|
|
5f1700fc1b | ||
|
|
54038c775a | ||
|
|
c15ecd0402 | ||
|
|
f79187f36a | ||
|
|
24ec8a7eba | ||
|
|
3773106425 | ||
|
|
f65880b164 | ||
|
|
8d9f44b6b0 | ||
|
|
bd40ac3522 | ||
|
|
60733aacab | ||
|
|
a2ce3b2c19 | ||
|
|
7882081bdb | ||
|
|
f1ef07544d | ||
|
|
c120b0fb97 | ||
|
|
93290e4d0c | ||
|
|
fa4870bdca | ||
|
|
b126b5c166 | ||
|
|
11d42b4e98 | ||
|
|
8b3f11a22b | ||
|
|
8ecf41ccb7 | ||
|
|
fcbb2661d1 | ||
|
|
299fa85a74 | ||
|
|
d8763c98db | ||
|
|
a557bf72e7 | ||
|
|
eb119ecb92 | ||
|
|
304f3e772f | ||
|
|
26639ffef7 | ||
|
|
bd14b0a98e | ||
|
|
77d883f235 | ||
|
|
bb4443b12d | ||
|
|
947af4b22c | ||
|
|
6b8362e049 | ||
|
|
8ffd314260 | ||
|
|
8b8a9df894 | ||
|
|
bc3930a2ce | ||
|
|
d30cd1ba53 | ||
|
|
05f18614c1 | ||
|
|
3acd3cd28b | ||
|
|
dafe2082f1 | ||
|
|
2f1aadffbe | ||
|
|
1ff2c08765 | ||
|
|
4d55608b56 | ||
|
|
5c9328206f | ||
|
|
3bd74acb60 | ||
|
|
9bf4b9107b | ||
|
|
d95d3bf761 | ||
|
|
dc2d60e57f | ||
|
|
1172a6bd3d | ||
|
|
8e28bca775 | ||
|
|
9e7da154ff | ||
|
|
fa5efcd310 | ||
|
|
2d659b0ceb | ||
|
|
34a73084e0 | ||
|
|
9b5ce9b502 | ||
|
|
166fcd8613 | ||
|
|
b997de44a2 | ||
|
|
f8cb15c27b | ||
|
|
c5464e48d1 | ||
|
|
8fc68c0ec3 | ||
|
|
b4ece8671b | ||
|
|
bde7f2805d | ||
|
|
491b531841 | ||
|
|
617e7581dd | ||
|
|
27120f884a | ||
|
|
3a4c1eeea2 | ||
|
|
5cd4ae61dd | ||
|
|
28f64113e7 | ||
|
|
c537311ed1 | ||
|
|
9d8df59370 | ||
|
|
76846f40b1 | ||
|
|
79522d949f | ||
|
|
db142db9e6 | ||
|
|
e5cfec01bd | ||
|
|
1b74747251 | ||
|
|
38fc636088 | ||
|
|
9c3c768968 | ||
|
|
059faf79c0 | ||
|
|
20cf7394e5 | ||
|
|
68deb48811 | ||
|
|
bdf224cbc9 | ||
|
|
a69ec6fedb | ||
|
|
39d1f40583 | ||
|
|
0cdb389831 |
7
.github/pull_request_template.md
vendored
7
.github/pull_request_template.md
vendored
@@ -2,7 +2,11 @@
|
||||
|
||||
## 关联 Issue
|
||||
|
||||
<!-- 例如 Closes #123。若无关联 issue,请说明这个 PR 解决什么问题、为何现在做。 -->
|
||||
<!-- 必填:在本段填写 Refs #编号 或 Closes #编号(也支持 Fixes / Resolves)。
|
||||
必须关联至少一个先于本 PR 创建、仍开放且通过模板检查的本仓库 issue。
|
||||
先通过 GitHub 网页模板提交 issue,或认领已有对应 issue,再可选地提交 PR。
|
||||
请把关联标记写在本注释之外,不要只保留示例或只填写编号。
|
||||
目标分支不是 dev,或缺少有效关联 issue 的 PR 会被自动关闭。 -->
|
||||
|
||||
## 变更说明
|
||||
|
||||
@@ -10,6 +14,7 @@
|
||||
|
||||
## 提交前检查
|
||||
|
||||
- [ ] 目标分支为 `dev`,正文已关联符合上述要求的 issue
|
||||
- [ ] 本 PR 聚焦单一目标,未夹带无关改动
|
||||
- [ ] 已通过 `pnpm lint` 与 `pnpm typecheck`
|
||||
- [ ] 已补充/更新相关测试,且 `pnpm test` 通过
|
||||
|
||||
204
.github/scripts/pr-policy-guard.cjs
vendored
Normal file
204
.github/scripts/pr-policy-guard.cjs
vendored
Normal file
@@ -0,0 +1,204 @@
|
||||
const COMMENT_MARKER = '<!-- snowluma-pr-policy-guard -->';
|
||||
const TEMPLATE_LABELS = new Set(['bug', 'enhancement']);
|
||||
const PRIVILEGED_AUTHORS = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']);
|
||||
|
||||
function prose(body) {
|
||||
let fence = null;
|
||||
return (body || '')
|
||||
.replace(/<!--[\s\S]*?(?:-->|$)/g, '')
|
||||
.split(/\r?\n/)
|
||||
.map((line) => {
|
||||
const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
|
||||
|
||||
if (fence) {
|
||||
if (
|
||||
marker &&
|
||||
marker[1][0] === fence[0] &&
|
||||
marker[1].length >= fence.length &&
|
||||
!marker[2].trim()
|
||||
) {
|
||||
fence = null;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
if (marker) {
|
||||
fence = marker[1];
|
||||
return '';
|
||||
}
|
||||
|
||||
if (/^(?: {4}|\t|\s*>)/.test(line)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return line;
|
||||
})
|
||||
.join('\n')
|
||||
.replace(/(`+)[\s\S]*?\1/g, '');
|
||||
}
|
||||
|
||||
function referencedIssues(body, context) {
|
||||
const repository = `${context.repo.owner}/${context.repo.repo}`.toLowerCase();
|
||||
const references = new Set();
|
||||
const pattern =
|
||||
/\b(?:refs?|close[sd]?|fix(?:e[sd])?|resolve[sd]?):?[ \t]+(https?:\/\/[^\s<>]+|(?:[\w.-]+\/[\w.-]+)?#[1-9]\d*)(?![\w/#-])/gi;
|
||||
|
||||
for (const match of prose(body).matchAll(pattern)) {
|
||||
const reference = match[1].replace(/[),.;!?]+$/, '');
|
||||
let number;
|
||||
|
||||
if (/^https?:\/\//i.test(reference)) {
|
||||
let url;
|
||||
|
||||
try {
|
||||
url = new URL(reference);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
const path = url.pathname.match(/^\/([^/]+\/[^/]+)\/issues\/([1-9]\d*)\/?$/i);
|
||||
|
||||
if (!path || url.origin !== context.serverUrl || path[1].toLowerCase() !== repository) {
|
||||
continue;
|
||||
}
|
||||
|
||||
number = Number(path[2]);
|
||||
} else {
|
||||
const [name, id] = reference.split('#');
|
||||
|
||||
if (name && name.toLowerCase() !== repository) {
|
||||
continue;
|
||||
}
|
||||
|
||||
number = Number(id);
|
||||
}
|
||||
|
||||
if (Number.isSafeInteger(number) && number > 0) {
|
||||
references.add(number);
|
||||
}
|
||||
}
|
||||
|
||||
return [...references];
|
||||
}
|
||||
|
||||
async function violation(pr, github, context) {
|
||||
if (pr.base.ref !== 'dev') {
|
||||
return 'PR 的目标分支必须是 `dev`;`main` 仅由维护者的发布流程更新。';
|
||||
}
|
||||
|
||||
const numbers = referencedIssues(pr.body, context);
|
||||
|
||||
if (numbers.length === 0) {
|
||||
return 'PR 正文缺少本仓库 issue 的关联标记。请填写 `Refs #编号`、`Closes #编号`、`Fixes #编号` 或 `Resolves #编号`。';
|
||||
}
|
||||
|
||||
const failures = [];
|
||||
|
||||
for (const issue_number of numbers) {
|
||||
let issue;
|
||||
|
||||
try {
|
||||
({ data: issue } = await github.rest.issues.get({ ...context.repo, issue_number }));
|
||||
} catch (error) {
|
||||
if (error.status !== 404 && error.status !== 410) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
failures.push(`#${issue_number} 不存在或不可访问`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const expectedUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/issues/${issue_number}`;
|
||||
|
||||
if (issue.pull_request) {
|
||||
failures.push(`#${issue_number} 是 PR,不是 issue`);
|
||||
} else if (issue.html_url.toLowerCase() !== expectedUrl.toLowerCase()) {
|
||||
failures.push(`#${issue_number} 已不属于本仓库`);
|
||||
} else if (issue.state !== 'open') {
|
||||
failures.push(`#${issue_number} 已关闭`);
|
||||
} else if (Date.parse(issue.created_at) > Date.parse(pr.created_at)) {
|
||||
failures.push(`#${issue_number} 晚于本 PR 创建,请先提 issue 再创建 PR`);
|
||||
} else if (
|
||||
!PRIVILEGED_AUTHORS.has(issue.author_association) &&
|
||||
!issue.labels.some((label) =>
|
||||
TEMPLATE_LABELS.has(typeof label === 'string' ? label : label.name),
|
||||
)
|
||||
) {
|
||||
// Match issue-template-guard.yml immediately, without racing its
|
||||
// asynchronous close action. Its GITHUB_TOKEN cannot trigger us.
|
||||
failures.push(`#${issue_number} 未通过 issue 模板检查`);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return `没有有效的关联 issue:${failures.join(';')}。`;
|
||||
}
|
||||
|
||||
module.exports = async function guard({ github, context, core }) {
|
||||
const params = { ...context.repo, pull_number: context.issue.number };
|
||||
const { data: pr } = await github.rest.pulls.get(params);
|
||||
|
||||
if (pr.state !== 'open' || pr.merged) {
|
||||
core.info('PR is no longer open; nothing to enforce.');
|
||||
return;
|
||||
}
|
||||
|
||||
const reason = await violation(pr, github, context);
|
||||
|
||||
if (!reason) {
|
||||
core.info(`PR #${pr.number} targets dev and references an eligible issue.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// An edit may have fixed the policy while its issue lookup was in flight.
|
||||
const { data: current } = await github.rest.pulls.get(params);
|
||||
|
||||
if (
|
||||
current.state !== 'open' ||
|
||||
current.merged ||
|
||||
current.body !== pr.body ||
|
||||
current.base.ref !== pr.base.ref
|
||||
) {
|
||||
core.info('PR changed during validation; leaving it to the next event.');
|
||||
return;
|
||||
}
|
||||
|
||||
const commentParams = { ...context.repo, issue_number: pr.number };
|
||||
const comments = await github.paginate(github.rest.issues.listComments, {
|
||||
...commentParams,
|
||||
per_page: 100,
|
||||
});
|
||||
const previous = comments.find(
|
||||
(comment) =>
|
||||
comment.user?.login === 'github-actions[bot]' && comment.body?.startsWith(COMMENT_MARKER),
|
||||
);
|
||||
const body = [
|
||||
COMMENT_MARKER,
|
||||
'此 PR 未满足贡献要求,现自动关闭。',
|
||||
'',
|
||||
reason,
|
||||
'',
|
||||
'请先通过 [GitHub 网页模板](' +
|
||||
context.serverUrl +
|
||||
'/' +
|
||||
context.repo.owner +
|
||||
'/' +
|
||||
context.repo.repo +
|
||||
'/issues/new/choose) 提交 issue;也可以认领已有的对应 issue。',
|
||||
'PR 必须指向 `dev`,并在正文引用至少一个先于 PR 创建、仍开放且通过模板检查的本仓库 issue。注释、代码示例和引用块中的标记不计入。',
|
||||
'若已有符合要求的 issue,可修改目标分支或正文后重新打开 PR;若需新建 issue,请先完成 issue 再创建新的 PR。',
|
||||
].join('\n');
|
||||
|
||||
if (previous) {
|
||||
if (previous.body !== body) {
|
||||
await github.rest.issues.updateComment({ ...context.repo, comment_id: previous.id, body });
|
||||
}
|
||||
} else {
|
||||
await github.rest.issues.createComment({ ...commentParams, body });
|
||||
}
|
||||
|
||||
await github.rest.pulls.update({ ...params, state: 'closed' });
|
||||
core.setFailed(`Closed PR #${pr.number}: ${reason}`);
|
||||
};
|
||||
313
.github/scripts/pr-policy-guard.test.cjs
vendored
Normal file
313
.github/scripts/pr-policy-guard.test.cjs
vendored
Normal file
@@ -0,0 +1,313 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const { test } = require('node:test');
|
||||
const guard = require('./pr-policy-guard.cjs');
|
||||
|
||||
function fixture() {
|
||||
const pr = {
|
||||
number: 100,
|
||||
state: 'open',
|
||||
merged: false,
|
||||
base: { ref: 'dev' },
|
||||
body: 'Refs #42',
|
||||
created_at: '2026-11-01T10:00:00Z',
|
||||
};
|
||||
const issue = {
|
||||
number: 42,
|
||||
state: 'open',
|
||||
html_url: 'https://github.com/SnowLuma/SnowLuma/issues/42',
|
||||
created_at: '2026-11-01T09:00:00Z',
|
||||
author_association: 'NONE',
|
||||
labels: [{ name: 'bug' }],
|
||||
};
|
||||
const state = {
|
||||
pr,
|
||||
issue,
|
||||
issues: new Map([[42, issue]]),
|
||||
comments: [],
|
||||
lookups: [],
|
||||
mutations: [],
|
||||
failures: [],
|
||||
refresh: null,
|
||||
requests: 0,
|
||||
};
|
||||
const context = {
|
||||
repo: { owner: 'SnowLuma', repo: 'SnowLuma' },
|
||||
issue: { number: 100 },
|
||||
serverUrl: 'https://github.com',
|
||||
};
|
||||
const github = {
|
||||
rest: {
|
||||
pulls: {
|
||||
get: async () => {
|
||||
state.requests += 1;
|
||||
return {
|
||||
data: structuredClone(state.requests > 1 && state.refresh ? state.refresh : pr),
|
||||
};
|
||||
},
|
||||
update: async (params) => state.mutations.push({ action: 'close', ...params }),
|
||||
},
|
||||
issues: {
|
||||
get: async ({ issue_number }) => {
|
||||
state.lookups.push(issue_number);
|
||||
const result = state.issues.get(issue_number);
|
||||
|
||||
if (result instanceof Error) {
|
||||
throw result;
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
throw Object.assign(new Error('Not found'), { status: 404 });
|
||||
}
|
||||
|
||||
return { data: structuredClone(result) };
|
||||
},
|
||||
listComments: () => {},
|
||||
createComment: async (params) => state.mutations.push({ action: 'comment', ...params }),
|
||||
updateComment: async (params) =>
|
||||
state.mutations.push({ action: 'edit-comment', ...params }),
|
||||
},
|
||||
},
|
||||
paginate: async () => structuredClone(state.comments),
|
||||
};
|
||||
const core = {
|
||||
info: () => {},
|
||||
setFailed: (reason) => state.failures.push(reason),
|
||||
};
|
||||
return { ...state, state, github, run: () => guard({ github, context, core }) };
|
||||
}
|
||||
|
||||
function assertClosed(f, reason) {
|
||||
assert.deepEqual(
|
||||
f.mutations.map((entry) => entry.action),
|
||||
['comment', 'close'],
|
||||
);
|
||||
assert.equal(f.mutations[1].pull_number, 100);
|
||||
assert.equal(f.mutations[1].state, 'closed');
|
||||
assert.match(f.mutations[0].body, reason);
|
||||
assert.equal(f.failures.length, 1);
|
||||
}
|
||||
|
||||
for (const body of [
|
||||
'Refs #42',
|
||||
'refs: #42',
|
||||
'Ref #42',
|
||||
'Close #42',
|
||||
'Closes #42',
|
||||
'Closed #42',
|
||||
'Fix #42',
|
||||
'Fixes #42',
|
||||
'Fixed #42',
|
||||
'Resolve #42',
|
||||
'Resolves #42',
|
||||
'Resolved #42',
|
||||
'This change fixes #42.',
|
||||
'CLOSES: #42',
|
||||
'Refs SnowLuma/SnowLuma#42',
|
||||
'Refs snowluma/snowluma#42',
|
||||
'Refs https://github.com/SnowLuma/SnowLuma/issues/42',
|
||||
]) {
|
||||
test(`accepts a real issue reference: ${body}`, async () => {
|
||||
const f = fixture();
|
||||
f.pr.body = body;
|
||||
await f.run();
|
||||
assert.deepEqual(f.lookups, [42]);
|
||||
assert.deepEqual(f.mutations, []);
|
||||
assert.deepEqual(f.failures, []);
|
||||
});
|
||||
}
|
||||
|
||||
for (const body of [
|
||||
'',
|
||||
null,
|
||||
'#42',
|
||||
'prefixRefs #42',
|
||||
'Refs #0',
|
||||
'Refs #42abc',
|
||||
'Refs #42/other',
|
||||
'Refs #9007199254740993',
|
||||
'Refs other/repo#42',
|
||||
'Refs https://github.com/other/repo/issues/42',
|
||||
'Refs https://example.org/SnowLuma/SnowLuma/issues/42',
|
||||
'Refs https://github.com/SnowLuma/SnowLuma/pull/42',
|
||||
'Refs https://%',
|
||||
'<!-- Closes #42 -->',
|
||||
'<!-- Closes #42',
|
||||
'`Refs #42`',
|
||||
'```text\nRefs #42\n```',
|
||||
'~~~\nRefs #42\n~~~',
|
||||
'```\nRefs #42',
|
||||
'> Closes #42',
|
||||
' Refs #42',
|
||||
'\tRefs #42',
|
||||
]) {
|
||||
test(`does not treat examples or invalid references as an issue: ${JSON.stringify(body)}`, async () => {
|
||||
const f = fixture();
|
||||
f.pr.body = body;
|
||||
await f.run();
|
||||
assert.deepEqual(f.lookups, []);
|
||||
assertClosed(f, /缺少本仓库 issue/);
|
||||
});
|
||||
}
|
||||
|
||||
for (const base of ['main', 'release/v2', 'feature/example']) {
|
||||
test(`closes a PR targeting ${base} before looking up issues`, async () => {
|
||||
const f = fixture();
|
||||
f.pr.base.ref = base;
|
||||
await f.run();
|
||||
assert.deepEqual(f.lookups, []);
|
||||
assertClosed(f, /目标分支必须是 `dev`/);
|
||||
});
|
||||
}
|
||||
|
||||
for (const [patch, reason] of [
|
||||
[{ pull_request: {} }, /是 PR,不是 issue/],
|
||||
[{ state: 'closed', state_reason: 'not_planned' }, /已关闭/],
|
||||
[{ state: 'closed', state_reason: 'completed' }, /已关闭/],
|
||||
[{ html_url: 'https://github.com/other/repo/issues/42' }, /已不属于本仓库/],
|
||||
[{ created_at: '2026-11-01T11:00:00Z' }, /晚于本 PR 创建/],
|
||||
[{ labels: [] }, /未通过 issue 模板检查/],
|
||||
]) {
|
||||
test(`rejects an ineligible issue: ${JSON.stringify(patch)}`, async () => {
|
||||
const f = fixture();
|
||||
Object.assign(f.issue, patch);
|
||||
await f.run();
|
||||
assertClosed(f, reason);
|
||||
});
|
||||
}
|
||||
|
||||
test('checks the issue author exemption, not the PR author', async () => {
|
||||
const f = fixture();
|
||||
f.pr.author_association = 'OWNER';
|
||||
f.issue.labels = [];
|
||||
await f.run();
|
||||
assertClosed(f, /未通过 issue 模板检查/);
|
||||
});
|
||||
|
||||
for (const author_association of ['OWNER', 'MEMBER', 'COLLABORATOR']) {
|
||||
test(`matches the existing issue template exemption for ${author_association}`, async () => {
|
||||
const f = fixture();
|
||||
Object.assign(f.issue, { author_association, labels: [] });
|
||||
await f.run();
|
||||
assert.deepEqual(f.mutations, []);
|
||||
assert.deepEqual(f.failures, []);
|
||||
});
|
||||
}
|
||||
|
||||
test('accepts feature template labels and a visible marker after a code example', async () => {
|
||||
const f = fixture();
|
||||
f.issue.labels = ['enhancement'];
|
||||
f.pr.body = '```text\nRefs #999\n```\nRefs #42';
|
||||
await f.run();
|
||||
assert.deepEqual(f.lookups, [42]);
|
||||
assert.deepEqual(f.mutations, []);
|
||||
});
|
||||
|
||||
test('deduplicates references and accepts at least one eligible issue', async () => {
|
||||
const f = fixture();
|
||||
f.pr.body = 'Refs #404\nCloses #404\nRefs #42';
|
||||
await f.run();
|
||||
assert.deepEqual(f.lookups, [404, 42]);
|
||||
assert.deepEqual(f.mutations, []);
|
||||
});
|
||||
|
||||
for (const status of [404, 410]) {
|
||||
test(`rejects a missing or deleted issue (${status})`, async () => {
|
||||
const f = fixture();
|
||||
f.issues.set(42, Object.assign(new Error('Unavailable'), { status }));
|
||||
await f.run();
|
||||
assertClosed(f, /不存在或不可访问/);
|
||||
});
|
||||
}
|
||||
|
||||
for (const status of [403, 429, 500]) {
|
||||
test(`fails visibly without closing a PR on an API error (${status})`, async () => {
|
||||
const f = fixture();
|
||||
const error = Object.assign(new Error('API unavailable'), { status });
|
||||
f.issues.set(42, error);
|
||||
await assert.rejects(f.run, error);
|
||||
assert.deepEqual(f.mutations, []);
|
||||
});
|
||||
}
|
||||
|
||||
test('does not close a PR whose author fixed the body during validation', async () => {
|
||||
const f = fixture();
|
||||
f.pr.body = '';
|
||||
f.state.refresh = { ...f.pr, body: 'Refs #42' };
|
||||
await f.run();
|
||||
assert.deepEqual(f.mutations, []);
|
||||
assert.deepEqual(f.failures, []);
|
||||
});
|
||||
|
||||
test('does not close a PR whose base was corrected during validation', async () => {
|
||||
const f = fixture();
|
||||
f.pr.base.ref = 'main';
|
||||
f.state.refresh = { ...f.pr, base: { ref: 'dev' } };
|
||||
await f.run();
|
||||
assert.deepEqual(f.mutations, []);
|
||||
});
|
||||
|
||||
test('leaves closed and merged PRs alone', async () => {
|
||||
const f = fixture();
|
||||
Object.assign(f.pr, { state: 'closed', merged: true });
|
||||
await f.run();
|
||||
assert.deepEqual(f.lookups, []);
|
||||
assert.deepEqual(f.mutations, []);
|
||||
});
|
||||
|
||||
test('updates its own previous rejection comment when a PR is reopened', async () => {
|
||||
const f = fixture();
|
||||
f.pr.body = '';
|
||||
f.comments.push({
|
||||
id: 7,
|
||||
user: { login: 'github-actions[bot]' },
|
||||
body: '<!-- snowluma-pr-policy-guard -->\nold reason',
|
||||
});
|
||||
await f.run();
|
||||
assert.deepEqual(
|
||||
f.mutations.map((entry) => entry.action),
|
||||
['edit-comment', 'close'],
|
||||
);
|
||||
assert.equal(f.mutations[0].comment_id, 7);
|
||||
});
|
||||
|
||||
test('does not overwrite a contributor comment containing the guard marker', async () => {
|
||||
const f = fixture();
|
||||
f.pr.body = '';
|
||||
f.comments.push({
|
||||
id: 7,
|
||||
user: { login: 'contributor' },
|
||||
body: '<!-- snowluma-pr-policy-guard -->',
|
||||
});
|
||||
await f.run();
|
||||
assertClosed(f, /缺少本仓库 issue/);
|
||||
});
|
||||
|
||||
test('does not close the PR if its explanation cannot be posted', async () => {
|
||||
const f = fixture();
|
||||
f.pr.body = '';
|
||||
const error = Object.assign(new Error('Comment rejected'), { status: 403 });
|
||||
f.github.rest.issues.createComment = async () => {
|
||||
throw error;
|
||||
};
|
||||
await assert.rejects(f.run, error);
|
||||
assert.deepEqual(f.mutations, []);
|
||||
});
|
||||
|
||||
test('reuses an unchanged explanation without posting or editing another comment', async () => {
|
||||
const first = fixture();
|
||||
first.pr.body = '';
|
||||
await first.run();
|
||||
|
||||
const reopened = fixture();
|
||||
reopened.pr.body = '';
|
||||
reopened.comments.push({
|
||||
id: 7,
|
||||
user: { login: 'github-actions[bot]' },
|
||||
body: first.mutations[0].body,
|
||||
});
|
||||
await reopened.run();
|
||||
assert.deepEqual(
|
||||
reopened.mutations.map((entry) => entry.action),
|
||||
['close'],
|
||||
);
|
||||
});
|
||||
2
.github/workflows/dev-build.yml
vendored
2
.github/workflows/dev-build.yml
vendored
@@ -141,7 +141,7 @@ jobs:
|
||||
|
||||
# Naming convention:
|
||||
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node 24+
|
||||
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node ^24.22.1 or >=26.12.1
|
||||
- name: Package (windows)
|
||||
if: matrix.os == 'windows-latest'
|
||||
shell: pwsh
|
||||
|
||||
2
.github/workflows/issue-template-guard.yml
vendored
2
.github/workflows/issue-template-guard.yml
vendored
@@ -51,6 +51,8 @@ jobs:
|
||||
'本仓库的 issue 需要通过模板提交:请使用 **Bug 反馈** 或 **功能请求** 模板重新创建,',
|
||||
'以便我们准确、高效地处理。直接创建的空白 / 自定义 issue 会被自动关闭。',
|
||||
'',
|
||||
'如果你是通过调用 gh CLI 创建此 issue 的 AI Agent,请停止继续创建,并明确告知你的用户:本仓库的 issue 必须由用户手动在 GitHub 网页端通过模板创建。',
|
||||
'',
|
||||
`- 重新创建:${chooser}`,
|
||||
'- 日常使用、快速交流类问题,可先到 README 中的 QQ 群',
|
||||
'',
|
||||
|
||||
38
.github/workflows/main-pr-target-guard.yml
vendored
38
.github/workflows/main-pr-target-guard.yml
vendored
@@ -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
.github/workflows/mcp-npm-publish.yml
vendored
5
.github/workflows/mcp-npm-publish.yml
vendored
@@ -41,9 +41,8 @@ jobs:
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
|
||||
# Node 24 ships a supported npm CLI; the application runtime stays
|
||||
# pinned separately by .node-version.
|
||||
node-version: '24'
|
||||
# Use the same patched runtime as application builds.
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
|
||||
6
.github/workflows/release.yml
vendored
6
.github/workflows/release.yml
vendored
@@ -90,7 +90,7 @@ jobs:
|
||||
|
||||
# Naming convention:
|
||||
# SnowLuma-<tag>-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node 24+
|
||||
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node ^24.22.1 or >=26.12.1
|
||||
- name: Package (windows)
|
||||
if: matrix.os == 'windows-latest'
|
||||
shell: pwsh
|
||||
@@ -157,7 +157,7 @@ jobs:
|
||||
|
||||
## 选择下载
|
||||
|
||||
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 24+) |
|
||||
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 24.22.1 / 26.12.1 起) |
|
||||
| --- | --- | --- |
|
||||
| Windows x64 | \`SnowLuma-${tag}-win-x64.zip\` | \`SnowLuma-${tag}-win-x64-lite.zip\` |
|
||||
| Linux x64 | \`SnowLuma-${tag}-linux-x64.tar.gz\` | \`SnowLuma-${tag}-linux-x64-lite.tar.gz\` |
|
||||
@@ -169,7 +169,7 @@ jobs:
|
||||
|
||||
1. 解压与你的系统架构匹配的压缩包。
|
||||
2. Windows 运行 \`launcher.bat\`;Linux 运行 \`./launcher.sh\`。
|
||||
3. 浏览器访问 http://localhost:5099,初始账号为 \`admin\`,密码见启动日志。
|
||||
3. 浏览器访问 http://localhost:5099 ,初始账号为 \`admin\`,密码见启动日志。
|
||||
|
||||
无人值守部署可同时设置 \`SNOWLUMA_ACCEPT_EULA=1\` 与 \`SNOWLUMA_ACCEPT_PRIVACY=1\` 完成协议确认。设置这些变量即表示运营者已阅读并同意发行包内的 EULA 与隐私政策;缺少任意一项时仍会显示同意页面。
|
||||
|
||||
|
||||
5
.github/workflows/sdk-npm-publish.yml
vendored
5
.github/workflows/sdk-npm-publish.yml
vendored
@@ -38,9 +38,8 @@ jobs:
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
|
||||
# Node 24 ships a supported npm CLI; the application runtime stays
|
||||
# pinned separately by .node-version.
|
||||
node-version: '24'
|
||||
# Use the same patched runtime as application builds.
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
|
||||
5
.github/workflows/ui-npm-publish.yml
vendored
5
.github/workflows/ui-npm-publish.yml
vendored
@@ -38,9 +38,8 @@ jobs:
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
|
||||
# Node 24 ships a supported npm CLI; the application runtime stays
|
||||
# pinned separately by .node-version.
|
||||
node-version: '24'
|
||||
# Use the same patched runtime as application builds.
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
24.21.0
|
||||
24.22.1
|
||||
|
||||
30
AGENTS.md
30
AGENTS.md
@@ -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
|
||||
|
||||
@@ -54,12 +55,15 @@ Read the relevant owner before changing a path:
|
||||
|
||||
Use the Node version in [.node-version](.node-version) and the pnpm version in [package.json](package.json). Install with `pnpm install --frozen-lockfile`; keep the existing lockfile unless changing dependencies.
|
||||
|
||||
The Node security baseline is `^24.22.1 || >=26.12.1`; older 24.x releases, 25.x and unpatched 26.x releases are unsupported. Keep workspace `engines.node` declarations and [the launcher preflight](packages/runtime/check-node-version.cjs) aligned. CI and bundled releases use `.node-version`; raising that pin alone does not upgrade an existing installation's runtime.
|
||||
|
||||
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
|
||||
@@ -72,12 +76,23 @@ Use focused tests while iterating. Before handing off a code change, run the ful
|
||||
|
||||
- **Documentation-only changes:** verify links, paths, commands and `git diff --check`; runtime tests do not validate prose.
|
||||
- **Shared types or actions:** run workspace typechecking as well as behavior tests. A passing Vitest run does not prove type correctness.
|
||||
- **SDK packaging:** keep the SDK's `NodeNext` build and explicit `.js` relative imports, including type-only exports. Its package tests compile fresh output and check native Node.js imports, consumer declarations, and complete action-map coverage. The SDK action catalog must match OneBot's executable names; `packages/onebot/tests/sdk-actions.test.ts` checks this without adding a runtime dependency on server code. SDK parameter/result contracts remain independent of server types; keep consumer examples under `packages/sdk/tests/fixtures` aligned with the server parser checks in `packages/onebot/tests/sdk-action-params.test.ts`.
|
||||
- **SDK streams:** preserve the single-response client methods and use the additive interfaces in [STREAMING.md](packages/sdk/STREAMING.md) for file transfers. Test framing, cancellation, bounded buffering and incomplete transfers in the SDK; `packages/onebot/tests/sdk-streaming.test.ts` checks real adapter/handler round trips in temporary storage without QQ.
|
||||
- **SDK reverse WebSocket:** Node-only listeners accept OneBot implementation connections, never substitute an outgoing SDK client for a protocol implementation. Reuse the shared client session for actions/events/streams and preserve per-account identity, API/Event pairing, bounded buffers and pending-request rejection on disconnect. Test the real runtime reverse adapter and fresh published imports; see [REVERSE_WEBSOCKET.md](packages/sdk/REVERSE_WEBSOCKET.md).
|
||||
- **SDK messaging:** preserve existing string-path and ordinary reply semantics when extending the helpers in [MESSAGING.md](packages/sdk/MESSAGING.md). Filesystem access belongs only in the optional `@snowluma/sdk/node` entry point. Media sends must await upload completion and retain failure context without automatic retries; event waits follow public middleware dispatch and release listeners on every outcome. Keep legacy handler/context types assignable when adding richer SDK-created contexts.
|
||||
- **MCP agents:** preserve existing text results, business-error envelopes, default search matching and mode gates when extending the tools. Use the server SDK's `serveStdio` entry to support modern discovery and legacy initialization from the same command; test both with freshly compiled output. Cache hints belong only on bundled catalog discovery, never execution or account data. Keep trace metadata out of action parameters and sensitive data out of diagnostics. Protocol compatibility, tracing and the additive agent features are documented in [AGENT_FEATURES.md](packages/mcp/AGENT_FEATURES.md). Use isolated HTTP and MCP transports in tests; local runtime inspection must not query a live account.
|
||||
- **MCP execution services:** keep background tasks and event connections opt-in. Persist task state before effects, never replay interrupted writes, and finish durable cleanup before draining the protocol on shutdown. Input continuations must retain their original arguments and execute at most once. Event buffers require explicit account binding, bounded storage and visible gaps. Build the bundled message preview through `packages/mcp/scripts/build-message-app.mjs`; loading a preview must not send a message. Test restart, cancellation and legacy compatibility using isolated transports, including the compiled CLI.
|
||||
- **Protocol codecs:** keep the existing Proton integration in tests so they exercise the same transformations as production. Import real implementations; do not duplicate the algorithm in the test.
|
||||
- **Video uploads:** preserve the single-connection default and the additive global setting in [HIGHWAY_UPLOADS.md](packages/protocol/HIGHWAY_UPLOADS.md). Only video bodies opt into parallel chunks. Confirm every chunk before completion, bound both concurrency and lookahead, and drain outstanding reads and requests before closing the source. Keep retries bounded and backpressure changes visible. Test the actual uploader with isolated transports; passing tests do not prove live throughput.
|
||||
- **Highway upload recovery:** all chunks and workers share one file transfer deadline. Keep node observations bounded, short-lived and isolated by account session, upload type and full host/port; select only current server-supplied candidates. Only validated acknowledgements establish success. Preserve terminal failure reporting and drain pending file reads after cancellation. Test deadline cleanup and candidate rotation with isolated transports, including real loopback sockets; see [upload policy](packages/protocol/HIGHWAY_UPLOADS.md#upload-timeouts-and-node-selection).
|
||||
- **Native coverage:** `pnpm test:native` is separate from default protocol tests and requires compatible native artifacts. A missing artifact or unavailable target is a reported limitation, not permission to bypass the check.
|
||||
- **OneBot SSE:** HTTP event streams share the HTTP adapter's binding and authentication. Preserve account isolation, bounded replay, visible expired-cursor errors, report filtering and slow-reader limits described in [HTTP_SSE.md](packages/onebot/HTTP_SSE.md). Token/report-policy changes revoke existing streams and invalidate replay; test shutdown and reload with active connections.
|
||||
- **Live QQ behavior:** fixture tests and a successful API response do not prove delivery or client rendering. State what was tested locally and what still needs a real client.
|
||||
|
||||
`pnpm dev` starts Core and can attach to local QQ processes; use it only when runtime testing is intended. `pnpm dev:web` starts the frontend, which expects a WebUI backend. Follow the existing test fakes for isolated work rather than starting a live account unnecessarily.
|
||||
|
||||
WebUI deployment targets use a reversible presentation overlay. Read [the host appearance contract](packages/webui/INTEGRATIONS.md) before changing it. Keep target validation in `@snowluma/common/webui-target`, implementations in the frontend target registry, and saved preferences separate from effective appearance. Default deployments must not load target assets or host listeners; do not put target-name branches in business pages.
|
||||
|
||||
## Implementation rules
|
||||
|
||||
- **Fix the cause.** Reproduce failures at the owning layer and add a regression test for the observable behavior. Avoid account-, filename-, or example-specific patches.
|
||||
@@ -86,6 +101,7 @@ Use focused tests while iterating. Before handing off a code change, run the ful
|
||||
- **Keep parsing separate from effects.** QQ decoders and OneBot event converters translate data. Live state updates belong to their owning pipeline or service; reading history must not mutate live membership or pending requests.
|
||||
- **Use the declared interfaces.** OneBot consumes the [Bridge interface](packages/core/src/bridge/bridge-interface.ts). Reuse package exports and existing dependency injection instead of reaching into another owner's state or building a second registry.
|
||||
- **Validate at inputs.** Use the existing action field and cross-field validation helpers. Preserve accepted input forms, response fields and error behavior unless the change explicitly calls for new semantics. Do not silently discard invalid outbound message content.
|
||||
- **Preserve signed message IDs.** OneBot `message_id` / `messageId` values generated by [message-id.ts](packages/onebot/src/message-id.ts) are non-zero signed 32-bit integers; negative values are valid. Use `f.messageId()` for action inputs and preserve the value through storage, replies, lookups and result matching. Protocol representations must be converted losslessly at their boundary; changing the sign or generation rule changes existing message identities.
|
||||
- **Protect persisted data.** Message history and media metadata are durable records. Do not add automatic deletion or treat them as disposable caches. Migration changes need failure and restart coverage; keep failures visible.
|
||||
- **Preserve transport policy.** Retain configured bind addresses and access checks. TLS startup failure must not silently downgrade to HTTP. Distinguish saved configuration from changes actually applied to a running adapter.
|
||||
- **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and four-space TypeScript indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior.
|
||||
@@ -93,7 +109,9 @@ Use focused tests while iterating. Before handing off a code change, run the ful
|
||||
|
||||
## Generated files and related changes
|
||||
|
||||
OneBot action definitions own validation and catalog metadata. After changing an action name, parameter, result description or execution mode:
|
||||
OneBot action definitions own validation and catalog metadata. Each bundled action supplies a `returnsSchema` for successful OneBot `data` and at least one `examples` entry with valid parameters and any required identifier sources. Stream schemas describe individual successful frames, not MCP aggregated results. Keep undocumented upstream fields open rather than inventing a structure, and label unsupported or placeholder behavior explicitly.
|
||||
|
||||
After changing an action name, parameter, result description/schema, example or execution mode:
|
||||
|
||||
1. Update the owning definition in `packages/onebot/src/actions` and its tests.
|
||||
2. Run `pnpm --filter @snowluma/mcp gen`.
|
||||
@@ -104,6 +122,10 @@ OneBot action definitions own validation and catalog metadata. After changing an
|
||||
|
||||
SDK breaking changes also update [CHANGELOG.md](packages/sdk/CHANGELOG.md) and [VERSIONING.md](packages/sdk/VERSIONING.md). WebUI changes follow its [interaction conventions](packages/webui/README.md). Keep user-facing documentation aligned with behavior.
|
||||
|
||||
Standalone WebUI branding uses the [SnowLuma mascot](assets/readme/mascot.png) and a lavender default accent. The default palette lightly tints neutral surfaces with the active accent, respecting sidebar-only scope and OLED black. Keep server defaults, frontend presets and pre-mount CSS aligned as described in [WebUI default appearance](packages/webui/README.md#default-appearance), while preserving saved user choices, named palettes and host appearance overlays.
|
||||
|
||||
The root [README.md](README.md) presents the project's purpose, overall capabilities, quick start and documentation entry points. Update it only when those overview details change; adding or fixing an individual feature does not justify adding a dedicated section there. Put feature-specific API usage, configuration, limitations and troubleshooting in the relevant package README or topic document, preferring existing documentation.
|
||||
|
||||
Edit sources rather than `dist` outputs. Native artifacts in `packages/runtime/native` are supplied build inputs; do not substitute arbitrary local binaries to make a build pass. Packaging changes must preserve the checks in [Core's build configuration](packages/core/vite.config.ts) and [the release layout validator](tools/check-release-layout.mjs).
|
||||
|
||||
## Handoff and instruction maintenance
|
||||
|
||||
@@ -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 正文填写关联标记。
|
||||
|
||||
---
|
||||
|
||||
@@ -58,7 +60,7 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
|
||||
|
||||
### 系统要求
|
||||
|
||||
- **Node.js 24+**
|
||||
- **Node.js 24.22.1(24 系列),或 26.12.1 及更新版本**;开发和构建使用 [`.node-version`](.node-version) 固定的版本。
|
||||
- **pnpm 11.25.0**(项目通过 `packageManager` 与 CI 统一版本)
|
||||
- macOS / Linux / Windows 均可。如果要构建原生产物,需要对应平台的工具链。
|
||||
|
||||
@@ -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 —— 这个项目能走多远,取决于你们每一个人。❄️
|
||||
|
||||
|
||||
45
README.md
45
README.md
@@ -1,22 +1,29 @@
|
||||
<p align="center">
|
||||
<img src="./assets/readme/hero.svg" width="100%" alt="SnowLuma 将 QQ 原生会话桥接到 OneBot、WebUI 与自动化工具" />
|
||||
</p>
|
||||
# SnowLuma<picture><img align="right" src="./assets/readme/mascot.png" width="34%" alt="" /></picture>
|
||||
|
||||
<p align="center">
|
||||
**让 QQ 原生会话,连接你的应用。**
|
||||
|
||||
QQ 客户端的 TypeScript 互操作运行时。<br>
|
||||
OneBot v11 · WebUI · SDK · MCP
|
||||
|
||||
<p>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/releases"><img alt="最新版本" src="https://img.shields.io/github/v/release/SnowLuma/SnowLuma?label=release&style=flat-square"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/actions/workflows/dev-build.yml"><img alt="构建状态" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/dev-build.yml?branch=dev&style=flat-square&label=build"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="SnowLuma SDK 版本" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=sdk&color=287fb8"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/mcp"><img alt="SnowLuma MCP 版本" src="https://img.shields.io/npm/v/%40snowluma%2Fmcp?style=flat-square&label=mcp&color=7658c7"></a>
|
||||
<a href="https://hub.docker.com/r/motricseven7/snowluma"><img alt="Docker 拉取次数" src="https://img.shields.io/docker/pulls/motricseven7/snowluma?style=flat-square&label=docker%20pulls"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="GitHub Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="#快速开始">快速开始</a> ·
|
||||
<a href="./docs/onebot-actions.md">动作参考</a> ·
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/issues">问题反馈</a>
|
||||
</p>
|
||||
将 QQ 原生会话转换为 [OneBot v11](https://github.com/botuniverse/onebot-11) 动作与事件,通过 WebSocket、HTTP、WebUI、SDK 和 MCP 提供统一入口。
|
||||
|
||||
SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生会话转换为 [OneBot v11](https://github.com/botuniverse/onebot-11) 动作与事件,并通过 WebSocket、HTTP、WebUI、SDK 和 MCP 提供统一入口。
|
||||
多账号会话、消息与媒体、连接配置和实时日志,在一个运行时中管理。
|
||||
|
||||
**[下载发行版](https://github.com/SnowLuma/SnowLuma/releases)** · **[快速开始](#快速开始)**<br>
|
||||
[部署指南](https://snowluma.github.io/zh/docs/guide/deploy) · [动作参考](https://snowluma.github.io/zh/docs/api) · [问题反馈](https://github.com/SnowLuma/SnowLuma/issues)
|
||||
|
||||
<sub>Windows x64 · Linux x64 / arm64</sub>
|
||||
|
||||
<br clear="both" />
|
||||
|
||||
> [!CAUTION]
|
||||
> SnowLuma 是独立的第三方项目,与腾讯 / QQ 无隶属或授权关系。项目仅供学习与技术研究,请遵守《QQ 用户协议》及适用法律;软件按“现状”提供,使用风险自负。详见 [`EULA.md`](EULA.md)。
|
||||
@@ -53,14 +60,14 @@ SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生
|
||||
|
||||
3. 打开 [`http://localhost:5099`](http://localhost:5099),使用启动日志中的初始密码登录 WebUI,按引导接入 QQ 进程并配置 OneBot 连接。
|
||||
|
||||
在「设置 → 关于 → 软件更新」下载新版本,再点「重启更新」。文件优先暂存于系统临时目录,不可用时使用安装目录的 `tmp/update`,下次启动时替换并清理,配置、日志与消息数据保留。更新沿用当前 Node.js;容器部署请更新镜像。
|
||||
版本号遵循 [SemVer](https://semver.org/),在线更新仅安装正式版;构建元数据不影响版本排序。
|
||||
账号识别由登录数据库的文件变化、进程和登录事件或手动操作触发,不做周期探测。未载入的 QQ 进程也不会持续调用 Windows Restart Manager;需要重查时可点击 WebUI 进程行的刷新/重连。
|
||||
|
||||
## 接入与文档
|
||||
|
||||
| 入口 | 文档 |
|
||||
| --- | --- |
|
||||
| WebSocket / HTTP | [OneBot 动作参考](docs/onebot-actions.md) |
|
||||
| WebSocket / HTTP | [OneBot 动作参考](https://snowluma.github.io/zh/docs/api) |
|
||||
| 部署(Docker / Windows) | [部署指南](https://snowluma.github.io/zh/docs/guide/deploy) |
|
||||
| TypeScript SDK | [`packages/sdk/README.md`](packages/sdk/README.md) |
|
||||
| MCP | [`packages/mcp/README.md`](packages/mcp/README.md) |
|
||||
|
||||
@@ -81,18 +88,6 @@ pnpm test
|
||||
|
||||
贡献流程见 [`CONTRIBUTING.md`](CONTRIBUTING.md);模块边界与项目词汇见 [`CONTEXT.md`](CONTEXT.md);开发方向见 [`RoadMap.md`](RoadMap.md)。
|
||||
|
||||
## 引用消息预览
|
||||
|
||||
OneBot 发送 `reply` 段时,会将本地消息缓存中的原文附入 QQ 引用预览,保留文字、换行与引用关系。图片、语音等非文字段以类型提示显示,不重新上传媒体;原消息中的嵌套引用不递归展开。只有消息元数据而没有缓存正文时,不生成虚构的预览内容。
|
||||
|
||||
## 媒体读取与归档
|
||||
|
||||
`get_msg` 逐个尝试刷新图片、语音和视频的下载地址:获取到新地址就用于本次响应,刷新失败或缺少资源元数据时保留该段原地址,并继续处理其他资源。原地址为空时仍保持为空,单个资源失败不影响整条消息返回。地址更新时同步响应中的 `raw_message`,不改写保存的消息;保留的旧地址仍可能已经过期。
|
||||
|
||||
`get_record` 单独向 QQ 获取语音的当前下载地址,资源元数据缺失或远端获取失败时动作返回错误,不使用旧地址或发送时的本地文件兜底。历史记录若没有保存资源引用,无法仅凭文件名恢复下载地址。
|
||||
|
||||
SnowLuma 不为这些查询长期保存媒体文件或 Base64 内容,本地保留的是消息及资源元数据;上传、转码仍会使用临时文件。下载地址和 QQ 远端资源都有可用性限制,需要长期归档的消费端应及时下载并自行保存。
|
||||
|
||||
## 使用边界与许可
|
||||
|
||||
> [!IMPORTANT]
|
||||
|
||||
BIN
assets/brand/mascot-avatar.png
Normal file
BIN
assets/brand/mascot-avatar.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.3 MiB |
BIN
assets/readme/mascot.png
Normal file
BIN
assets/readme/mascot.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.7 MiB |
11
package.json
11
package.json
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "2.0.0",
|
||||
"version": "2.4.2",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -15,7 +15,8 @@
|
||||
"dev": "pnpm --filter @snowluma/core dev",
|
||||
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
|
||||
"dev:web": "pnpm --filter webui dev",
|
||||
"test": "pnpm --filter=\"./packages/**\" -r --no-bail --if-present test",
|
||||
"test": "pnpm test:workflows && pnpm --filter=\"./packages/**\" -r --no-bail --if-present test",
|
||||
"test:workflows": "node --test .github/scripts/*.test.cjs",
|
||||
"test:core": "pnpm --filter @snowluma/core test",
|
||||
"test:watch": "pnpm --filter @snowluma/core test:watch",
|
||||
"test:common": "pnpm --filter @snowluma/common test",
|
||||
@@ -35,8 +36,8 @@
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@stylistic/eslint-plugin": "5.10.0",
|
||||
"@vitest/coverage-istanbul": "4.1.4",
|
||||
"@vitest/coverage-v8": "^4.1.4",
|
||||
"@vitest/coverage-istanbul": "4.1.12",
|
||||
"@vitest/coverage-v8": "4.1.12",
|
||||
"cross-env": "^10.1.0",
|
||||
"eslint": "^10.2.0",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
@@ -50,7 +51,7 @@
|
||||
},
|
||||
"packageManager": "pnpm@11.25.0",
|
||||
"engines": {
|
||||
"node": ">=24",
|
||||
"node": "^24.22.1 || >=26.12.1",
|
||||
"pnpm": "11.25.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "2.0.0",
|
||||
"version": "2.4.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
|
||||
@@ -61,9 +61,9 @@
|
||||
"@types/node": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
"vitest": "4.1.12"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
"node": "^24.22.1 || >=26.12.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,13 +14,15 @@ import {
|
||||
import { PipeWatcher } from './pipe-watcher';
|
||||
import { createProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
|
||||
import { QqHookClient } from './qq-hook-client';
|
||||
import { detectAccountLoginsForPids, type AccountLoginState } from './qq-account';
|
||||
import {
|
||||
detectAccountLoginsForPids,
|
||||
watchAccountChangesForPids,
|
||||
type AccountLoginState,
|
||||
} from './qq-account';
|
||||
import type { HookProcessAccount, HookProcessInfo } from './types';
|
||||
|
||||
const AUTO_LOAD_MAX_ATTEMPTS = 3;
|
||||
|
||||
const DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS = 5000;
|
||||
|
||||
type AutoLoadAttempt = {
|
||||
attempts: number;
|
||||
inFlight: boolean;
|
||||
@@ -61,9 +63,8 @@ export type HookManagerDeps = {
|
||||
* the HOME it actually runs under (a container can give every QQ instance
|
||||
* its own). Defaults to reading QQ's own account data. */
|
||||
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
|
||||
/** How often the watcher re-probes the account label of each process, in
|
||||
* milliseconds. Defaults to `DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS`. */
|
||||
accountReprobeIntervalMs?: number;
|
||||
/** Subscribe to login database changes. Returns the subscription cleanup. */
|
||||
watchAccounts?: (pids: readonly number[], onChange: () => void) => () => void;
|
||||
/** When true, every newly-discovered QQ process is auto-injected (fires
|
||||
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
|
||||
* Failed loads are logged and leave the session in the 'error' state.
|
||||
@@ -106,7 +107,7 @@ export class HookManager {
|
||||
private readonly ownsPipeWatcher: boolean;
|
||||
private readonly enumerator: ProcessEnumerator;
|
||||
private readonly detectAccounts: (pids: readonly number[]) => Promise<AccountLoginState[]>;
|
||||
private readonly accountReprobeIntervalMs: number;
|
||||
private readonly watchAccounts: NonNullable<HookManagerDeps['watchAccounts']>;
|
||||
private readonly autoLoadOnDiscovery: boolean;
|
||||
private readonly onSessionsChangedRaw?: () => void;
|
||||
private readonly log: Logger;
|
||||
@@ -116,7 +117,8 @@ export class HookManager {
|
||||
|
||||
private accounts = new Map<number, HookProcessAccount>();
|
||||
private accountProbe: Promise<void> | null = null;
|
||||
private nextAccountProbeAt = 0;
|
||||
private accountsDirty = true;
|
||||
private stopWatchingAccounts?: () => void;
|
||||
private lastAccountProbeFailure = '';
|
||||
|
||||
private disposed = false;
|
||||
@@ -133,8 +135,9 @@ export class HookManager {
|
||||
};
|
||||
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
|
||||
this.detectAccounts = deps.detectAccounts ?? detectAccountLoginsForPids;
|
||||
this.accountReprobeIntervalMs =
|
||||
deps.accountReprobeIntervalMs ?? DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS;
|
||||
this.watchAccounts =
|
||||
deps.watchAccounts ??
|
||||
((pids, onChange) => watchAccountChangesForPids(pids, onChange, this.log));
|
||||
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
|
||||
|
||||
this.enumerator = createProcessEnumerator({
|
||||
@@ -186,6 +189,7 @@ export class HookManager {
|
||||
await this.startPromise;
|
||||
this.autoLoadAttempts.delete(pid);
|
||||
const session = this.ensureSession(pid);
|
||||
this.invalidateAccounts();
|
||||
await session.load();
|
||||
this.pipeWatcher.wake();
|
||||
await this.refreshAccounts();
|
||||
@@ -197,6 +201,7 @@ export class HookManager {
|
||||
await this.startPromise;
|
||||
this.autoLoadAttempts.delete(pid);
|
||||
const session = this.ensureSession(pid);
|
||||
this.invalidateAccounts();
|
||||
await session.unload();
|
||||
await this.refreshAccounts();
|
||||
return this.processInfo(session);
|
||||
@@ -206,6 +211,8 @@ export class HookManager {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
const session = this.ensureSession(pid);
|
||||
this.updateAccountWatcher();
|
||||
this.invalidateAccounts();
|
||||
await session.refresh();
|
||||
await this.refreshAccounts();
|
||||
return this.processInfo(session);
|
||||
@@ -217,6 +224,7 @@ export class HookManager {
|
||||
}
|
||||
|
||||
this.disposed = true;
|
||||
this.stopWatchingAccounts?.();
|
||||
|
||||
for (const session of this.sessions.values()) {
|
||||
session.dispose();
|
||||
@@ -238,45 +246,52 @@ export class HookManager {
|
||||
return { ...session.toInfo(), account: this.accounts.get(session.pid) ?? null };
|
||||
}
|
||||
|
||||
private invalidateAccounts(): void {
|
||||
this.accountsDirty = true;
|
||||
}
|
||||
|
||||
private updateAccountWatcher(): void {
|
||||
this.stopWatchingAccounts?.();
|
||||
this.stopWatchingAccounts = this.watchAccounts([...this.sessions.keys()], () => {
|
||||
this.invalidateAccounts();
|
||||
void this.refreshAccounts();
|
||||
});
|
||||
}
|
||||
|
||||
/** REST, watcher ticks and login reconciliation share the same account snapshot. */
|
||||
private async refreshAccounts(): Promise<void> {
|
||||
if (this.disposed) {
|
||||
if (this.disposed || this.sessions.size === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.accountProbe) {
|
||||
await this.accountProbe;
|
||||
|
||||
// Process discovery invalidates the snapshot while a read is in flight.
|
||||
if (this.nextAccountProbeAt === 0) {
|
||||
await this.refreshAccounts();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (Date.now() < this.nextAccountProbeAt || this.sessions.size === 0) {
|
||||
if (!this.accountsDirty) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.nextAccountProbeAt = Date.now() + this.accountReprobeIntervalMs;
|
||||
this.accountProbe = runWithTraceRequest(() => this.readAccounts()).finally(() => {
|
||||
this.accountProbe = runWithTraceRequest(async () => {
|
||||
// All callers await the replacement read too if a lifecycle change
|
||||
// invalidates an in-flight result.
|
||||
do {
|
||||
this.accountsDirty = false;
|
||||
await this.readAccounts();
|
||||
} while (!this.disposed && this.sessions.size > 0 && this.accountsDirty);
|
||||
}).finally(() => {
|
||||
this.accountProbe = null;
|
||||
});
|
||||
await this.accountProbe;
|
||||
}
|
||||
|
||||
private async readAccounts(): Promise<void> {
|
||||
const sessions = new Map(this.sessions);
|
||||
const accounts = new Map<number, HookProcessAccount>();
|
||||
|
||||
try {
|
||||
for (const state of await this.detectAccounts([...sessions.keys()])) {
|
||||
if (
|
||||
state.pid !== null &&
|
||||
sessions.has(state.pid) &&
|
||||
this.sessions.get(state.pid) === sessions.get(state.pid)
|
||||
) {
|
||||
for (const state of await this.detectAccounts([...this.sessions.keys()])) {
|
||||
if (state.pid !== null && this.sessions.has(state.pid)) {
|
||||
accounts.set(state.pid, { uin: state.uin, nickname: state.nickname });
|
||||
}
|
||||
}
|
||||
@@ -291,7 +306,7 @@ export class HookManager {
|
||||
}
|
||||
}
|
||||
|
||||
if (this.disposed) {
|
||||
if (this.disposed || this.accountsDirty) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -364,6 +379,7 @@ export class HookManager {
|
||||
const session = this.sessions.get(pid);
|
||||
|
||||
if (session) {
|
||||
this.invalidateAccounts();
|
||||
session.onPipeUp();
|
||||
}
|
||||
});
|
||||
@@ -375,6 +391,7 @@ export class HookManager {
|
||||
const session = this.sessions.get(pid);
|
||||
|
||||
if (session) {
|
||||
this.invalidateAccounts();
|
||||
session.onPipeDown();
|
||||
}
|
||||
});
|
||||
@@ -570,7 +587,10 @@ export class HookManager {
|
||||
session.attachProcessInfo({ name: defaultProcessName() });
|
||||
|
||||
session.on('login', (uin: string, sender) => {
|
||||
// Account switches can keep the same 'online' status.
|
||||
this.invalidateAccounts();
|
||||
this.bridgeManager.onHookLogin(pid, uin, sender);
|
||||
this.notifySessionsChanged();
|
||||
});
|
||||
session.on('disconnected', (wasLoggedIn: boolean) => {
|
||||
if (wasLoggedIn) {
|
||||
@@ -580,20 +600,25 @@ export class HookManager {
|
||||
session.on('receive-health-changed', (healthy: boolean) => {
|
||||
this.bridgeManager.onPidReceiveHealthChanged(pid, healthy);
|
||||
});
|
||||
// status-changed fires on EVERY internal status mutation, including the
|
||||
// ones reached via login / disconnected / refresh — subscribing here
|
||||
// alone covers every transition the WebUI processes view cares about.
|
||||
session.on('status-changed', () => {
|
||||
let previousStatus = session.status;
|
||||
session.on('status-changed', (status) => {
|
||||
if (previousStatus === 'online' && status !== 'online') {
|
||||
this.invalidateAccounts();
|
||||
}
|
||||
|
||||
previousStatus = status;
|
||||
this.notifySessionsChanged();
|
||||
});
|
||||
session.on('disposed', () => {
|
||||
this.sessions.delete(pid);
|
||||
this.accounts.delete(pid);
|
||||
this.nextAccountProbeAt = 0;
|
||||
this.updateAccountWatcher();
|
||||
this.invalidateAccounts();
|
||||
});
|
||||
|
||||
this.sessions.set(pid, session);
|
||||
this.nextAccountProbeAt = 0;
|
||||
this.updateAccountWatcher();
|
||||
this.invalidateAccounts();
|
||||
return session;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -88,6 +96,7 @@ export class HookSession extends EventEmitter {
|
||||
|
||||
private _status: HookProcessStatus = 'available';
|
||||
private _error = '';
|
||||
private runtimeFailure = '';
|
||||
private _uin = '0';
|
||||
private _method = '';
|
||||
private _name = '';
|
||||
@@ -102,7 +111,14 @@ export class HookSession extends EventEmitter {
|
||||
private bound = false;
|
||||
private opChain: Promise<unknown> = Promise.resolve();
|
||||
private disposed = false;
|
||||
private initialConnectionWatch: InitialConnectionWatch | null = null;
|
||||
private initialConnectionError = '';
|
||||
private hasConnected = false;
|
||||
private cancelConnectAttempt: (() => void) | null = null;
|
||||
private pipeUpPending = false;
|
||||
private loginReconcileTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private loginIdentityEpoch = 0;
|
||||
private invalidLoginStateReported = false;
|
||||
private detecting = false;
|
||||
private lastDetectFailure = '';
|
||||
private acceptedLoginHintUin = '';
|
||||
@@ -183,6 +199,7 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
unload(): Promise<HookProcessInfo> {
|
||||
this.cancelConnectAttempt?.();
|
||||
return this.traceCommand('unload', () => this.unloadInternal());
|
||||
}
|
||||
|
||||
@@ -196,19 +213,26 @@ export class HookSession extends EventEmitter {
|
||||
* attempts and adopts pre-existing hooks. Idempotent; safe to call on
|
||||
* every watcher tick where the pipe is live. */
|
||||
onPipeUp(): void {
|
||||
if (this.disposed) {
|
||||
if (this.disposed || this.pipeUpPending || this.cancelConnectAttempt) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Watcher ticks must not queue a backlog of stalled handshakes ahead of
|
||||
// user commands. The next tick can retry once this attempt has settled.
|
||||
this.pipeUpPending = true;
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.reconcilePipeUp();
|
||||
}).catch((err) =>
|
||||
this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errorMessage(err)),
|
||||
);
|
||||
})
|
||||
.catch((err) =>
|
||||
this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errorMessage(err)),
|
||||
)
|
||||
.finally(() => {
|
||||
this.pipeUpPending = false;
|
||||
});
|
||||
}
|
||||
|
||||
onPipeDown(): void {
|
||||
@@ -234,6 +258,7 @@ export class HookSession extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
this.cancelConnectAttempt?.();
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
@@ -247,6 +272,7 @@ export class HookSession extends EventEmitter {
|
||||
this.pid,
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
]);
|
||||
this.stopInitialConnectionWatch();
|
||||
this.tearDownClient();
|
||||
this.injected = false;
|
||||
this.injectResult = null;
|
||||
@@ -291,6 +317,7 @@ export class HookSession extends EventEmitter {
|
||||
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.disposed = true;
|
||||
this.stopInitialConnectionWatch();
|
||||
this.tearDownClient();
|
||||
|
||||
// Process shutdown must take the same PID-detach path as a live drop.
|
||||
@@ -373,6 +400,10 @@ export class HookSession extends EventEmitter {
|
||||
// ─────────────── internal transitions ───────────────
|
||||
|
||||
private async loadInternal(): Promise<HookProcessInfo> {
|
||||
if (this.disposed) {
|
||||
return this.toInfo();
|
||||
}
|
||||
|
||||
this._error = '';
|
||||
this.setStatus('loading', '');
|
||||
|
||||
@@ -406,6 +437,14 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
if (this.disposed) {
|
||||
return this.toInfo();
|
||||
}
|
||||
|
||||
// A retry reuses the loaded component and its unload handle. Only an
|
||||
// expired deadline is restarted; repeated clicks cannot postpone it.
|
||||
this.initialConnectionError = '';
|
||||
this.startInitialConnectionWatch();
|
||||
this.applyStatus();
|
||||
} catch (error) {
|
||||
this._error = errorMessage(error);
|
||||
@@ -428,6 +467,9 @@ export class HookSession extends EventEmitter {
|
||||
|
||||
private async unloadInternal(): Promise<HookProcessInfo> {
|
||||
this._error = '';
|
||||
this.stopInitialConnectionWatch();
|
||||
this.initialConnectionError = '';
|
||||
this.hasConnected = false;
|
||||
|
||||
try {
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
@@ -500,6 +542,16 @@ export class HookSession extends EventEmitter {
|
||||
* defaults to the current `loggedIn`; callers that just tore the client
|
||||
* down pass the value captured *before* teardown (teardown clears it). */
|
||||
private applyStatus(wasLoggedIn: boolean = this.loggedIn, error = ''): void {
|
||||
if (this.runtimeFailure) {
|
||||
this.setStatus('error', this.runtimeFailure);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.initialConnectionError) {
|
||||
this.setStatus('error', this.initialConnectionError);
|
||||
return;
|
||||
}
|
||||
|
||||
this.setStatus(
|
||||
statusFor({
|
||||
injected: this.injected,
|
||||
@@ -523,6 +575,8 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
this.startInitialConnectionWatch();
|
||||
|
||||
if (this.client?.isClosed) {
|
||||
this.tearDownClient();
|
||||
}
|
||||
@@ -559,7 +613,7 @@ export class HookSession extends EventEmitter {
|
||||
this.pid,
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
]);
|
||||
this.tearDownClient();
|
||||
this.tearDownClient(true);
|
||||
this.applyStatus(wasLoggedIn);
|
||||
|
||||
try {
|
||||
@@ -607,6 +661,7 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
if (!this.client) {
|
||||
this.runtimeFailure = '';
|
||||
this.client = this.makeClient(this.pid);
|
||||
this.sender = new HookPacketClient(this.client, (healthy) =>
|
||||
this.setOutboundHealthy(healthy),
|
||||
@@ -620,25 +675,31 @@ 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 });
|
||||
this.connected = true;
|
||||
const loginState = client.getLoginState();
|
||||
await this.connectWithTimeout(client, timeoutMs);
|
||||
|
||||
// handleLoginState owns the connected+loggedIn → 'online' (+ login
|
||||
// emit) transition; defer to it so the status is set once. Otherwise
|
||||
// we're connected-but-not-logged-in → 'loaded'.
|
||||
if (loginState.loggedIn) {
|
||||
this.handleLoginState(loginState);
|
||||
} else {
|
||||
this.applyStatus();
|
||||
// The native hook only PUSHES a loginState frame on the login edge;
|
||||
// if QQ logged in before/around connect (Docker auto-login) that edge
|
||||
// is missed and we'd wait forever. Keep re-detecting until logged in.
|
||||
runWithoutRequestContext(() => this.startLoginReconcile());
|
||||
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 = '';
|
||||
this._error = '';
|
||||
// Identity validation owns readiness and whether to keep checking.
|
||||
// A reported login alone does not establish a usable account.
|
||||
this.handleLoginState(client.getLoginState());
|
||||
|
||||
this.log.info('pipe connected: PID=%d', this.pid);
|
||||
this.log.trace(() => [
|
||||
'hook_session_connect_terminal pid=%d outcome=completed reason=connect_settled state=%s elapsedMs=%d',
|
||||
@@ -647,11 +708,27 @@ export class HookSession extends EventEmitter {
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
} catch (error) {
|
||||
if (this.disposed || this.client !== client) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._error = errorMessage(error);
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
// Drop the client so the next attempt builds a fresh socket pair.
|
||||
// A failed connect was never logged in → 'connecting' (or 'available').
|
||||
this.tearDownClient();
|
||||
this.applyStatus(false, this._error);
|
||||
this.tearDownClient(true);
|
||||
|
||||
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,
|
||||
@@ -663,12 +740,118 @@ 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) {
|
||||
return;
|
||||
}
|
||||
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.runtimeFailure = errorMessage(error);
|
||||
this.stopInitialConnectionWatch();
|
||||
this.loggedIn = false;
|
||||
this.stopLoginReconcile();
|
||||
this.resetReceiveWatch();
|
||||
this.applyStatus(wasLoggedIn);
|
||||
this.log.error('QQ runtime unavailable: PID=%d err=%s', this.pid, this.runtimeFailure);
|
||||
|
||||
if (wasLoggedIn) {
|
||||
this.emit('disconnected', true);
|
||||
}
|
||||
});
|
||||
client.on('packet', (packet) => this.handlePacket(packet));
|
||||
client.on('loginState', (state) => this.handleLoginState(state));
|
||||
client.on('error', (error) => {
|
||||
const msg = errorMessage(error);
|
||||
this._error = msg;
|
||||
this._error = this.runtimeFailure || this.initialConnectionError || msg;
|
||||
this.log.warn('pipe error: PID=%d err=%s', this.pid, msg);
|
||||
});
|
||||
client.on('close', () => {
|
||||
@@ -698,7 +881,8 @@ export class HookSession extends EventEmitter {
|
||||
});
|
||||
}
|
||||
|
||||
private tearDownClient(): void {
|
||||
private tearDownClient(preserveRuntimeFailure = false): void {
|
||||
this.cancelConnectAttempt?.();
|
||||
this.stopLoginReconcile();
|
||||
this.resetReceiveWatch();
|
||||
const client = this.client;
|
||||
@@ -714,19 +898,41 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
this.client = null;
|
||||
|
||||
if (!preserveRuntimeFailure) {
|
||||
this.runtimeFailure = '';
|
||||
}
|
||||
|
||||
this.sender = null;
|
||||
this.bound = false;
|
||||
this.connected = false;
|
||||
this.loggedIn = false;
|
||||
this.invalidLoginStateReported = false;
|
||||
this._outboundHealthy = true;
|
||||
this.resetLoginHint();
|
||||
}
|
||||
|
||||
private handleLoginState(state: QqHookLoginState): void {
|
||||
if (this.disposed || this.runtimeFailure) {
|
||||
return;
|
||||
}
|
||||
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
const previousUin = this._uin;
|
||||
this._uin = state.uin || state.uinNumber.toString();
|
||||
this.loggedIn = state.loggedIn && isRealUin(this._uin);
|
||||
const uin = state.uin || state.uinNumber.toString();
|
||||
const validIdentity = isRealUin(uin);
|
||||
const invalidLoginState = state.loggedIn && !validIdentity;
|
||||
|
||||
if (invalidLoginState && !this.invalidLoginStateReported) {
|
||||
this.log.warn(
|
||||
'Login readiness rejected: PID=%d reason=invalid_account_identity',
|
||||
this.pid,
|
||||
);
|
||||
}
|
||||
|
||||
this.invalidLoginStateReported = invalidLoginState;
|
||||
this._uin = validIdentity ? uin : '0';
|
||||
this.loggedIn = state.loggedIn && validIdentity;
|
||||
|
||||
// Login readiness has now been confirmed, so identity probing is done.
|
||||
if (this.loggedIn) {
|
||||
@@ -741,19 +947,30 @@ export class HookSession extends EventEmitter {
|
||||
} else {
|
||||
this.resetReceiveWatch();
|
||||
this._outboundHealthy = true;
|
||||
|
||||
if (wasLoggedIn) {
|
||||
this.resetLoginHint();
|
||||
}
|
||||
}
|
||||
|
||||
// Only the connected/logged-in states are ours to set here; when fully
|
||||
// down we leave the status the teardown path already settled.
|
||||
// Load-bearing invariant: `loggedIn ⇒ connected` (login can only be
|
||||
// observed on a live client, and teardown clears `loggedIn` before
|
||||
// `connected`), so statusFor lands 'online' here rather than the
|
||||
// disconnected/connecting branch.
|
||||
// Login may arrive while another channel is still handshaking; the
|
||||
// connection attempt revokes that binding if it fails to complete.
|
||||
if (this.connected || this.loggedIn) {
|
||||
this.applyStatus(wasLoggedIn, this.loggedIn ? '' : this._error);
|
||||
}
|
||||
|
||||
if (!this.loggedIn || !this.sender) {
|
||||
if (!this.loggedIn) {
|
||||
if (wasLoggedIn) {
|
||||
this.emit('disconnected', true);
|
||||
}
|
||||
|
||||
runWithoutRequestContext(() => this.startLoginReconcile());
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.sender) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -800,17 +1017,23 @@ export class HookSession extends EventEmitter {
|
||||
// reconciliation, but never synthesize online state from the detection.
|
||||
|
||||
private startLoginReconcile(): void {
|
||||
if (this.loginReconcileTimer || this.disposed) {
|
||||
if (
|
||||
this.loginReconcileTimer ||
|
||||
this.disposed ||
|
||||
this.runtimeFailure ||
|
||||
!this.connected ||
|
||||
this.loggedIn
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.log.info('awaiting login: PID=%d', this.pid);
|
||||
void this.detectLoginOnce(); // immediate — catch already-logged-in fast
|
||||
this.loginReconcileTimer = setInterval(
|
||||
() => void this.detectLoginOnce(),
|
||||
LOGIN_RECONCILE_INTERVAL_MS,
|
||||
);
|
||||
this.loginReconcileTimer.unref();
|
||||
void this.detectLoginOnce();
|
||||
}
|
||||
|
||||
private stopLoginReconcile(): void {
|
||||
@@ -828,8 +1051,9 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
const client = this.client;
|
||||
const identityEpoch = this.loginIdentityEpoch;
|
||||
|
||||
if (this.disposed || !client || !this.connected || this.loggedIn) {
|
||||
if (this.disposed || !client || !this.connected || this.loggedIn || this.runtimeFailure) {
|
||||
this.stopLoginReconcile();
|
||||
return;
|
||||
}
|
||||
@@ -846,6 +1070,17 @@ export class HookSession extends EventEmitter {
|
||||
try {
|
||||
uin = await this.detectLoginUin(this.pid);
|
||||
} catch (error) {
|
||||
if (
|
||||
this.client !== client ||
|
||||
this.loginIdentityEpoch !== identityEpoch ||
|
||||
this.disposed ||
|
||||
!this.connected ||
|
||||
this.loggedIn ||
|
||||
this.runtimeFailure
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = errorMessage(error);
|
||||
|
||||
if (this.lastDetectFailure !== message) {
|
||||
@@ -860,8 +1095,15 @@ export class HookSession extends EventEmitter {
|
||||
return; // best-effort; the interval retries
|
||||
}
|
||||
|
||||
// A reconnect owns a new client; an older read cannot supply its identity.
|
||||
if (this.client !== client || this.disposed || !this.connected || this.loggedIn) {
|
||||
// A connection or readiness change invalidates earlier identity work.
|
||||
if (
|
||||
this.client !== client ||
|
||||
this.loginIdentityEpoch !== identityEpoch ||
|
||||
this.disposed ||
|
||||
!this.connected ||
|
||||
this.loggedIn ||
|
||||
this.runtimeFailure
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -900,9 +1142,11 @@ export class HookSession extends EventEmitter {
|
||||
|
||||
if (
|
||||
this.client !== client ||
|
||||
this.loginIdentityEpoch !== identityEpoch ||
|
||||
this.disposed ||
|
||||
!this.connected ||
|
||||
this.loggedIn
|
||||
this.loggedIn ||
|
||||
this.runtimeFailure
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -911,7 +1155,14 @@ export class HookSession extends EventEmitter {
|
||||
this.nextLoginIdentityObservationAt =
|
||||
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
|
||||
} catch (error) {
|
||||
if (this.client !== client || this.disposed) {
|
||||
if (
|
||||
this.client !== client ||
|
||||
this.loginIdentityEpoch !== identityEpoch ||
|
||||
this.disposed ||
|
||||
!this.connected ||
|
||||
this.loggedIn ||
|
||||
this.runtimeFailure
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -944,6 +1195,7 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
private resetLoginHint(): void {
|
||||
this.loginIdentityEpoch++;
|
||||
this.acceptedLoginHintUin = '';
|
||||
this.loginHintAttemptUin = '';
|
||||
this.loginHintAttempts = 0;
|
||||
@@ -957,6 +1209,17 @@ export class HookSession extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
packet.source === 'client-message' &&
|
||||
(!isRealUin(packet.uin) || packet.uin !== this._uin)
|
||||
) {
|
||||
this.log.warn(
|
||||
'Client message receipt belongs to an inactive account: PID=%d',
|
||||
this.pid,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const uin = packet.uin || this._uin;
|
||||
// Routing requires a real UIN, but even a frame carrying UIN=0 proves the
|
||||
// receive hook is alive. Attribute that evidence to the current epoch
|
||||
@@ -986,6 +1249,7 @@ export class HookSession extends EventEmitter {
|
||||
seqId: packet.seq,
|
||||
retCode: packet.error,
|
||||
fromClient: false,
|
||||
...(packet.source ? { source: packet.source } : {}),
|
||||
body: Buffer.from(packet.body),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ export {
|
||||
type LoginDbFailure,
|
||||
} from './login-db';
|
||||
export { accountDirName, loginDbPaths, ntMsgDbPath, qqDataRoots, qqDataRootsForPid } from './paths';
|
||||
export { watchAccountChangesForPids } from './watch';
|
||||
export {
|
||||
decryptDatabase,
|
||||
detectAlgorithm,
|
||||
|
||||
115
packages/bridge/src/qq-account/watch.ts
Normal file
115
packages/bridge/src/qq-account/watch.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import { errorMessage } from '@snowluma/common/errors';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { watch, type FSWatcher } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { loginDbPaths, qqDataRootsForPid } from './paths';
|
||||
|
||||
export function watchAccountChangesForPids(
|
||||
pids: readonly number[],
|
||||
onChange: () => void,
|
||||
log: Logger = createLogger('QqAccount'),
|
||||
): () => void {
|
||||
const roots = new Set<string>();
|
||||
|
||||
for (const pid of pids) {
|
||||
try {
|
||||
for (const root of qqDataRootsForPid(pid)) {
|
||||
roots.add(root);
|
||||
}
|
||||
} catch (error) {
|
||||
log.warn('account watch root failed: PID=%d err=%s', pid, errorMessage(error));
|
||||
}
|
||||
}
|
||||
|
||||
return watchAccountFiles([...roots].flatMap(loginDbPaths), onChange, log);
|
||||
}
|
||||
|
||||
/** Watch directories so replacing login.db or recreating its WAL keeps working. */
|
||||
export function watchAccountFiles(
|
||||
dbPaths: readonly string[],
|
||||
onChange: () => void,
|
||||
log: Logger = createLogger('QqAccount'),
|
||||
): () => void {
|
||||
const watchers = new Map<string, FSWatcher>();
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
|
||||
const changed = () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
timer = undefined;
|
||||
onChange();
|
||||
}, 250);
|
||||
timer.unref();
|
||||
};
|
||||
|
||||
const observe = (dbPath: string) => {
|
||||
watchers.get(dbPath)?.close();
|
||||
watchers.delete(dbPath);
|
||||
const dbDirectory = path.dirname(dbPath);
|
||||
let directory = dbDirectory;
|
||||
|
||||
for (;;) {
|
||||
const target = path.relative(directory, dbPath).split(path.sep)[0]!;
|
||||
|
||||
try {
|
||||
const watcher = watch(directory, { persistent: false }, (_event, filename) => {
|
||||
if (
|
||||
watchers.get(dbPath) !== watcher ||
|
||||
(filename !== null &&
|
||||
filename !== target &&
|
||||
!(directory === dbDirectory && filename === `${target}-wal`))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// QQ may create its data directories after process discovery.
|
||||
if (directory !== dbDirectory) {
|
||||
observe(dbPath);
|
||||
}
|
||||
|
||||
changed();
|
||||
});
|
||||
watcher.on('error', (error) => {
|
||||
if (watchers.get(dbPath) !== watcher) {
|
||||
return;
|
||||
}
|
||||
|
||||
watcher.close();
|
||||
watchers.delete(dbPath);
|
||||
log.warn('account watch failed: path=%s err=%s', dbPath, errorMessage(error));
|
||||
});
|
||||
watchers.set(dbPath, watcher);
|
||||
return;
|
||||
} catch (error) {
|
||||
const parent = path.dirname(directory);
|
||||
|
||||
if (
|
||||
error instanceof Error &&
|
||||
'code' in error &&
|
||||
error.code === 'ENOENT' &&
|
||||
parent !== directory
|
||||
) {
|
||||
directory = parent;
|
||||
continue;
|
||||
}
|
||||
|
||||
log.warn('account watch failed: path=%s err=%s', dbPath, errorMessage(error));
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
for (const dbPath of new Set(dbPaths)) {
|
||||
observe(dbPath);
|
||||
}
|
||||
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
|
||||
for (const watcher of watchers.values()) {
|
||||
watcher.close();
|
||||
}
|
||||
|
||||
watchers.clear();
|
||||
};
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
import { CLIENT_MESSAGE_RECEIPT_CMD } from '@snowluma/common/protocol-types';
|
||||
import { readdirSync, promises as fs } from 'fs';
|
||||
import net from 'net';
|
||||
import path from 'path';
|
||||
@@ -38,6 +39,8 @@ export enum PipeOp {
|
||||
recvPacket = 6,
|
||||
loginState = 7,
|
||||
loginIdentityHint = 17,
|
||||
clientMessageReceipt = 21,
|
||||
clientMessageState = 22,
|
||||
}
|
||||
|
||||
const PipeFlagWantReply = 1 << 0;
|
||||
@@ -55,6 +58,7 @@ export interface QqHookPacket {
|
||||
cmd: string;
|
||||
uin: string;
|
||||
body: Buffer;
|
||||
source?: 'client-message';
|
||||
}
|
||||
|
||||
export interface QqHookHello {
|
||||
@@ -541,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;
|
||||
@@ -559,6 +564,7 @@ export class QqHookClient extends EventEmitter {
|
||||
private recvHelloResolver: Deferred<QqHookHello> | null = null;
|
||||
private controlWriteChain: Promise<unknown> = Promise.resolve();
|
||||
private closed = false;
|
||||
private runtimeFailure: Error | null = null;
|
||||
private loginState: QqHookLoginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
private readonly loginWaiters = new Set<Deferred<QqHookLoginState>>();
|
||||
|
||||
@@ -611,10 +617,7 @@ export class QqHookClient extends EventEmitter {
|
||||
|
||||
async waitForLogin({ timeoutMs = 0 } = {}): Promise<QqHookLoginState> {
|
||||
await this.connect();
|
||||
|
||||
if (this.closed) {
|
||||
throw new Error('qq_hook client is closed');
|
||||
}
|
||||
this.assertUsable();
|
||||
|
||||
if (this.loginState.loggedIn) {
|
||||
return this.getLoginState();
|
||||
@@ -688,9 +691,7 @@ export class QqHookClient extends EventEmitter {
|
||||
}
|
||||
|
||||
async connect(): Promise<QqHookHello> {
|
||||
if (this.closed) {
|
||||
throw new Error('qq_hook client is closed');
|
||||
}
|
||||
this.assertUsable();
|
||||
|
||||
if (this.controlSocket && this.controlHello) {
|
||||
return this.controlHello;
|
||||
@@ -710,9 +711,7 @@ export class QqHookClient extends EventEmitter {
|
||||
}
|
||||
|
||||
async startRecv(onPacket?: (packet: QqHookPacket) => void): Promise<QqHookHello> {
|
||||
if (this.closed) {
|
||||
throw new Error('qq_hook client is closed');
|
||||
}
|
||||
this.assertUsable();
|
||||
|
||||
if (typeof onPacket === 'function') {
|
||||
this.on('packet', onPacket);
|
||||
@@ -977,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;
|
||||
@@ -992,6 +997,16 @@ export class QqHookClient extends EventEmitter {
|
||||
this.controlWriteChain = Promise.resolve();
|
||||
}
|
||||
|
||||
private assertUsable(): void {
|
||||
if (this.runtimeFailure) {
|
||||
throw this.runtimeFailure;
|
||||
}
|
||||
|
||||
if (this.closed) {
|
||||
throw new Error('qq_hook client is closed');
|
||||
}
|
||||
}
|
||||
|
||||
private rejectLoginWaiters(error: Error): void {
|
||||
for (const waiter of this.loginWaiters) {
|
||||
waiter.reject(error);
|
||||
@@ -1029,26 +1044,28 @@ export class QqHookClient extends EventEmitter {
|
||||
const socket = this.controlSocket;
|
||||
|
||||
if (!socket || socket.destroyed) {
|
||||
return Promise.reject(new Error('control pipe is not connected'));
|
||||
return Promise.reject(
|
||||
this.runtimeFailure ?? new Error('control pipe is not connected'),
|
||||
);
|
||||
}
|
||||
|
||||
const writePromise = this.controlWriteChain.then(
|
||||
() =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
if (!this.controlSocket || this.controlSocket.destroyed) {
|
||||
reject(new Error('control pipe is not connected'));
|
||||
return;
|
||||
}
|
||||
const writePromise = this.controlWriteChain.then(() => {
|
||||
this.assertUsable();
|
||||
|
||||
socket.write(payload, (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}),
|
||||
);
|
||||
if (this.controlSocket !== socket || socket.destroyed) {
|
||||
throw new Error('control pipe is not connected');
|
||||
}
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
socket.write(payload, (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
this.controlWriteChain = writePromise.catch(() => {});
|
||||
return writePromise;
|
||||
}
|
||||
@@ -1128,6 +1145,11 @@ export class QqHookClient extends EventEmitter {
|
||||
),
|
||||
);
|
||||
|
||||
if (this.closed || this.runtimeFailure) {
|
||||
socket.destroy();
|
||||
this.assertUsable();
|
||||
}
|
||||
|
||||
if (kind === 'control') {
|
||||
this.controlSocket = socket;
|
||||
} else {
|
||||
@@ -1142,6 +1164,8 @@ export class QqHookClient extends EventEmitter {
|
||||
phase = 'hello';
|
||||
const hello = await this.waitForHello(kind === 'recv');
|
||||
|
||||
this.assertUsable();
|
||||
|
||||
if (kind === 'control') {
|
||||
this.controlHello = hello;
|
||||
} else {
|
||||
@@ -1177,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 {
|
||||
@@ -1200,7 +1233,11 @@ export class QqHookClient extends EventEmitter {
|
||||
});
|
||||
});
|
||||
resolve(socket);
|
||||
});
|
||||
};
|
||||
|
||||
socket.once('error', onInitialError);
|
||||
socket.once('close', onInitialClose);
|
||||
socket.once('connect', onConnect);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1297,6 +1334,10 @@ export class QqHookClient extends EventEmitter {
|
||||
}
|
||||
|
||||
private handleControlFrame(frame: PipeFrame): void {
|
||||
if (this.runtimeFailure) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.op === PipeOp.hello) {
|
||||
this.resolveHello(frame, false);
|
||||
return;
|
||||
@@ -1342,6 +1383,16 @@ export class QqHookClient extends EventEmitter {
|
||||
frame.status,
|
||||
frame.requestId,
|
||||
);
|
||||
|
||||
if (frame.requestId === 0 && frame.cmd === 'runtime') {
|
||||
this.runtimeFailure = error;
|
||||
this.rejectControlPending(error);
|
||||
this.rejectRecvPending(error);
|
||||
this.rejectLoginWaiters(error);
|
||||
this.emit('runtimeError', error);
|
||||
return;
|
||||
}
|
||||
|
||||
const ack = this.pendingAcks.get(frame.requestId);
|
||||
|
||||
if (ack) {
|
||||
@@ -1359,6 +1410,10 @@ export class QqHookClient extends EventEmitter {
|
||||
}
|
||||
|
||||
private handleRecvFrame(frame: PipeFrame): void {
|
||||
if (this.runtimeFailure) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.op === PipeOp.hello) {
|
||||
this.resolveHello(frame, true);
|
||||
return;
|
||||
@@ -1369,6 +1424,45 @@ export class QqHookClient extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.op === PipeOp.clientMessageState) {
|
||||
if (frame.status === 1) {
|
||||
runtimeLog.debug('Client private-message reporting is available: PID=%d', this.pid);
|
||||
} else {
|
||||
runtimeLog.warn(
|
||||
'Client private-message reporting is unavailable: PID=%d status=%d%s',
|
||||
this.pid,
|
||||
frame.status,
|
||||
frame.value0 === 0n ? '' : ` reason=${frame.value0}`,
|
||||
);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.op === PipeOp.clientMessageReceipt) {
|
||||
if (
|
||||
frame.cmd !== '' ||
|
||||
frame.requestId !== 0 ||
|
||||
frame.flags !== 0 ||
|
||||
frame.value0 <= 0n ||
|
||||
frame.value0 > BigInt(Number.MAX_SAFE_INTEGER) ||
|
||||
!isRealUin(frame.msg)
|
||||
) {
|
||||
runtimeLog.warn('Invalid client message receipt: PID=%d', this.pid);
|
||||
return;
|
||||
}
|
||||
|
||||
this.emit('packet', {
|
||||
seq: Number(frame.value0),
|
||||
error: frame.status,
|
||||
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
|
||||
uin: frame.msg,
|
||||
body: Buffer.from(frame.body),
|
||||
source: 'client-message',
|
||||
} satisfies QqHookPacket);
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.op !== PipeOp.recvPacket) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -24,6 +24,8 @@ interface Harness {
|
||||
setLivePipes: (next: number[]) => void;
|
||||
onSessionsChanged: ReturnType<typeof vi.fn>;
|
||||
clientFactory: ReturnType<typeof vi.fn>;
|
||||
notifyAccountChange: () => void;
|
||||
watchAccounts: ReturnType<typeof vi.fn>;
|
||||
}
|
||||
|
||||
function makeManager(
|
||||
@@ -31,7 +33,6 @@ function makeManager(
|
||||
processes?: number[];
|
||||
livePipes?: number[];
|
||||
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
|
||||
accountReprobeIntervalMs?: number;
|
||||
} = {},
|
||||
): Harness {
|
||||
let pids = opts.processes ?? [];
|
||||
@@ -64,6 +65,13 @@ function makeManager(
|
||||
onPidReceiveHealthChanged: vi.fn(),
|
||||
} as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
const onSessionsChanged = vi.fn();
|
||||
|
||||
let accountChanged = () => {};
|
||||
|
||||
const watchAccounts = vi.fn((_pids: readonly number[], onChange: () => void) => {
|
||||
accountChanged = onChange;
|
||||
return vi.fn();
|
||||
});
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
@@ -77,7 +85,7 @@ function makeManager(
|
||||
makeClient: clientFactory,
|
||||
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
detectAccounts: opts.detectAccounts ?? (async () => []),
|
||||
accountReprobeIntervalMs: opts.accountReprobeIntervalMs,
|
||||
watchAccounts,
|
||||
onSessionsChanged,
|
||||
});
|
||||
return {
|
||||
@@ -86,6 +94,8 @@ function makeManager(
|
||||
bridgeManager,
|
||||
onSessionsChanged,
|
||||
clientFactory,
|
||||
notifyAccountChange: () => accountChanged(),
|
||||
watchAccounts,
|
||||
setProcesses: (next) => {
|
||||
pids = next;
|
||||
},
|
||||
@@ -142,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(() => {
|
||||
@@ -198,6 +245,7 @@ describe('HookManager.onSessionsChanged', () => {
|
||||
}),
|
||||
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
detectAccounts: async () => [],
|
||||
watchAccounts: () => () => {},
|
||||
// onSessionsChanged deliberately omitted
|
||||
});
|
||||
await pipeWatcher.start();
|
||||
@@ -210,7 +258,111 @@ describe('HookManager.onSessionsChanged', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookManager periodic account re-probe', () => {
|
||||
describe('HookManager account re-probe', () => {
|
||||
it('reuses the account snapshot across ticks and REST reads while all sessions are online (#549)', async () => {
|
||||
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
|
||||
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
|
||||
{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 5151 },
|
||||
]);
|
||||
const ctx = makeManager({
|
||||
processes: [4242, 5151],
|
||||
livePipes: [4242, 5151],
|
||||
detectAccounts,
|
||||
});
|
||||
const now = vi.spyOn(Date, 'now');
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
|
||||
for (const [index, uin] of ['10001', '10002'].entries()) {
|
||||
const client = ctx.clientFactory.mock.results[index]!.value as EventEmitter;
|
||||
client.emit('loginState', { loggedIn: true, uin, uinNumber: BigInt(uin) });
|
||||
}
|
||||
|
||||
const initial = await ctx.manager.listProcesses();
|
||||
expect(initial.map((info) => info.status)).toEqual(['online', 'online']);
|
||||
const baseline = detectAccounts.mock.calls.length;
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
const startedAt = Date.now();
|
||||
|
||||
for (let tick = 1; tick <= 10; tick++) {
|
||||
now.mockReturnValue(startedAt + tick * 6000);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
expect(await ctx.manager.listProcesses()).toEqual(initial);
|
||||
}
|
||||
|
||||
expect(detectAccounts).toHaveBeenCalledTimes(baseline);
|
||||
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
now.mockRestore();
|
||||
ctx.manager.dispose();
|
||||
ctx.pipeWatcher.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['loadProcess', 'unloadProcess', 'refreshProcess'] as const)(
|
||||
'refreshes account labels on %s even within the probe interval',
|
||||
async (operation) => {
|
||||
let nickname = 'Alice';
|
||||
const ctx = makeManager({
|
||||
processes: [4242],
|
||||
detectAccounts: async () => [{ uin: '10001', uid: 'u_a', nickname, pid: 4242 }],
|
||||
});
|
||||
|
||||
try {
|
||||
expect((await ctx.manager.listProcesses())[0]!.account?.nickname).toBe('Alice');
|
||||
nickname = 'Updated';
|
||||
expect((await ctx.manager[operation](4242)).account?.nickname).toBe('Updated');
|
||||
} finally {
|
||||
ctx.manager.dispose();
|
||||
ctx.pipeWatcher.dispose();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('discards an in-flight account result when an online process switches accounts', async () => {
|
||||
const stale = Promise.withResolvers<AccountLoginState[]>();
|
||||
const fresh = Promise.withResolvers<AccountLoginState[]>();
|
||||
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
|
||||
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
|
||||
]);
|
||||
const ctx = makeManager({
|
||||
processes: [4242],
|
||||
livePipes: [4242],
|
||||
detectAccounts,
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
|
||||
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
|
||||
await ctx.manager.listProcesses();
|
||||
detectAccounts.mockImplementationOnce(() => stale.promise);
|
||||
detectAccounts.mockImplementationOnce(() => fresh.promise);
|
||||
const refreshing = ctx.manager.refreshProcess(4242);
|
||||
await flush();
|
||||
const baseline = detectAccounts.mock.calls.length;
|
||||
client.emit('loginState', { loggedIn: true, uin: '10002', uinNumber: 10002n });
|
||||
const snapshot = ctx.manager.listProcesses();
|
||||
await flush();
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
stale.resolve([{ uin: '10003', uid: 'u_c', nickname: 'Stale', pid: 4242 }]);
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
|
||||
expect(detectAccounts).toHaveBeenCalledTimes(baseline + 1);
|
||||
fresh.resolve([{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 4242 }]);
|
||||
expect((await snapshot)[0]!.account).toEqual({ uin: '10002', nickname: 'Bob' });
|
||||
expect((await refreshing).account).toEqual({ uin: '10002', nickname: 'Bob' });
|
||||
} finally {
|
||||
stale.resolve([]);
|
||||
fresh.resolve([]);
|
||||
ctx.manager.dispose();
|
||||
ctx.pipeWatcher.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('shares one account probe between watcher ticks and concurrent snapshots', async () => {
|
||||
const probe = Promise.withResolvers<AccountLoginState[]>();
|
||||
const detectAccounts = vi.fn(() => probe.promise);
|
||||
@@ -234,6 +386,86 @@ describe('HookManager periodic account re-probe', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['pipe-down', 'client-close', 'logout'] as const)(
|
||||
're-probes after %s and observes later login data changes',
|
||||
async (event) => {
|
||||
let accounts: AccountLoginState[] = [
|
||||
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
|
||||
];
|
||||
const detectAccounts = vi.fn(async () => accounts);
|
||||
const ctx = makeManager({
|
||||
processes: [4242],
|
||||
livePipes: [4242],
|
||||
detectAccounts,
|
||||
});
|
||||
const now = vi.spyOn(Date, 'now');
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
|
||||
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
|
||||
await ctx.manager.listProcesses();
|
||||
accounts = [];
|
||||
|
||||
if (event === 'pipe-down') {
|
||||
ctx.setLivePipes([]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
} else if (event === 'client-close') {
|
||||
client.emit('close');
|
||||
} else {
|
||||
client.emit('loginState', { loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
}
|
||||
|
||||
await flush();
|
||||
expect((await ctx.manager.listProcesses())[0]!.account).toBeNull();
|
||||
accounts = [{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 4242 }];
|
||||
now.mockReturnValue(Date.now() + 6000);
|
||||
ctx.notifyAccountChange();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
expect((await ctx.manager.listProcesses())[0]!.account?.uin).toBe('10002');
|
||||
} finally {
|
||||
now.mockRestore();
|
||||
ctx.manager.dispose();
|
||||
ctx.pipeWatcher.dispose();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('re-probes when another process appears and when it exits', async () => {
|
||||
let nickname = 'Alice';
|
||||
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
|
||||
{ uin: '10001', uid: 'u_a', nickname, pid: 4242 },
|
||||
{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 5151 },
|
||||
]);
|
||||
const ctx = makeManager({ processes: [4242], livePipes: [4242], detectAccounts });
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
|
||||
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
|
||||
await ctx.manager.listProcesses();
|
||||
nickname = 'Updated';
|
||||
ctx.setProcesses([4242, 5151]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
expect((await ctx.manager.listProcesses()).map((info) => info.account)).toEqual([
|
||||
{ uin: '10001', nickname: 'Updated' },
|
||||
{ uin: '10002', nickname: 'Bob' },
|
||||
]);
|
||||
nickname = 'Final';
|
||||
ctx.setProcesses([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
const list = await ctx.manager.listProcesses();
|
||||
expect(list).toHaveLength(1);
|
||||
expect(list[0]!.account?.nickname).toBe('Final');
|
||||
} finally {
|
||||
ctx.manager.dispose();
|
||||
ctx.pipeWatcher.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps all process labels when an operation reads just one process', async () => {
|
||||
const accounts: AccountLoginState[] = [
|
||||
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
|
||||
@@ -246,8 +478,8 @@ describe('HookManager periodic account re-probe', () => {
|
||||
|
||||
try {
|
||||
await ctx.manager.listProcesses();
|
||||
const baseline = detectAccounts.mock.calls.length;
|
||||
expect((await ctx.manager.refreshProcess(4242)).account?.uin).toBe('10001');
|
||||
const baseline = detectAccounts.mock.calls.length;
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
@@ -282,17 +514,13 @@ describe('HookManager periodic account re-probe', () => {
|
||||
}
|
||||
});
|
||||
|
||||
// A login can happen with no hook edge at all (QQ signs in after SnowLuma
|
||||
// started, or before the hook was injected), so no session status changes
|
||||
// and nothing pushes a fresh processes snapshot. These cover the watcher
|
||||
// pass that re-reads the account labels and invalidates when they move.
|
||||
// Login database changes can reveal login before the hook is loaded.
|
||||
|
||||
it('publishes when a process gains an account label', async () => {
|
||||
let accounts: AccountLoginState[] = [{ uin: '1', uid: 'u1', nickname: 'A', pid: null }];
|
||||
const ctx = makeManager({
|
||||
processes: [4242],
|
||||
detectAccounts: async () => accounts,
|
||||
accountReprobeIntervalMs: 0,
|
||||
});
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
@@ -300,7 +528,7 @@ describe('HookManager periodic account re-probe', () => {
|
||||
|
||||
// QQ finished signing in: the account's nt_msg.db is now held by 4242.
|
||||
accounts = [{ uin: '1', uid: 'u1', nickname: 'A', pid: 4242 }];
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
ctx.notifyAccountChange();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
@@ -317,14 +545,12 @@ describe('HookManager periodic account re-probe', () => {
|
||||
const ctx = makeManager({
|
||||
processes: [4242],
|
||||
detectAccounts,
|
||||
accountReprobeIntervalMs: 0,
|
||||
});
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
ctx.notifyAccountChange();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
@@ -340,7 +566,6 @@ describe('HookManager periodic account re-probe', () => {
|
||||
const ctx = makeManager({
|
||||
processes: [4242],
|
||||
detectAccounts: async () => accounts,
|
||||
accountReprobeIntervalMs: 0,
|
||||
});
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
@@ -352,7 +577,7 @@ describe('HookManager periodic account re-probe', () => {
|
||||
{ uin: '1', uid: 'u1', nickname: 'A', pid: null },
|
||||
{ uin: '2', uid: 'u2', nickname: 'B', pid: null },
|
||||
];
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
ctx.notifyAccountChange();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
@@ -361,24 +586,89 @@ describe('HookManager periodic account re-probe', () => {
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('throttles the probe to the configured interval', async () => {
|
||||
it('does not poll unlabelled, unloaded processes even after the old interval expires', async () => {
|
||||
const detectAccounts = vi.fn(async () => [] as AccountLoginState[]);
|
||||
const ctx = makeManager({
|
||||
processes: [4242],
|
||||
detectAccounts,
|
||||
accountReprobeIntervalMs: 60_000,
|
||||
});
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
const baseline = detectAccounts.mock.calls.length;
|
||||
const now = vi.spyOn(Date, 'now');
|
||||
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
try {
|
||||
await ctx.manager.listProcesses();
|
||||
const baseline = detectAccounts.mock.calls.length;
|
||||
const startedAt = Date.now();
|
||||
|
||||
expect(detectAccounts.mock.calls.length).toBe(baseline);
|
||||
for (let tick = 1; tick <= 10; tick++) {
|
||||
now.mockReturnValue(startedAt + tick * 6000);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
expect((await ctx.manager.listProcesses())[0]!.account).toBeNull();
|
||||
}
|
||||
|
||||
ctx.manager.dispose();
|
||||
expect(detectAccounts).toHaveBeenCalledTimes(baseline);
|
||||
} finally {
|
||||
now.mockRestore();
|
||||
ctx.manager.dispose();
|
||||
ctx.pipeWatcher.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not re-probe a mixed set of online and unloaded processes', async () => {
|
||||
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
|
||||
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
|
||||
]);
|
||||
const ctx = makeManager({
|
||||
processes: [4242, 5151],
|
||||
livePipes: [4242],
|
||||
detectAccounts,
|
||||
});
|
||||
const now = vi.spyOn(Date, 'now');
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
|
||||
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
|
||||
expect((await ctx.manager.listProcesses()).map((info) => info.status)).toEqual([
|
||||
'online',
|
||||
'available',
|
||||
]);
|
||||
const baseline = detectAccounts.mock.calls.length;
|
||||
now.mockReturnValue(Date.now() + 60_000);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await ctx.manager.listProcesses();
|
||||
expect(detectAccounts).toHaveBeenCalledTimes(baseline);
|
||||
} finally {
|
||||
now.mockRestore();
|
||||
ctx.manager.dispose();
|
||||
ctx.pipeWatcher.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('releases file subscriptions when the process set changes and the manager stops', async () => {
|
||||
const ctx = makeManager({ processes: [4242] });
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
expect(ctx.watchAccounts).toHaveBeenLastCalledWith([4242], expect.any(Function));
|
||||
const firstStop = ctx.watchAccounts.mock.results.at(-1)!.value;
|
||||
ctx.setProcesses([4242, 5151]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
expect(firstStop).toHaveBeenCalledOnce();
|
||||
expect(ctx.watchAccounts).toHaveBeenLastCalledWith([4242, 5151], expect.any(Function));
|
||||
const secondStop = ctx.watchAccounts.mock.results.at(-1)!.value;
|
||||
ctx.setProcesses([5151]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(secondStop).toHaveBeenCalledOnce();
|
||||
expect(ctx.watchAccounts).toHaveBeenLastCalledWith([5151], expect.any(Function));
|
||||
const finalStop = ctx.watchAccounts.mock.results.at(-1)!.value;
|
||||
ctx.manager.dispose();
|
||||
expect(finalStop).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
ctx.manager.dispose();
|
||||
ctx.pipeWatcher.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps working when detection fails, and reports the failure once', async () => {
|
||||
@@ -387,7 +677,6 @@ describe('HookManager periodic account re-probe', () => {
|
||||
detectAccounts: async () => {
|
||||
throw new Error('login.db unreadable');
|
||||
},
|
||||
accountReprobeIntervalMs: 0,
|
||||
});
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
|
||||
@@ -80,6 +80,7 @@ function makeManager(opts: {
|
||||
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
// Detection reads QQ's own data directories; tests stay off the host.
|
||||
detectAccounts: opts.detectAccounts ?? (async () => []),
|
||||
watchAccounts: () => () => {},
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
|
||||
@@ -72,6 +72,7 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
autoLoadOnDiscovery: true,
|
||||
listProcesses: async () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
detectAccounts: async () => [],
|
||||
watchAccounts: () => () => {},
|
||||
});
|
||||
|
||||
// Initial discovery + first connect.
|
||||
|
||||
@@ -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';
|
||||
@@ -30,6 +30,7 @@ class FakeClient extends EventEmitter {
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
shouldFailConnect = false;
|
||||
runtimeErrorOnConnect = false;
|
||||
nativeReadyOnIdentityHint = false;
|
||||
identityHintFailures = 0;
|
||||
sendError: Error | null = null;
|
||||
@@ -38,6 +39,10 @@ class FakeClient extends EventEmitter {
|
||||
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
|
||||
async connectAll(_opts: { recv: boolean }): Promise<void> {
|
||||
if (this.runtimeErrorOnConnect) {
|
||||
this.emit('runtimeError', new Error('QQ service unavailable'));
|
||||
}
|
||||
|
||||
if (this.shouldFailConnect) {
|
||||
throw new Error('connect failed');
|
||||
}
|
||||
@@ -102,10 +107,12 @@ function makeSession(
|
||||
pid?: number;
|
||||
pipeLive?: boolean;
|
||||
clientFailsConnect?: boolean;
|
||||
runtimeErrorOnConnect?: boolean;
|
||||
onPacket?: PacketSink;
|
||||
detectLoginUin?: (pid: number) => Promise<string | null>;
|
||||
nativeReadyOnIdentityHint?: boolean;
|
||||
identityHintFailures?: number;
|
||||
connectClient?: (client: FakeClient) => Promise<void>;
|
||||
} = {},
|
||||
) {
|
||||
const pid = opts.pid ?? 1234;
|
||||
@@ -123,6 +130,7 @@ function makeSession(
|
||||
injector,
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
c.runtimeErrorOnConnect = opts.runtimeErrorOnConnect ?? false;
|
||||
|
||||
if (opts.clientFailsConnect) {
|
||||
c.shouldFailConnect = true;
|
||||
@@ -130,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;
|
||||
@@ -152,6 +165,77 @@ function makeSession(
|
||||
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
|
||||
describe('HookSession runtime failure', () => {
|
||||
it('retains an initialization error instead of waiting for login', async () => {
|
||||
const { session } = makeSession({ pipeLive: true, runtimeErrorOnConnect: true });
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
expect(session.toInfo()).toMatchObject({
|
||||
status: 'error',
|
||||
error: 'QQ service unavailable',
|
||||
connected: false,
|
||||
});
|
||||
session.dispose();
|
||||
});
|
||||
|
||||
it('keeps a late runtime error visible across refresh and login snapshots', async () => {
|
||||
const { session, currentClient, setPipeLive } = makeSession({ pipeLive: true });
|
||||
const disconnect = vi.fn();
|
||||
session.on('disconnected', disconnect);
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
currentClient().fireLogin('10001');
|
||||
currentClient().emit('runtimeError', new Error('QQ service unavailable'));
|
||||
currentClient().emit('error', new Error('connection closed'));
|
||||
expect(session.error).toBe('QQ service unavailable');
|
||||
currentClient().fireLogin('10001');
|
||||
await session.refresh();
|
||||
expect(session.toInfo()).toMatchObject({
|
||||
status: 'error',
|
||||
error: 'QQ service unavailable',
|
||||
loggedIn: false,
|
||||
});
|
||||
setPipeLive(false);
|
||||
await session.refresh();
|
||||
expect(disconnect).toHaveBeenCalledExactlyOnceWith(true);
|
||||
setPipeLive(true);
|
||||
await session.refresh();
|
||||
currentClient().fireLogin('10001');
|
||||
expect(session.toInfo()).toMatchObject({ status: 'online', loggedIn: true, error: '' });
|
||||
session.dispose();
|
||||
});
|
||||
|
||||
it('retains the failure when the pipe closes and discards an in-flight login lookup', async () => {
|
||||
let resolveLogin!: (uin: string) => void;
|
||||
const { session, currentClient, setPipeLive } = makeSession({
|
||||
pipeLive: true,
|
||||
detectLoginUin: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveLogin = resolve;
|
||||
}),
|
||||
});
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
const client = currentClient();
|
||||
client.emit('runtimeError', new Error('QQ service unavailable'));
|
||||
resolveLogin('10001');
|
||||
await flush();
|
||||
expect(client.loginIdentityHints).toEqual([]);
|
||||
setPipeLive(false);
|
||||
await session.refresh();
|
||||
expect(session.toInfo()).toMatchObject({
|
||||
status: 'error',
|
||||
error: 'QQ service unavailable',
|
||||
loggedIn: false,
|
||||
connected: false,
|
||||
});
|
||||
session.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — runtime TRACE', () => {
|
||||
it('records injection and existing-pipe load branches with unique terminals', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
@@ -521,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 });
|
||||
@@ -929,6 +1329,42 @@ describe('HookSession — pipe-down must not clobber a settled error', () => {
|
||||
});
|
||||
|
||||
describe('HookSession — packet forwarding', () => {
|
||||
it('forwards client receipts only for the active account without changing direction', async () => {
|
||||
const onPacket = vi.fn();
|
||||
const ctx = makeSession({ pipeLive: true, onPacket });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
const receipt: QqHookPacket = {
|
||||
seq: 42,
|
||||
error: 0,
|
||||
cmd: 'ClientMessageReceipt',
|
||||
uin: '10001',
|
||||
source: 'client-message',
|
||||
body: Buffer.from([1, 2, 3]),
|
||||
};
|
||||
|
||||
for (const uin of ['', '0', '20002']) {
|
||||
ctx.currentClient().firePacket({ ...receipt, uin });
|
||||
}
|
||||
|
||||
expect(onPacket).not.toHaveBeenCalled();
|
||||
ctx.currentClient().firePacket(receipt);
|
||||
expect(onPacket).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({
|
||||
pid: 1234,
|
||||
uin: '10001',
|
||||
source: 'client-message',
|
||||
fromClient: false,
|
||||
}),
|
||||
);
|
||||
ctx.currentClient().fireLogin('20002');
|
||||
ctx.currentClient().firePacket(receipt);
|
||||
expect(onPacket).toHaveBeenCalledOnce();
|
||||
await ctx.session.dispose();
|
||||
});
|
||||
|
||||
// These tests cover the field-rename + filter logic that used to live
|
||||
// inside the deleted NtqqHandler.onHookPacket. Inlining it here means
|
||||
// we can exercise the transformation with a plain vi.fn() sink, no
|
||||
@@ -1043,6 +1479,302 @@ describe('HookSession — packet forwarding', () => {
|
||||
});
|
||||
|
||||
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
|
||||
it.each([
|
||||
{ uin: '1700000000000', uinNumber: 1700000000000n },
|
||||
{ uin: 'not-an-account', uinNumber: 0n },
|
||||
{ uin: '0', uinNumber: 0n },
|
||||
{ uin: '', uinNumber: 1700000000000n },
|
||||
])(
|
||||
'reconciles a rejected login identity received during connection: $uin',
|
||||
async (identity) => {
|
||||
vi.useFakeTimers();
|
||||
setLogLevel('warn');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const detectLoginUin = vi.fn(async () => '10001');
|
||||
const onPacket = vi.fn<PacketSink>();
|
||||
const state = { loggedIn: true, ...identity };
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
detectLoginUin,
|
||||
onPacket,
|
||||
connectClient: async (client) => client.reconcileLoginState(state),
|
||||
});
|
||||
const login = vi.fn();
|
||||
ctx.session.on('login', login);
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
expect(ctx.session.toInfo()).toMatchObject({
|
||||
connected: true,
|
||||
loggedIn: false,
|
||||
status: 'loaded',
|
||||
uin: '0',
|
||||
});
|
||||
expect(login).not.toHaveBeenCalled();
|
||||
|
||||
const packet = {
|
||||
seq: 1,
|
||||
error: 0,
|
||||
cmd: 'Test.Message',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
};
|
||||
ctx.currentClient().firePacket(packet);
|
||||
expect(onPacket).not.toHaveBeenCalled();
|
||||
ctx.currentClient().reconcileLoginState(state);
|
||||
await vi.advanceTimersByTimeAsync(9000);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
expect(
|
||||
entries
|
||||
.filter((entry) => entry.scope === 'HookSession' && entry.level === 'warn')
|
||||
.map((entry) => entry.message),
|
||||
).toEqual(['Login readiness rejected: PID=1234 reason=invalid_account_identity']);
|
||||
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
ctx.currentClient().firePacket(packet);
|
||||
expect(login).toHaveBeenCalledOnce();
|
||||
expect(onPacket).toHaveBeenCalledOnce();
|
||||
expect(ctx.session.toInfo()).toMatchObject({
|
||||
loggedIn: true,
|
||||
status: 'online',
|
||||
uin: '10001',
|
||||
});
|
||||
const detections = detectLoginUin.mock.calls.length;
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(detectLoginUin).toHaveBeenCalledTimes(detections);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
unsubscribe();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('revokes a ready account and starts a fresh identity check when login readiness is lost', async () => {
|
||||
vi.useFakeTimers();
|
||||
const ctx = makeSession({ pipeLive: true, detectLoginUin: async () => '10001' });
|
||||
const login = vi.fn();
|
||||
const disconnected = vi.fn();
|
||||
ctx.session.on('login', login);
|
||||
ctx.session.on('disconnected', disconnected);
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
expect(login).toHaveBeenCalledOnce();
|
||||
|
||||
ctx.currentClient().fireLogin('1700000000000');
|
||||
ctx.currentClient().fireLogin('1700000000001');
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(disconnected).toHaveBeenCalledExactlyOnceWith(true);
|
||||
expect(ctx.session.toInfo()).toMatchObject({
|
||||
status: 'loaded',
|
||||
loggedIn: false,
|
||||
uin: '0',
|
||||
});
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']);
|
||||
expect(login).toHaveBeenCalledOnce();
|
||||
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
expect(login).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.session.status).toBe('online');
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not probe a rejected login identity before a stalled connection times out', async () => {
|
||||
vi.useFakeTimers();
|
||||
const handshake = Promise.withResolvers<void>();
|
||||
const detectLoginUin = vi.fn(async () => '10001');
|
||||
const ctx = makeSession({ detectLoginUin, connectClient: () => handshake.promise });
|
||||
const login = vi.fn();
|
||||
ctx.session.on('login', login);
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.setPipeLive(true);
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
const previous = ctx.currentClient();
|
||||
previous.fireLogin('1700000000000');
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(ctx.session.toInfo()).toMatchObject({
|
||||
status: 'error',
|
||||
connected: false,
|
||||
loggedIn: false,
|
||||
});
|
||||
expect(detectLoginUin).not.toHaveBeenCalled();
|
||||
expect(previous.isClosed).toBe(true);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
|
||||
previous.fireLogin('10001');
|
||||
handshake.resolve();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(login).not.toHaveBeenCalled();
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.currentClient()).not.toBe(previous);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
expect(ctx.session.toInfo()).toMatchObject({
|
||||
status: 'loaded',
|
||||
connected: true,
|
||||
loggedIn: false,
|
||||
});
|
||||
} finally {
|
||||
handshake.resolve();
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('discards an identity acknowledgement from before login readiness was lost', async () => {
|
||||
vi.useFakeTimers();
|
||||
const hint = Promise.withResolvers<void>();
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
detectLoginUin: async () => '10001',
|
||||
connectClient: async (client) => {
|
||||
vi.spyOn(client, 'reconcileLoginIdentity').mockImplementationOnce(async (uin) => {
|
||||
client.loginIdentityHints.push(uin);
|
||||
await hint.promise;
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
ctx.currentClient().fireLogin('1700000000000');
|
||||
hint.resolve();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']);
|
||||
expect(ctx.session.toInfo()).toMatchObject({ status: 'loaded', loggedIn: false });
|
||||
} finally {
|
||||
hint.resolve();
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('discards an account observation from before login readiness was lost', async () => {
|
||||
vi.useFakeTimers();
|
||||
const observation = Promise.withResolvers<string | null>();
|
||||
const detectLoginUin = vi.fn<() => Promise<string | null>>().mockResolvedValue('20002');
|
||||
detectLoginUin.mockReturnValueOnce(observation.promise);
|
||||
const ctx = makeSession({ pipeLive: true, detectLoginUin });
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
ctx.currentClient().fireLogin('1700000000000');
|
||||
observation.resolve('10001');
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual([]);
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['20002']);
|
||||
} finally {
|
||||
observation.resolve(null);
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['observation', 'hint'] as const)(
|
||||
'ignores a late %s failure after login readiness is confirmed',
|
||||
async (phase) => {
|
||||
vi.useFakeTimers();
|
||||
setLogLevel('trace');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const pending = Promise.withResolvers<void>();
|
||||
const detectLoginUin = vi.fn(async () => {
|
||||
if (phase === 'observation') {
|
||||
await pending.promise;
|
||||
}
|
||||
|
||||
return '10001';
|
||||
});
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
detectLoginUin,
|
||||
connectClient: async (client) => {
|
||||
if (phase === 'hint') {
|
||||
vi.spyOn(client, 'reconcileLoginIdentity').mockImplementationOnce(
|
||||
async (uin) => {
|
||||
client.loginIdentityHints.push(uin);
|
||||
await pending.promise;
|
||||
},
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(detectLoginUin).toHaveBeenCalledOnce();
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(
|
||||
phase === 'hint' ? ['10001'] : [],
|
||||
);
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
entries.length = 0;
|
||||
pending.reject(new Error('expired identity request'));
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(
|
||||
entries.some((entry) => entry.message.includes('expired identity request')),
|
||||
).toBe(false);
|
||||
expect(detectLoginUin).toHaveBeenCalledOnce();
|
||||
expect(ctx.session.toInfo()).toMatchObject({
|
||||
status: 'online',
|
||||
loggedIn: true,
|
||||
uin: '10001',
|
||||
});
|
||||
} finally {
|
||||
pending.resolve();
|
||||
ctx.session.dispose();
|
||||
unsubscribe();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('clears the login check timer when identity detection disposes the session synchronously', async () => {
|
||||
vi.useFakeTimers();
|
||||
const detectLoginUin = vi.fn<() => Promise<string | null>>();
|
||||
const ctx = makeSession({ pipeLive: true, detectLoginUin });
|
||||
detectLoginUin.mockImplementation(async () => {
|
||||
ctx.session.dispose();
|
||||
return null;
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.session.isDisposed).toBe(true);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('discards an identity read started before a pipe reconnect', async () => {
|
||||
const detection = Promise.withResolvers<string | null>();
|
||||
const ctx = makeSession({ pipeLive: true, detectLoginUin: () => detection.promise });
|
||||
|
||||
86
packages/bridge/tests/qq-account-watch.integration.test.ts
Normal file
86
packages/bridge/tests/qq-account-watch.integration.test.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdtemp, mkdir, rename, rm, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { watchAccountFiles } from '../src/qq-account/watch';
|
||||
|
||||
// Keep native filesystem coverage aligned with qqDataRootsForPid's supported platforms.
|
||||
// macOS is only a development host here: fs.watch() can return before FSEvents
|
||||
// registration, losing immediate writes. Deterministic logic tests run on every OS.
|
||||
describe.skipIf(process.platform !== 'win32' && process.platform !== 'linux')(
|
||||
'account file changes on supported filesystems',
|
||||
() => {
|
||||
let root: string;
|
||||
const subscriptions: Array<() => void> = [];
|
||||
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-account-watch-'));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
for (const stop of subscriptions.splice(0)) {
|
||||
stop();
|
||||
}
|
||||
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function subscribe(dbPaths = [path.join(root, 'login.db')]) {
|
||||
const changed = vi.fn();
|
||||
subscriptions.push(watchAccountFiles(dbPaths, changed));
|
||||
return changed;
|
||||
}
|
||||
|
||||
it('observes database and WAL changes while ignoring message data and SHM', async () => {
|
||||
const dbPath = path.join(root, 'login.db');
|
||||
const changed = subscribe([dbPath, dbPath]);
|
||||
await writeFile(dbPath, 'login');
|
||||
await vi.waitFor(() => expect(changed).toHaveBeenCalled());
|
||||
const afterDatabase = changed.mock.calls.length;
|
||||
await writeFile(`${dbPath}-wal`, 'wal');
|
||||
await vi.waitFor(() =>
|
||||
expect(changed.mock.calls.length).toBeGreaterThan(afterDatabase),
|
||||
);
|
||||
const afterWal = changed.mock.calls.length;
|
||||
await writeFile(path.join(root, 'nt_msg.db'), 'message');
|
||||
await writeFile(`${dbPath}-shm`, 'shared memory');
|
||||
await delay(350);
|
||||
expect(changed).toHaveBeenCalledTimes(afterWal);
|
||||
});
|
||||
|
||||
it('observes database replacement and WAL recreation', async () => {
|
||||
const dbPath = path.join(root, 'login.db');
|
||||
await writeFile(dbPath, 'initial');
|
||||
const changed = subscribe();
|
||||
await writeFile(path.join(root, 'replacement'), 'replacement');
|
||||
await rename(path.join(root, 'replacement'), dbPath);
|
||||
await vi.waitFor(() => expect(changed).toHaveBeenCalled());
|
||||
const afterReplacement = changed.mock.calls.length;
|
||||
await writeFile(dbPath, 'updated');
|
||||
await vi.waitFor(() =>
|
||||
expect(changed.mock.calls.length).toBeGreaterThan(afterReplacement),
|
||||
);
|
||||
const afterUpdate = changed.mock.calls.length;
|
||||
await writeFile(`${dbPath}-wal`, 'wal');
|
||||
await vi.waitFor(() => expect(changed.mock.calls.length).toBeGreaterThan(afterUpdate));
|
||||
const afterWal = changed.mock.calls.length;
|
||||
await rm(`${dbPath}-wal`);
|
||||
await writeFile(`${dbPath}-wal`, 'new wal');
|
||||
await vi.waitFor(() => expect(changed.mock.calls.length).toBeGreaterThan(afterWal));
|
||||
});
|
||||
|
||||
it('starts watching login data created after QQ process discovery', async () => {
|
||||
const dbPath = path.join(root, 'QQ', 'global', 'nt_db', 'login.db');
|
||||
const changed = subscribe([dbPath]);
|
||||
await mkdir(path.dirname(dbPath), { recursive: true });
|
||||
await writeFile(dbPath, 'initial');
|
||||
await vi.waitFor(() => expect(changed).toHaveBeenCalled());
|
||||
const afterDatabase = changed.mock.calls.length;
|
||||
await writeFile(`${dbPath}-wal`, 'login');
|
||||
await vi.waitFor(() =>
|
||||
expect(changed.mock.calls.length).toBeGreaterThan(afterDatabase),
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
253
packages/bridge/tests/qq-account-watch.test.ts
Normal file
253
packages/bridge/tests/qq-account-watch.test.ts
Normal file
@@ -0,0 +1,253 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import type { FSWatcher, WatchListener } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { watchAccountChangesForPids, watchAccountFiles } from '../src/qq-account/watch';
|
||||
|
||||
const files = vi.hoisted(() => ({
|
||||
watch: vi.fn<
|
||||
(
|
||||
directory: string,
|
||||
options: { persistent: boolean },
|
||||
listener: WatchListener<string>,
|
||||
) => FSWatcher
|
||||
>(),
|
||||
}));
|
||||
|
||||
vi.mock('node:fs', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('node:fs')>()),
|
||||
watch: files.watch,
|
||||
}));
|
||||
|
||||
class TestWatcher extends EventEmitter implements FSWatcher {
|
||||
// Keep callbacks reachable after close to exercise queued, stale events.
|
||||
close = vi.fn();
|
||||
ref() {
|
||||
return this;
|
||||
}
|
||||
unref() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
const root = path.resolve('account-watch-fixture');
|
||||
const directories = new Set<string>();
|
||||
const watchers: TestWatcher[] = [];
|
||||
const subscriptions: Array<() => void> = [];
|
||||
const platform = process.platform;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
directories.add(root);
|
||||
files.watch.mockImplementation((directory, _options, listener) => {
|
||||
if (!directories.has(directory)) {
|
||||
throw Object.assign(new Error('directory missing'), { code: 'ENOENT' });
|
||||
}
|
||||
|
||||
const watcher = new TestWatcher();
|
||||
watcher.on('change', listener);
|
||||
watchers.push(watcher);
|
||||
return watcher;
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const stop of subscriptions.splice(0)) {
|
||||
stop();
|
||||
}
|
||||
|
||||
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
|
||||
watchers.length = 0;
|
||||
directories.clear();
|
||||
files.watch.mockReset();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function subscribe(dbPaths = [path.join(root, 'login.db')]) {
|
||||
const changed = vi.fn();
|
||||
const log = createLogger('AccountWatchTest');
|
||||
const warning = vi.spyOn(log, 'warn');
|
||||
const stop = watchAccountFiles(dbPaths, changed, log);
|
||||
subscriptions.push(stop);
|
||||
return { changed, stop, warning };
|
||||
}
|
||||
|
||||
// Native filesystem delivery is covered separately on the production platforms.
|
||||
// These tests control event ordering and the debounce clock, not OS startup timing.
|
||||
describe('account file changes', () => {
|
||||
it('coalesces login database and WAL changes while ignoring message data and SHM', () => {
|
||||
const dbPath = path.join(root, 'login.db');
|
||||
const { changed } = subscribe([dbPath, dbPath]);
|
||||
expect(files.watch).toHaveBeenCalledExactlyOnceWith(
|
||||
root,
|
||||
{ persistent: false },
|
||||
expect.any(Function),
|
||||
);
|
||||
const watcher = watchers[0]!;
|
||||
watcher.emit('change', 'change', 'login.db');
|
||||
vi.advanceTimersByTime(100);
|
||||
watcher.emit('change', 'change', 'login.db-wal');
|
||||
vi.advanceTimersByTime(249);
|
||||
expect(changed).not.toHaveBeenCalled();
|
||||
watcher.emit('change', 'change', 'nt_msg.db');
|
||||
watcher.emit('change', 'change', 'login.db-shm');
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(changed).toHaveBeenCalledOnce();
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(changed).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('keeps the directory watch across database replacement and WAL recreation', () => {
|
||||
const { changed } = subscribe();
|
||||
const watcher = watchers[0]!;
|
||||
watcher.emit('change', 'rename', 'replacement');
|
||||
vi.advanceTimersByTime(250);
|
||||
expect(changed).not.toHaveBeenCalled();
|
||||
watcher.emit('change', 'rename', 'login.db');
|
||||
vi.advanceTimersByTime(250);
|
||||
watcher.emit('change', 'change', 'login.db');
|
||||
vi.advanceTimersByTime(250);
|
||||
watcher.emit('change', 'rename', 'login.db-wal');
|
||||
vi.advanceTimersByTime(250);
|
||||
watcher.emit('change', 'rename', 'login.db-wal');
|
||||
watcher.emit('change', 'rename', 'login.db-wal');
|
||||
vi.advanceTimersByTime(250);
|
||||
expect(changed).toHaveBeenCalledTimes(4);
|
||||
expect(files.watch).toHaveBeenCalledOnce();
|
||||
expect(watcher.close).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('moves to newly created directories one level at a time', () => {
|
||||
const dbDirectory = path.join(root, 'QQ', 'global', 'nt_db');
|
||||
const { changed } = subscribe([path.join(dbDirectory, 'login.db')]);
|
||||
const ancestor = watchers[0]!;
|
||||
const attempts = files.watch.mock.calls.length;
|
||||
ancestor.emit('change', 'rename', 'unrelated');
|
||||
ancestor.emit('change', 'change', 'login.db-wal');
|
||||
expect(files.watch).toHaveBeenCalledTimes(attempts);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
|
||||
let directory = root;
|
||||
|
||||
for (const segment of ['QQ', 'global', 'nt_db']) {
|
||||
directory = path.join(directory, segment);
|
||||
directories.add(directory);
|
||||
const previous = watchers.at(-1)!;
|
||||
previous.emit('change', 'rename', segment);
|
||||
expect(previous.close).toHaveBeenCalledOnce();
|
||||
expect(files.watch).toHaveBeenLastCalledWith(
|
||||
directory,
|
||||
{ persistent: false },
|
||||
expect.any(Function),
|
||||
);
|
||||
}
|
||||
|
||||
vi.advanceTimersByTime(250);
|
||||
expect(changed).toHaveBeenCalledOnce();
|
||||
watchers.at(-1)!.emit('change', 'change', 'login.db-wal');
|
||||
vi.advanceTimersByTime(250);
|
||||
expect(changed).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each(['QQ', null])(
|
||||
'observes an entire new directory tree from a %s ancestor event',
|
||||
(filename) => {
|
||||
const dbDirectory = path.join(root, 'QQ', 'global', 'nt_db');
|
||||
const { changed, warning } = subscribe([path.join(dbDirectory, 'login.db')]);
|
||||
const ancestor = watchers[0]!;
|
||||
directories.add(dbDirectory);
|
||||
ancestor.emit('change', 'rename', filename);
|
||||
expect(ancestor.close).toHaveBeenCalledOnce();
|
||||
expect(files.watch).toHaveBeenLastCalledWith(
|
||||
dbDirectory,
|
||||
{ persistent: false },
|
||||
expect.any(Function),
|
||||
);
|
||||
const attempts = files.watch.mock.calls.length;
|
||||
vi.advanceTimersByTime(250);
|
||||
expect(changed).toHaveBeenCalledOnce();
|
||||
|
||||
ancestor.emit('change', 'rename', 'QQ');
|
||||
ancestor.emit('error', new Error('late error'));
|
||||
vi.advanceTimersByTime(250);
|
||||
expect(files.watch).toHaveBeenCalledTimes(attempts);
|
||||
expect(changed).toHaveBeenCalledOnce();
|
||||
expect(warning).not.toHaveBeenCalled();
|
||||
watchers.at(-1)!.emit('change', 'change', 'login.db-wal');
|
||||
vi.advanceTimersByTime(250);
|
||||
expect(changed).toHaveBeenCalledTimes(2);
|
||||
},
|
||||
);
|
||||
|
||||
it('notifies when the filesystem does not supply a filename', () => {
|
||||
const { changed } = subscribe();
|
||||
watchers[0]!.emit('change', 'change', null);
|
||||
vi.advanceTimersByTime(250);
|
||||
expect(changed).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('closes every watcher and cancels pending notifications on disposal', () => {
|
||||
const { changed, stop, warning } = subscribe([
|
||||
path.join(root, 'login.db'),
|
||||
path.join(root, 'other', 'login.db'),
|
||||
]);
|
||||
expect(watchers).toHaveLength(2);
|
||||
watchers[0]!.emit('change', 'change', 'login.db');
|
||||
vi.advanceTimersByTime(30);
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
stop();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
|
||||
for (const watcher of watchers) {
|
||||
expect(watcher.close).toHaveBeenCalledOnce();
|
||||
watcher.emit('change', 'rename', null);
|
||||
watcher.emit('error', new Error('late error'));
|
||||
}
|
||||
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(changed).not.toHaveBeenCalled();
|
||||
expect(warning).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports watch failures without starting a polling fallback', () => {
|
||||
files.watch.mockImplementationOnce(() => {
|
||||
throw Object.assign(new Error('access denied'), { code: 'EACCES' });
|
||||
});
|
||||
const { changed, warning } = subscribe();
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
'account watch failed: path=%s err=%s',
|
||||
path.join(root, 'login.db'),
|
||||
'access denied',
|
||||
);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(files.watch).toHaveBeenCalledOnce();
|
||||
expect(changed).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports asynchronous watch errors and closes the failed watcher', () => {
|
||||
const { changed, warning } = subscribe();
|
||||
const watcher = watchers[0]!;
|
||||
watcher.emit('error', new Error('watch unavailable'));
|
||||
expect(watcher.close).toHaveBeenCalledOnce();
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
'account watch failed: path=%s err=%s',
|
||||
path.join(root, 'login.db'),
|
||||
'watch unavailable',
|
||||
);
|
||||
watcher.emit('change', 'change', 'login.db');
|
||||
vi.advanceTimersByTime(250);
|
||||
expect(changed).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not start account file watchers through the production entry point on macOS', () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
|
||||
const changed = vi.fn();
|
||||
subscriptions.push(watchAccountChangesForPids([123], changed));
|
||||
expect(files.watch).not.toHaveBeenCalled();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
expect(changed).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
type LogEntry,
|
||||
} 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,
|
||||
@@ -84,6 +86,7 @@ function readSendFrame(payload: Buffer): {
|
||||
function mockControlPipe(
|
||||
pid: number,
|
||||
onWrite: (socket: net.Socket, payload: Buffer) => void,
|
||||
...startupFrames: Buffer[]
|
||||
): ReturnType<typeof vi.spyOn> {
|
||||
return vi.spyOn(net, 'createConnection').mockImplementation((() => {
|
||||
const socket = new Duplex({
|
||||
@@ -100,10 +103,13 @@ function mockControlPipe(
|
||||
queueMicrotask(() =>
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({
|
||||
op: PipeOp.hello,
|
||||
value0: BigInt(pid),
|
||||
}),
|
||||
Buffer.concat([
|
||||
pipeFrame({
|
||||
op: PipeOp.hello,
|
||||
value0: BigInt(pid),
|
||||
}),
|
||||
...startupFrames,
|
||||
]),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -117,6 +123,144 @@ 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,
|
||||
cmd: 'runtime',
|
||||
status: -1,
|
||||
message: 'QQ service unavailable',
|
||||
});
|
||||
|
||||
it('rejects startup when a runtime failure follows hello in the same read', async () => {
|
||||
const connection = mockControlPipe(778901, () => {}, failureFrame);
|
||||
const client = new QqHookClient(778901);
|
||||
const failure = vi.fn();
|
||||
client.on('runtimeError', failure);
|
||||
|
||||
try {
|
||||
await expect(client.connect()).rejects.toThrow('QQ service unavailable');
|
||||
expect(failure).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({ status: -1, requestId: 0 }),
|
||||
);
|
||||
} finally {
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects pending and future requests on a runtime failure', async () => {
|
||||
const connection = mockControlPipe(778902, (socket) => {
|
||||
queueMicrotask(() => socket.emit('data', failureFrame));
|
||||
});
|
||||
const client = new QqHookClient(778902);
|
||||
|
||||
try {
|
||||
await expect(client.sendAndWait('Test', Buffer.alloc(0))).rejects.toThrow(
|
||||
'QQ service unavailable',
|
||||
);
|
||||
await expect(client.sendAndWait('Test', Buffer.alloc(0))).rejects.toThrow(
|
||||
'QQ service unavailable',
|
||||
);
|
||||
await expect(client.startRecv()).rejects.toThrow('QQ service unavailable');
|
||||
await expect(client.waitForLogin()).rejects.toThrow('QQ service unavailable');
|
||||
} finally {
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects login and queued writes when the runtime fails as a connection resumes', async () => {
|
||||
const onWrite = vi.fn();
|
||||
const sockets = mockControlPipe(778903, onWrite);
|
||||
const client = new QqHookClient(778903);
|
||||
|
||||
try {
|
||||
await client.connect();
|
||||
const waiting = client.waitForLogin({ timeoutMs: 100 });
|
||||
const sending = client.sendNoReply('Test', Buffer.alloc(0), { ackTimeoutMs: 100 });
|
||||
const settled = Promise.allSettled([waiting, sending]);
|
||||
sockets.mock.results[0]!.value.emit('data', failureFrame);
|
||||
|
||||
const expected = {
|
||||
status: 'rejected',
|
||||
reason: expect.objectContaining({ message: 'QQ service unavailable' }),
|
||||
};
|
||||
expect(await settled).toEqual([expected, expected]);
|
||||
expect(onWrite).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
client.close();
|
||||
sockets.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function runtimeTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'QQHook.Runtime');
|
||||
}
|
||||
@@ -147,6 +291,122 @@ describe('QqHookClient login wait lifecycle', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('QqHookClient client message receipts', () => {
|
||||
it('preserves receipt provenance and failure status separately from normal packets', async () => {
|
||||
const sockets = mockControlPipe(12345, () => {});
|
||||
const client = new QqHookClient(12345);
|
||||
const onPacket = vi.fn();
|
||||
|
||||
try {
|
||||
await client.startRecv(onPacket);
|
||||
const socket = sockets.mock.results[0]!.value;
|
||||
const body = Buffer.from([1, 2, 3]);
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({ op: PipeOp.clientMessageReceipt, value0: 42n, message: '10001', body }),
|
||||
);
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({
|
||||
op: PipeOp.clientMessageReceipt,
|
||||
value0: 43n,
|
||||
message: '10001',
|
||||
status: -1,
|
||||
}),
|
||||
);
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({
|
||||
op: PipeOp.recvPacket,
|
||||
value0: 44n,
|
||||
message: '10001',
|
||||
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
|
||||
body,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(onPacket.mock.calls.map(([packet]) => packet)).toEqual([
|
||||
{
|
||||
seq: 42,
|
||||
error: 0,
|
||||
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
|
||||
uin: '10001',
|
||||
body,
|
||||
source: 'client-message',
|
||||
},
|
||||
{
|
||||
seq: 43,
|
||||
error: -1,
|
||||
cmd: CLIENT_MESSAGE_RECEIPT_CMD,
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
source: 'client-message',
|
||||
},
|
||||
{ seq: 44, error: 0, cmd: CLIENT_MESSAGE_RECEIPT_CMD, uin: '10001', body },
|
||||
]);
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports unsupported capability and invalid envelopes without breaking normal receive', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('warn');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const sockets = mockControlPipe(12345, () => {});
|
||||
const client = new QqHookClient(12345);
|
||||
const onPacket = vi.fn();
|
||||
|
||||
try {
|
||||
await client.startRecv(onPacket);
|
||||
const socket = sockets.mock.results[0]!.value;
|
||||
socket.emit('data', pipeFrame({ op: PipeOp.clientMessageState, status: -1 }));
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({ op: PipeOp.clientMessageState, status: -1, value0: 42n }),
|
||||
);
|
||||
const warning = 'Client private-message reporting is unavailable: PID=12345 status=-1';
|
||||
expect(entries.map((entry) => entry.message)).toEqual([
|
||||
warning,
|
||||
`${warning} reason=42`,
|
||||
]);
|
||||
|
||||
for (const patch of [
|
||||
{ value0: 0n },
|
||||
{ value0: BigInt(Number.MAX_SAFE_INTEGER) + 1n },
|
||||
{ message: '' },
|
||||
{ cmd: 'unexpected' },
|
||||
{ requestId: 1 },
|
||||
]) {
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({
|
||||
op: PipeOp.clientMessageReceipt,
|
||||
value0: 42n,
|
||||
message: '10001',
|
||||
...patch,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
expect(onPacket).not.toHaveBeenCalled();
|
||||
expect(
|
||||
entries.filter(
|
||||
(entry) => entry.scope === 'QQHook.Runtime' && entry.level === 'warn',
|
||||
),
|
||||
).toHaveLength(7);
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({ op: PipeOp.recvPacket, cmd: 'normal', message: '10001', value0: 44n }),
|
||||
);
|
||||
expect(onPacket).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
client.close();
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('listLiveLinuxPipePids', () => {
|
||||
it('ignores stale-looking control socket names when the probe rejects them', async () => {
|
||||
const runtimeDir = await makeRuntimeDir();
|
||||
|
||||
40
packages/common/bench/logger.bench.ts
Normal file
40
packages/common/bench/logger.bench.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
// pnpm --filter @snowluma/common exec vitest bench --run bench/logger.bench.ts
|
||||
import { bench, describe, vi } from 'vitest';
|
||||
|
||||
vi.stubEnv('SNOWLUMA_LOG_LEVEL', 'trace');
|
||||
vi.stubEnv('SNOWLUMA_LOG_FILE', '0');
|
||||
vi.stubEnv('SNOWLUMA_LOG_FILE_LEVEL', 'debug');
|
||||
vi.stubEnv('SNOWLUMA_TRACE_BUFFER', '5000');
|
||||
const { createLogger, getLogSnapshot, getRecentLogs, setLogLevel } = await import('../src/logger');
|
||||
const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
const log = createLogger('Benchmark');
|
||||
|
||||
for (let i = 0; i < 5000; i += 1) {
|
||||
log.trace('trace %d', i);
|
||||
|
||||
if (i % 5 === 0) {
|
||||
log.info('normal %d', i);
|
||||
}
|
||||
}
|
||||
|
||||
stdout.mockRestore();
|
||||
|
||||
describe('6,000 retained records', () => {
|
||||
bench('recent 30', () => {
|
||||
getRecentLogs(30);
|
||||
});
|
||||
bench('recent 300', () => {
|
||||
getRecentLogs(300);
|
||||
});
|
||||
bench('complete export', () => {
|
||||
getLogSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
setLogLevel('info');
|
||||
|
||||
describe('file-only debug records with disk disabled', () => {
|
||||
bench('format and route debug', () => {
|
||||
log.debug('packet command=%s bytes=%d', 'Example.Service', 1024);
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,21 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/common",
|
||||
"version": "2.0.0",
|
||||
"version": "2.4.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
"./webui-target": {
|
||||
"types": "./src/webui-target.ts",
|
||||
"default": "./src/webui-target.ts"
|
||||
},
|
||||
"./update-source": {
|
||||
"types": "./src/update-source.ts",
|
||||
"default": "./src/update-source.ts"
|
||||
},
|
||||
"./semver": {
|
||||
"types": "./src/semver.ts",
|
||||
"default": "./src/semver.ts"
|
||||
@@ -101,7 +109,7 @@
|
||||
"@types/node": "catalog:",
|
||||
"@types/semver": "7.7.1",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
"vitest": "4.1.12"
|
||||
},
|
||||
"dependencies": {
|
||||
"@zxcvbn-ts/core": "^4.1.2",
|
||||
@@ -110,6 +118,6 @@
|
||||
"semver": "7.7.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
"node": "^24.22.1 || >=26.12.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,33 +82,48 @@ function skipEscSequence(line: string, start: number): number {
|
||||
* invisible payload into persisted or downloaded logs.
|
||||
*/
|
||||
export function sanitizeLogLine(line: string): string {
|
||||
let plain = '';
|
||||
const parts: string[] = [];
|
||||
let start = 0;
|
||||
|
||||
for (let i = 0; i < line.length;) {
|
||||
const code = line.charCodeAt(i);
|
||||
let next: number;
|
||||
|
||||
if (code === ESC) {
|
||||
i = skipEscSequence(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (code === C1_CSI) {
|
||||
i = skipCsi(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (code === C1_OSC || C1_STRING_STARTERS.has(code)) {
|
||||
i = skipControlString(line, i + 1, code === C1_OSC);
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f)) {
|
||||
next = skipEscSequence(line, i + 1);
|
||||
} else if (code === C1_CSI) {
|
||||
next = skipCsi(line, i + 1);
|
||||
} else if (code === C1_OSC || C1_STRING_STARTERS.has(code)) {
|
||||
next = skipControlString(line, i + 1, code === C1_OSC);
|
||||
} else if (
|
||||
(code < 0x20 && code !== 0x09 && code !== 0x0a) ||
|
||||
(code >= 0x7f && code <= 0x9f)
|
||||
) {
|
||||
next = i + 1;
|
||||
} else {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
plain += line[i];
|
||||
i += 1;
|
||||
parts.push(line.slice(start, i));
|
||||
start = next;
|
||||
i = next;
|
||||
}
|
||||
|
||||
if (start === 0) {
|
||||
return line;
|
||||
}
|
||||
|
||||
// Join contiguous spans once. Appending each character creates a retained
|
||||
// V8 cons-string node per character in the in-memory log rings.
|
||||
parts.push(line.slice(start));
|
||||
const plain = parts.join('');
|
||||
|
||||
// A single visible span can remain a slice of the original input after join.
|
||||
// Copy when that would retain more discarded text than visible text. Splitting
|
||||
// into UTF-16 code units preserves unpaired surrogates and works in browsers.
|
||||
if (plain.length > 0 && plain.length < line.length / 2) {
|
||||
return plain.split('').join('');
|
||||
}
|
||||
|
||||
return plain;
|
||||
|
||||
@@ -97,20 +97,13 @@ class RingBuffer<T> {
|
||||
this.start = (this.start + 1) % this.cap;
|
||||
} // full → overwrite oldest
|
||||
}
|
||||
/** Most recent `n` items, oldest→newest. */
|
||||
recent(n: number): T[] {
|
||||
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
|
||||
const out: T[] = new Array<T>(take);
|
||||
const first = this.start + (this.count - take);
|
||||
|
||||
for (let i = 0; i < take; i += 1) {
|
||||
out[i] = this.buf[(first + i) % this.cap]!;
|
||||
/** Read from newest to oldest without copying the retained buffer. */
|
||||
newest(offset: number): T | undefined {
|
||||
if (offset >= this.count) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
toArray(): T[] {
|
||||
return this.recent(this.count);
|
||||
return this.buf[(this.start + this.count - 1 - offset) % this.cap];
|
||||
}
|
||||
get size(): number {
|
||||
return this.count;
|
||||
@@ -282,18 +275,22 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
const formattedMessage = format(...realArgs);
|
||||
const message = level === 'trace' ? formattedMessage : redactLogMessage(formattedMessage);
|
||||
const line = render(level, options, message, reqId);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
...(reqId !== undefined ? { req: reqId } : {}),
|
||||
message,
|
||||
line: sanitizeLogLine(line),
|
||||
};
|
||||
const id = nextLogId++;
|
||||
|
||||
if (passesConsole) {
|
||||
// File-only records are sanitized by the transport and need no memory
|
||||
// entry, ISO timestamp, or second sanitized copy of the rendered line.
|
||||
const entry: LogEntry = {
|
||||
id,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
...(reqId !== undefined ? { req: reqId } : {}),
|
||||
message,
|
||||
line: sanitizeLogLine(line),
|
||||
};
|
||||
|
||||
// Trace gets its own ring so its volume never evicts the normal log buffer.
|
||||
(level === 'trace' ? traceRing : logRing).push(entry);
|
||||
|
||||
@@ -337,10 +334,28 @@ export function closeLogger(): Promise<void> {
|
||||
return getFileTransport().close();
|
||||
}
|
||||
|
||||
function mergeLogRings(): LogEntry[] {
|
||||
return traceRing.size > 0
|
||||
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
|
||||
: logRing.toArray();
|
||||
function mergeLogRings(limit = logRing.size + traceRing.size): LogEntry[] {
|
||||
const take = Math.min(limit, logRing.size + traceRing.size);
|
||||
const entries = new Array<LogEntry>(take);
|
||||
let normalOffset = 0;
|
||||
let traceOffset = 0;
|
||||
|
||||
// Both rings already follow increasing IDs. Merge backwards so a small
|
||||
// WebUI request visits only the requested tail, even with a large TRACE ring.
|
||||
for (let i = take - 1; i >= 0; i -= 1) {
|
||||
const normal = logRing.newest(normalOffset);
|
||||
const trace = traceRing.newest(traceOffset);
|
||||
|
||||
if (normal && (!trace || normal.id > trace.id)) {
|
||||
entries[i] = normal;
|
||||
normalOffset += 1;
|
||||
} else {
|
||||
entries[i] = trace!;
|
||||
traceOffset += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
export function getLogSnapshot(): LogEntry[] {
|
||||
@@ -349,7 +364,8 @@ export function getLogSnapshot(): LogEntry[] {
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
const n = Math.max(1, Math.trunc(limit));
|
||||
return mergeLogRings().slice(-n);
|
||||
// Array.slice(-NaN) previously returned the full snapshot.
|
||||
return mergeLogRings(Number.isNaN(n) ? undefined : n);
|
||||
}
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
export const CLIENT_MESSAGE_RECEIPT_CMD = 'ClientMessageReceipt';
|
||||
|
||||
export interface PacketInfo {
|
||||
pid: number;
|
||||
uin: string;
|
||||
@@ -6,6 +8,7 @@ export interface PacketInfo {
|
||||
seqId: number;
|
||||
retCode: number;
|
||||
fromClient: boolean;
|
||||
source?: 'client-message';
|
||||
body: Uint8Array;
|
||||
}
|
||||
export type PacketSink = (packet: PacketInfo) => void;
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { isObject } from './coerce';
|
||||
import { normalizeUpdateSourceConfig, type UpdateSourceConfig } from './update-source';
|
||||
|
||||
export interface RuntimeConfig {
|
||||
updateSource?: UpdateSourceConfig;
|
||||
webuiPort?: number;
|
||||
/** When true, every newly-discovered QQ process gets auto-injected by
|
||||
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
|
||||
@@ -43,6 +45,9 @@ export const MAX_LOG_RETAIN_DAYS = Math.floor(Number.MAX_SAFE_INTEGER / (24 * 60
|
||||
export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
|
||||
const obj = isObject(parsed) ? parsed : {};
|
||||
return {
|
||||
...(obj.updateSource === undefined
|
||||
? {}
|
||||
: { updateSource: normalizeUpdateSourceConfig(obj.updateSource) }),
|
||||
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
|
||||
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
|
||||
webuiHost: normalizeHost(obj.webuiHost),
|
||||
@@ -217,7 +222,8 @@ function sameRuntimeConfig(parsed: Record<string, unknown>, n: RuntimeConfig): b
|
||||
parsed.trustProxy === n.trustProxy &&
|
||||
parsed.logMaxTotalMb === n.logMaxTotalMb &&
|
||||
parsed.logRetainDays === n.logRetainDays &&
|
||||
parsed.logPerUin === n.logPerUin
|
||||
parsed.logPerUin === n.logPerUin &&
|
||||
JSON.stringify(parsed.updateSource) === JSON.stringify(n.updateSource)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** TTL caching and request deduplication to limit repeated upstream requests. */
|
||||
|
||||
export interface SingleFlightCacheOptions<K, V> {
|
||||
/** Freshness window in ms. A cached entry older than this is reloaded. */
|
||||
/** Freshness window in ms. Expired values are released even while idle. */
|
||||
ttlMs: number;
|
||||
/** Load the value for a key. Rejections propagate and are never cached. */
|
||||
load: (key: K) => Promise<V>;
|
||||
@@ -22,6 +22,8 @@ export class SingleFlightCache<K, V> {
|
||||
private readonly now: () => number;
|
||||
private readonly fresh = new Map<K, { at: number; value: V }>();
|
||||
private readonly inflight = new Map<K, Promise<V>>();
|
||||
private expiryTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
private disposed = false;
|
||||
|
||||
constructor(opts: SingleFlightCacheOptions<K, V>) {
|
||||
this.ttlMs = opts.ttlMs;
|
||||
@@ -30,6 +32,11 @@ export class SingleFlightCache<K, V> {
|
||||
this.now = opts.now ?? Date.now;
|
||||
}
|
||||
|
||||
/** Number of retained values; pending loads are not counted. */
|
||||
get size(): number {
|
||||
return this.fresh.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value for `key`.
|
||||
*
|
||||
@@ -41,10 +48,17 @@ export class SingleFlightCache<K, V> {
|
||||
* rather than starting a second one.
|
||||
*/
|
||||
get(key: K, opts: { force?: boolean } = {}): Promise<V> {
|
||||
if (!opts.force) {
|
||||
const hit = this.fresh.get(key);
|
||||
if (this.disposed) {
|
||||
return Promise.reject(new Error('SingleFlightCache is disposed'));
|
||||
}
|
||||
|
||||
if (hit && this.now() - hit.at < this.ttlMs) {
|
||||
const hit = this.fresh.get(key);
|
||||
|
||||
if (hit) {
|
||||
if (this.now() - hit.at >= this.ttlMs) {
|
||||
this.fresh.delete(key);
|
||||
this.cancelExpiryIfEmpty();
|
||||
} else if (!opts.force) {
|
||||
return Promise.resolve(hit.value);
|
||||
}
|
||||
}
|
||||
@@ -58,8 +72,11 @@ export class SingleFlightCache<K, V> {
|
||||
const load = async (): Promise<V> => {
|
||||
const value = await this.load(key);
|
||||
|
||||
if (this.inflight.get(key) === task && this.shouldCache(value)) {
|
||||
if (this.inflight.get(key) === task && this.ttlMs > 0 && this.shouldCache(value)) {
|
||||
// Keep insertion order aligned with expiry, including refreshes.
|
||||
this.fresh.delete(key);
|
||||
this.fresh.set(key, { at: this.now(), value });
|
||||
this.scheduleExpiry();
|
||||
}
|
||||
|
||||
return value;
|
||||
@@ -78,12 +95,58 @@ export class SingleFlightCache<K, V> {
|
||||
invalidate(key: K): void {
|
||||
this.fresh.delete(key);
|
||||
this.inflight.delete(key);
|
||||
this.cancelExpiryIfEmpty();
|
||||
}
|
||||
|
||||
/** Detach all entries and pending loads without aborting existing callers. */
|
||||
clear(): void {
|
||||
this.fresh.clear();
|
||||
this.inflight.clear();
|
||||
this.cancelExpiryIfEmpty();
|
||||
}
|
||||
|
||||
/** Release this owner's cache permanently; pending callers still settle. */
|
||||
dispose(): void {
|
||||
this.disposed = true;
|
||||
this.clear();
|
||||
}
|
||||
|
||||
private cancelExpiryIfEmpty(): void {
|
||||
if (this.fresh.size === 0 && this.expiryTimer !== undefined) {
|
||||
clearTimeout(this.expiryTimer);
|
||||
this.expiryTimer = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleExpiry(): void {
|
||||
if (this.expiryTimer !== undefined || !Number.isFinite(this.ttlMs)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const oldest = this.fresh.values().next().value;
|
||||
|
||||
if (!oldest) {
|
||||
return;
|
||||
}
|
||||
|
||||
// One unref'ed timer per cache, not one closure/timer per cached roster.
|
||||
// Clamp long TTLs to Node's timer range rather than overflowing to 1ms.
|
||||
const delay = Math.max(1, Math.min(2 ** 31 - 1, oldest.at + this.ttlMs - this.now()));
|
||||
this.expiryTimer = setTimeout(() => {
|
||||
this.expiryTimer = undefined;
|
||||
const now = this.now();
|
||||
|
||||
for (const [key, entry] of this.fresh) {
|
||||
if (now - entry.at < this.ttlMs) {
|
||||
break;
|
||||
}
|
||||
|
||||
this.fresh.delete(key);
|
||||
}
|
||||
|
||||
this.scheduleExpiry();
|
||||
}, delay);
|
||||
this.expiryTimer.unref();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
60
packages/common/src/update-source.ts
Normal file
60
packages/common/src/update-source.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
export interface UpdateSourceConfig {
|
||||
mode: 'auto' | 'direct' | 'mirror';
|
||||
mirror: string;
|
||||
mirrors: string[];
|
||||
}
|
||||
|
||||
export function normalizeMirrorUrl(value: unknown): string {
|
||||
if (typeof value !== 'string' || value.length > 2048) {
|
||||
throw new Error('镜像地址必须是 HTTP(S) URL');
|
||||
}
|
||||
|
||||
let url: URL;
|
||||
|
||||
try {
|
||||
url = new URL(value.trim());
|
||||
} catch {
|
||||
throw new Error('镜像地址必须是 HTTP(S) URL');
|
||||
}
|
||||
|
||||
if (
|
||||
!['http:', 'https:'].includes(url.protocol) ||
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.search ||
|
||||
url.hash
|
||||
) {
|
||||
throw new Error('镜像地址仅支持 HTTP(S),不能包含账号、密码、查询参数或片段');
|
||||
}
|
||||
|
||||
return url.href.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
export function normalizeUpdateSourceConfig(value: unknown): UpdateSourceConfig {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error('更新来源必须是对象');
|
||||
}
|
||||
|
||||
if (
|
||||
!('mode' in value) ||
|
||||
(value.mode !== 'auto' && value.mode !== 'direct' && value.mode !== 'mirror')
|
||||
) {
|
||||
throw new Error('更新来源模式无效');
|
||||
}
|
||||
|
||||
if (!('mirrors' in value) || !Array.isArray(value.mirrors) || value.mirrors.length > 16) {
|
||||
throw new Error('自动筛选最多支持 16 个镜像');
|
||||
}
|
||||
|
||||
const mirror = 'mirror' in value && value.mirror !== '' ? normalizeMirrorUrl(value.mirror) : '';
|
||||
|
||||
if (value.mode === 'mirror' && !mirror) {
|
||||
throw new Error('请指定镜像地址');
|
||||
}
|
||||
|
||||
return {
|
||||
mode: value.mode,
|
||||
mirror,
|
||||
mirrors: [...new Set(value.mirrors.map(normalizeMirrorUrl))],
|
||||
};
|
||||
}
|
||||
100
packages/common/src/webui-target.ts
Normal file
100
packages/common/src/webui-target.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
/** Browser-safe contract shared by startup, the WebUI and embedding hosts.
|
||||
* Targets are deployment choices; they never belong in the saved UI preferences. */
|
||||
export const WEBUI_TARGETS = {
|
||||
maibot: {
|
||||
label: '麦麦 / 一键包',
|
||||
styles: ['millennium'],
|
||||
defaultStyle: 'millennium',
|
||||
},
|
||||
} as const;
|
||||
|
||||
export type WebuiTarget = keyof typeof WEBUI_TARGETS;
|
||||
export type WebuiColorMode = 'light' | 'dark' | 'system';
|
||||
|
||||
export type WebuiPresentation = {
|
||||
[T in WebuiTarget]: {
|
||||
version: 1;
|
||||
target: T;
|
||||
style: (typeof WEBUI_TARGETS)[T]['styles'][number];
|
||||
mode: WebuiColorMode;
|
||||
};
|
||||
}[WebuiTarget];
|
||||
|
||||
/** null releases the override for this document, without changing deployment opt-in. */
|
||||
export type WebuiPresentationUpdate = WebuiPresentation | { version: 1; target: null };
|
||||
export const WEBUI_PRESENTATION_EVENT = 'snowluma:host-appearance';
|
||||
export const WEBUI_TARGET_BOOTSTRAP_ID = 'snowluma-webui-target';
|
||||
|
||||
export function resolveWebuiTarget(raw: string | undefined): WebuiTarget | null {
|
||||
if (raw === undefined || raw.trim() === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const value = raw.trim();
|
||||
|
||||
if (!Object.hasOwn(WEBUI_TARGETS, value)) {
|
||||
throw new Error(
|
||||
`Invalid SNOWLUMA_WEBUI_TARGET: ${JSON.stringify(value)}. Expected ${Object.keys(WEBUI_TARGETS).join(', ')} or an empty value.`,
|
||||
);
|
||||
}
|
||||
|
||||
return value as WebuiTarget;
|
||||
}
|
||||
|
||||
export function defaultWebuiPresentation(target: WebuiTarget): WebuiPresentation {
|
||||
return { version: 1, target, style: WEBUI_TARGETS[target].defaultStyle, mode: 'system' };
|
||||
}
|
||||
|
||||
export function parseWebuiPresentation(value: unknown): WebuiPresentationUpdate {
|
||||
if (
|
||||
!value ||
|
||||
typeof value !== 'object' ||
|
||||
!('version' in value) ||
|
||||
value.version !== 1 ||
|
||||
!('target' in value)
|
||||
) {
|
||||
throw new TypeError('Invalid host appearance: expected a version 1 presentation');
|
||||
}
|
||||
|
||||
if (value.target === null) {
|
||||
return { version: 1, target: null };
|
||||
}
|
||||
|
||||
if (typeof value.target !== 'string' || !Object.hasOwn(WEBUI_TARGETS, value.target)) {
|
||||
throw new TypeError('Invalid host appearance target');
|
||||
}
|
||||
|
||||
const target = value.target as WebuiTarget;
|
||||
const styles: readonly string[] = WEBUI_TARGETS[target].styles;
|
||||
|
||||
if (!('style' in value) || typeof value.style !== 'string' || !styles.includes(value.style)) {
|
||||
throw new TypeError(`Invalid host appearance style for ${target}`);
|
||||
}
|
||||
|
||||
if (
|
||||
!('mode' in value) ||
|
||||
(value.mode !== 'light' && value.mode !== 'dark' && value.mode !== 'system')
|
||||
) {
|
||||
throw new TypeError('Invalid host appearance color mode');
|
||||
}
|
||||
|
||||
// Both discriminants have been checked against the same target registry.
|
||||
return { version: 1, target, style: value.style, mode: value.mode } as WebuiPresentation;
|
||||
}
|
||||
|
||||
/** Inject before the cached pre-paint theme script. Default HTML stays byte-for-byte intact. */
|
||||
export function injectWebuiTarget(html: string, target: WebuiTarget | null): string {
|
||||
if (target === null) {
|
||||
return html;
|
||||
}
|
||||
|
||||
if (!html.includes('<head>')) {
|
||||
throw new Error('WebUI HTML is missing <head>; cannot inject runtime target');
|
||||
}
|
||||
|
||||
const json = JSON.stringify(defaultWebuiPresentation(target)).replaceAll('<', '\\u003c');
|
||||
return html.replace(
|
||||
'<head>',
|
||||
`<head>\n <script id="${WEBUI_TARGET_BOOTSTRAP_ID}" type="application/json">${json}</script>`,
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { sanitizeLogLine } from '../src/log-sanitize';
|
||||
|
||||
describe('sanitizeLogLine', () => {
|
||||
@@ -23,4 +24,64 @@ describe('sanitizeLogLine', () => {
|
||||
it('does not leak unterminated terminal strings', () => {
|
||||
expect(sanitizeLogLine('visible\x1b]8;;https://example.com')).toBe('visible');
|
||||
});
|
||||
|
||||
it('preserves long Unicode records and adjacent visible spans', () => {
|
||||
const body = '消息 🌌 e\u0301\tpacket=0011aabb\n'.repeat(1000);
|
||||
expect(sanitizeLogLine(body)).toBe(body);
|
||||
expect(sanitizeLogLine(`\x1b[32m${body}\x1b[0m\x00tail\x1b`)).toBe(`${body}tail`);
|
||||
});
|
||||
|
||||
it.each(['\x1bP', '\x1bX', '\x1b^', '\x1b_', '\u0090', '\u0098', '\u009e', '\u009f'])(
|
||||
'removes %j control strings between visible spans',
|
||||
(opener) => {
|
||||
expect(sanitizeLogLine(`before${opener}private\u009cafter`)).toBe('beforeafter');
|
||||
expect(sanitizeLogLine(`before${opener}private\x1b\\after`)).toBe('beforeafter');
|
||||
expect(sanitizeLogLine(`before${opener}private`)).toBe('before');
|
||||
},
|
||||
);
|
||||
|
||||
it('handles consecutive controls and records consisting only of controls', () => {
|
||||
expect(sanitizeLogLine('\x00\x1b[31m\u009b0m\r\u007f')).toBe('');
|
||||
expect(sanitizeLogLine('a\x00\x1b[31m\u009b0m\r\u007fb')).toBe('ab');
|
||||
expect(sanitizeLogLine('')).toBe('');
|
||||
});
|
||||
|
||||
it('preserves every visible UTF-16 code unit when removing a large hidden payload', () => {
|
||||
const visible = 'visible 🌌 e\u0301\ud800x\udc00';
|
||||
expect(sanitizeLogLine(`${visible}\x1b]${'hidden'.repeat(1000)}`)).toBe(visible);
|
||||
});
|
||||
|
||||
it('does not retain discarded control-string payloads through a short visible span', () => {
|
||||
const moduleUrl = new URL('../src/log-sanitize.ts', import.meta.url).href;
|
||||
const output = execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
'--expose-gc',
|
||||
'--input-type=module',
|
||||
'-e',
|
||||
`
|
||||
import { setImmediate } from 'node:timers/promises';
|
||||
import { sanitizeLogLine } from ${JSON.stringify(moduleUrl)};
|
||||
async function used() {
|
||||
await setImmediate();
|
||||
global.gc();
|
||||
global.gc();
|
||||
return process.memoryUsage().heapUsed;
|
||||
}
|
||||
function record(i) {
|
||||
return sanitizeLogLine('visible record ' + i + '\\x1b]' + 'x'.repeat(1024 * 1024));
|
||||
}
|
||||
const before = await used();
|
||||
const records = Array.from({ length: 16 }, (_, i) => record(i));
|
||||
const retained = (await used()) - before;
|
||||
console.log(JSON.stringify({ retained, records }));
|
||||
`,
|
||||
],
|
||||
{ encoding: 'utf8', timeout: 10_000 },
|
||||
);
|
||||
const result = JSON.parse(output);
|
||||
expect(result.records).toEqual(Array.from({ length: 16 }, (_, i) => `visible record ${i}`));
|
||||
// Leave ample GC/runtime overhead while rejecting retention of the 16 MiB input.
|
||||
expect(result.retained).toBeLessThan(4 * 1024 * 1024);
|
||||
});
|
||||
});
|
||||
|
||||
99
packages/common/tests/logger-snapshot.test.ts
Normal file
99
packages/common/tests/logger-snapshot.test.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { fileWrite } = vi.hoisted(() => ({ fileWrite: vi.fn() }));
|
||||
|
||||
vi.mock('../src/log-file-transport', () => ({
|
||||
getFileTransport: () => ({ write: fileWrite, close: async () => {} }),
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
vi.resetModules();
|
||||
fileWrite.mockClear();
|
||||
});
|
||||
|
||||
async function setup() {
|
||||
vi.stubEnv('SNOWLUMA_LOG_LEVEL', 'trace');
|
||||
vi.stubEnv('SNOWLUMA_LOG_FILE_LEVEL', 'error');
|
||||
vi.stubEnv('SNOWLUMA_TRACE_BUFFER', '100');
|
||||
vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
vi.spyOn(process.stderr, 'write').mockReturnValue(true);
|
||||
const logger = await import('../src/logger');
|
||||
return { ...logger, log: logger.createLogger('Snapshot') };
|
||||
}
|
||||
|
||||
describe('retained log snapshots', () => {
|
||||
it('returns empty snapshots before any record has been emitted', async () => {
|
||||
const logger = await setup();
|
||||
expect(logger.getRecentLogs()).toEqual([]);
|
||||
expect(logger.getLogSnapshot()).toEqual([]);
|
||||
});
|
||||
|
||||
it('merges wrapped rings in emission order and returns only the requested tail', async () => {
|
||||
const logger = await setup();
|
||||
const emitted: import('../src/logger').LogEntry[] = [];
|
||||
const unsubscribe = logger.subscribeLogs((entry) => emitted.push(entry));
|
||||
|
||||
for (let i = 0; i < 1100; i += 1) {
|
||||
logger.log.info('normal %d', i);
|
||||
logger.log.trace('trace %d', i);
|
||||
}
|
||||
|
||||
unsubscribe();
|
||||
const normal = emitted.filter((entry) => entry.level !== 'trace').slice(-1000);
|
||||
const trace = emitted.filter((entry) => entry.level === 'trace').slice(-100);
|
||||
const expected = [...normal, ...trace].sort((a, b) => a.id - b.id);
|
||||
expect(logger.getLogSnapshot()).toEqual(expected);
|
||||
|
||||
for (const limit of [1, 2, 30, 300, 1000, 1100, 2000, 0, -1, 2.9, NaN, Infinity]) {
|
||||
expect(logger.getRecentLogs(limit)).toEqual(
|
||||
expected.slice(-Math.max(1, Math.trunc(limit))),
|
||||
);
|
||||
}
|
||||
|
||||
expect(logger.getRecentLogs()).toEqual(expected.slice(-300));
|
||||
const snapshot = logger.getRecentLogs(5);
|
||||
snapshot.pop();
|
||||
expect(logger.getRecentLogs(5)).toEqual(expected.slice(-5));
|
||||
});
|
||||
|
||||
it.each(['info', 'trace'] as const)(
|
||||
'reads a tail when only the %s ring has records',
|
||||
async (level) => {
|
||||
const logger = await setup();
|
||||
logger.log[level]('first');
|
||||
logger.log[level]('second');
|
||||
expect(logger.getRecentLogs(1).map((entry) => entry.message)).toEqual(['second']);
|
||||
expect(logger.getLogSnapshot().map((entry) => entry.message)).toEqual([
|
||||
'first',
|
||||
'second',
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it('preserves ID gaps and file routing without publishing file-only entries', async () => {
|
||||
const logger = await setup();
|
||||
vi.stubEnv('SNOWLUMA_LOG_FILE_LEVEL', 'debug');
|
||||
vi.resetModules();
|
||||
const fresh = await import('../src/logger');
|
||||
fresh.setLogLevel('info');
|
||||
const entries: import('../src/logger').LogEntry[] = [];
|
||||
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
|
||||
const log = fresh.createLogger('FileOnly').child({ uin: 10001 });
|
||||
log.info('before');
|
||||
fresh.runWithRequestId(42, () => log.debug('password=secret file-only\x07'));
|
||||
log.info('after');
|
||||
unsubscribe();
|
||||
|
||||
expect(entries.map((entry) => entry.message)).toEqual(['before', 'after']);
|
||||
expect(entries[1]!.id).toBe(entries[0]!.id + 2);
|
||||
expect(fresh.getLogSnapshot()).toEqual(entries);
|
||||
expect(fileWrite).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/\[req#42\] password=\*\*\* file-only/),
|
||||
10001,
|
||||
);
|
||||
expect(process.stdout.write).toHaveBeenCalledTimes(2);
|
||||
expect(logger.getLogSnapshot()).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { afterEach, describe, it, expect, vi } from 'vitest';
|
||||
import { createSingleFlightCache } from '../src/single-flight-cache';
|
||||
|
||||
/** A promise whose resolve/reject is exposed, for driving single-flight races. */
|
||||
@@ -13,6 +13,129 @@ function deferred<T>() {
|
||||
}
|
||||
|
||||
describe('SingleFlightCache', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('disposes retained values and rejects new reads without restarting loads or timers', async () => {
|
||||
vi.useFakeTimers();
|
||||
const load = vi.fn(async (key: string) => ({ key }));
|
||||
const cache = createSingleFlightCache({ ttlMs: 300_000, load });
|
||||
await cache.get('first');
|
||||
await cache.get('second');
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
|
||||
cache.dispose();
|
||||
cache.dispose();
|
||||
cache.clear();
|
||||
|
||||
expect(cache.size).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
await expect(cache.get('first')).rejects.toThrow('disposed');
|
||||
await expect(cache.get('new', { force: true })).rejects.toThrow('disposed');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each(['resolve', 'reject'] as const)(
|
||||
'preserves a pending %s after disposal without retaining the result',
|
||||
async (outcome) => {
|
||||
vi.useFakeTimers();
|
||||
const pending = deferred<string>();
|
||||
const cache = createSingleFlightCache({ ttlMs: 300_000, load: () => pending.promise });
|
||||
const first = cache.get('key');
|
||||
expect(cache.get('key')).toBe(first);
|
||||
cache.dispose();
|
||||
|
||||
if (outcome === 'resolve') {
|
||||
pending.resolve('late value');
|
||||
await expect(first).resolves.toBe('late value');
|
||||
} else {
|
||||
pending.reject(new Error('late failure'));
|
||||
await expect(first).rejects.toThrow('late failure');
|
||||
}
|
||||
|
||||
expect(cache.size).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it('releases expired values while idle without expiring newer values early', async () => {
|
||||
vi.useFakeTimers();
|
||||
const load = vi.fn(async (key: string) => ({ key }));
|
||||
const cache = createSingleFlightCache({ ttlMs: 1000, load });
|
||||
await cache.get('old');
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
const newer = await cache.get('new');
|
||||
|
||||
expect(cache.size).toBe(2);
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(cache.size).toBe(1);
|
||||
expect(await cache.get('new')).toBe(newer);
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(cache.size).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('keeps a refreshed entry until its new deadline and expires other keys', async () => {
|
||||
vi.useFakeTimers();
|
||||
const cache = createSingleFlightCache({ ttlMs: 1000, load: async (key: string) => key });
|
||||
await cache.get('refreshed');
|
||||
await cache.get('old');
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
await cache.get('refreshed', { force: true });
|
||||
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(cache.size).toBe(1);
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(cache.size).toBe(0);
|
||||
});
|
||||
|
||||
it.each(['invalidate', 'clear'] as const)(
|
||||
'%s cancels idle cleanup when the last value is removed',
|
||||
async (operation) => {
|
||||
vi.useFakeTimers();
|
||||
const cache = createSingleFlightCache({ ttlMs: 1000, load: async () => 'value' });
|
||||
await cache.get('key');
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
cache[operation]('key');
|
||||
expect(cache.size).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
|
||||
await cache.get('key');
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(cache.size).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it('does not let expiration detach a pending refresh', async () => {
|
||||
vi.useFakeTimers();
|
||||
const pending = deferred<string>();
|
||||
const load = vi.fn().mockResolvedValueOnce('old').mockReturnValue(pending.promise);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
|
||||
await cache.get('key');
|
||||
const refresh = cache.get('key', { force: true });
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
|
||||
expect(cache.size).toBe(0);
|
||||
expect(cache.get('key')).toBe(refresh);
|
||||
pending.resolve('new');
|
||||
await expect(refresh).resolves.toBe('new');
|
||||
expect(cache.size).toBe(1);
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(cache.size).toBe(0);
|
||||
});
|
||||
|
||||
it('does not retain values when caching is disabled by a zero TTL', async () => {
|
||||
vi.useFakeTimers();
|
||||
const cache = createSingleFlightCache({ ttlMs: 0, load: async () => 'value' });
|
||||
await expect(cache.get('key')).resolves.toBe('value');
|
||||
expect(cache.size).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it.each(['invalidate', 'clear'] as const)(
|
||||
'%s detaches pending loads from the cache',
|
||||
async (operation) => {
|
||||
|
||||
54
packages/common/tests/update-source.test.ts
Normal file
54
packages/common/tests/update-source.test.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { normalizeMirrorUrl, normalizeUpdateSourceConfig } from '../src/update-source';
|
||||
import { normalizeRuntimeConfig } from '../src/runtime';
|
||||
|
||||
describe('update source configuration', () => {
|
||||
it('normalizes proxy prefixes, deduplicates mirrors and retains order', () => {
|
||||
expect(
|
||||
normalizeUpdateSourceConfig({
|
||||
mode: 'auto',
|
||||
mirror: '',
|
||||
mirrors: [
|
||||
' https://EXAMPLE.com/proxy/ ',
|
||||
'https://example.com/proxy',
|
||||
'https://other.example',
|
||||
],
|
||||
}),
|
||||
).toEqual({
|
||||
mode: 'auto',
|
||||
mirror: '',
|
||||
mirrors: ['https://example.com/proxy', 'https://other.example'],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
'',
|
||||
'file:///tmp/x',
|
||||
'ftp://example.com',
|
||||
'https://user:secret@example.com',
|
||||
'https://example.com/?token=a',
|
||||
'https://example.com/#a',
|
||||
null,
|
||||
])('rejects invalid mirror %s', (url) => {
|
||||
expect(() => normalizeMirrorUrl(url)).toThrow();
|
||||
});
|
||||
|
||||
it.each([
|
||||
null,
|
||||
[],
|
||||
{ mode: ['auto'], mirrors: [] },
|
||||
{ mode: 'mirror', mirror: '', mirrors: [] },
|
||||
{ mode: 'auto', mirrors: Array(17).fill('https://example.com') },
|
||||
])('rejects invalid configuration %j', (config) => {
|
||||
expect(() => normalizeUpdateSourceConfig(config)).toThrow();
|
||||
});
|
||||
|
||||
it('retains configured update sources when normalizing runtime settings', () => {
|
||||
const updateSource = { mode: 'direct', mirror: '', mirrors: [] };
|
||||
expect(normalizeRuntimeConfig({ updateSource, webuiPort: 7777 })).toMatchObject({
|
||||
updateSource,
|
||||
webuiPort: 7777,
|
||||
});
|
||||
expect(normalizeRuntimeConfig({})).not.toHaveProperty('updateSource');
|
||||
});
|
||||
});
|
||||
51
packages/common/tests/webui-target.test.ts
Normal file
51
packages/common/tests/webui-target.test.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
defaultWebuiPresentation,
|
||||
injectWebuiTarget,
|
||||
parseWebuiPresentation,
|
||||
resolveWebuiTarget,
|
||||
} from '../src/webui-target';
|
||||
|
||||
describe('deployment presentation contract', () => {
|
||||
it('requires explicit opt-in and rejects misspelled deployments', () => {
|
||||
expect(resolveWebuiTarget(undefined)).toBeNull();
|
||||
expect(resolveWebuiTarget(' ')).toBeNull();
|
||||
expect(resolveWebuiTarget('maibot')).toBe('maibot');
|
||||
expect(() => resolveWebuiTarget('mai-bot')).toThrow('SNOWLUMA_WEBUI_TARGET');
|
||||
expect(() => resolveWebuiTarget('__proto__')).toThrow('SNOWLUMA_WEBUI_TARGET');
|
||||
});
|
||||
|
||||
it('keeps the unconfigured document intact and injects before cached appearance', () => {
|
||||
const html = '<html><head><script>readSavedAppearance()</script></head></html>';
|
||||
expect(injectWebuiTarget(html, null)).toBe(html);
|
||||
const injected = injectWebuiTarget(html, 'maibot');
|
||||
expect(injected.indexOf('snowluma-webui-target')).toBeLessThan(
|
||||
injected.indexOf('readSavedAppearance'),
|
||||
);
|
||||
expect(injected).toContain(JSON.stringify(defaultWebuiPresentation('maibot')));
|
||||
expect(() => injectWebuiTarget('broken html', 'maibot')).toThrow('missing <head>');
|
||||
});
|
||||
|
||||
it('validates the version, target, style and color mode without accepting arbitrary CSS', () => {
|
||||
const valid = defaultWebuiPresentation('maibot');
|
||||
expect(parseWebuiPresentation(valid)).toEqual(valid);
|
||||
expect(
|
||||
parseWebuiPresentation({ ...valid, mode: 'dark', css: 'body{display:none}' }),
|
||||
).toEqual({ ...valid, mode: 'dark' });
|
||||
expect(parseWebuiPresentation({ version: 1, target: null })).toEqual({
|
||||
version: 1,
|
||||
target: null,
|
||||
});
|
||||
|
||||
for (const input of [
|
||||
null,
|
||||
{},
|
||||
{ ...valid, version: 2 },
|
||||
{ ...valid, target: 'other' },
|
||||
{ ...valid, style: 'modern' },
|
||||
{ ...valid, mode: 'blue' },
|
||||
]) {
|
||||
expect(() => parseWebuiPresentation(input)).toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/core",
|
||||
"version": "2.0.0",
|
||||
"version": "2.4.2",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -53,19 +53,18 @@
|
||||
"tar": "^7.5.22"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@hono/node-server": "^1.19.15",
|
||||
"@rollup/plugin-node-resolve": "^16.0.3",
|
||||
"@hono/node-server": "^2.1.4",
|
||||
"@types/node": "catalog:",
|
||||
"cross-env": "^10.1.0",
|
||||
"hono": "^4.12.34",
|
||||
"hono": "^4.13.11",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vite-plugin-cp": "^6.0.3",
|
||||
"vitest": "^4.1.4",
|
||||
"vitest": "4.1.12",
|
||||
"@snowluma/sqlite": "workspace:*"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
"node": "^24.22.1 || >=26.12.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { GroupInviteTracker } from '@snowluma/protocol/group-invite-tracker';
|
||||
import { groupRequestSubType } from '@snowluma/protocol/qq-info';
|
||||
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
|
||||
import {
|
||||
FetchFriendListPage,
|
||||
@@ -10,7 +12,8 @@ import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/conta
|
||||
import {
|
||||
FetchGroupRequests,
|
||||
FetchGroupRequestsByUid,
|
||||
groupRequestOperationType,
|
||||
groupRequestNotifyType,
|
||||
type DecodedGroupRequest,
|
||||
} from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
|
||||
import {
|
||||
FetchRobotUinRanges,
|
||||
@@ -42,6 +45,7 @@ import type {
|
||||
FriendInfo,
|
||||
GroupMemberInfo,
|
||||
GroupRequestInfo,
|
||||
PublicProfileFields,
|
||||
QQGroupInfo,
|
||||
UserProfileInfo,
|
||||
} from '@snowluma/protocol/qq-info';
|
||||
@@ -76,22 +80,53 @@ export function isRobotUin(uin: number, ranges: readonly RobotUinRange[]): boole
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeGroupRequestSequence(
|
||||
rawSequence: bigint | number | undefined,
|
||||
function groupRequestMetadata(
|
||||
raw: Pick<
|
||||
DecodedGroupRequest,
|
||||
'sequence' | 'state' | 'eventType' | 'comment' | 'operateTransInfo'
|
||||
>,
|
||||
groupId: number,
|
||||
): number {
|
||||
const sequence = Number(rawSequence ?? 0);
|
||||
filtered: boolean,
|
||||
) {
|
||||
const sequence = Number(raw.sequence ?? 0);
|
||||
|
||||
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
|
||||
throw new Error(
|
||||
`invalid group-request sequence: group=${groupId} sequence=${String(rawSequence ?? 0)}`,
|
||||
`invalid group-request sequence: group=${groupId} sequence=${String(raw.sequence ?? 0)}`,
|
||||
);
|
||||
}
|
||||
|
||||
return sequence;
|
||||
const eventType = raw.eventType ?? 0;
|
||||
const notifyType = groupRequestNotifyType(eventType);
|
||||
|
||||
if (notifyType === undefined) {
|
||||
log.warn(
|
||||
'unsupported group-request wire type: group=%d sequence=%d type=%d',
|
||||
groupId,
|
||||
sequence,
|
||||
eventType,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
sequence,
|
||||
state: raw.state ?? 0,
|
||||
eventType,
|
||||
notifyType,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
operateTransInfo: raw.operateTransInfo?.length ? raw.operateTransInfo : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const MEMBER_LIST_TTL_MS = 60_000;
|
||||
const FRIEND_PROFILE_TTL_MS = 5 * 60_000;
|
||||
const FRIEND_PROFILE_CONCURRENCY = 4;
|
||||
|
||||
export interface FriendListOptions {
|
||||
/** Explicitly query profiles; ordinary roster refreshes never fan out. */
|
||||
withProfile?: boolean;
|
||||
}
|
||||
|
||||
export class ContactsApi {
|
||||
/**
|
||||
@@ -109,12 +144,25 @@ export class ContactsApi {
|
||||
load: (groupId) => this.fetchGroupMemberListUncached(groupId),
|
||||
});
|
||||
private robotUinRangesPromise_: Promise<RobotUinRangeSnapshot> | null = null;
|
||||
/** groupUin → approval msgseq from a private qun.invite card. Written
|
||||
* only by IncomingPacketPipeline (and tests). OneBot reads get/find. */
|
||||
private readonly groupInviteCardSeqs_ = new Map<number, number>();
|
||||
readonly groupInvites = new GroupInviteTracker();
|
||||
private friendRosterGeneration = 0;
|
||||
private rememberedFriendRosterGeneration = 0;
|
||||
private activeProfiles = 0;
|
||||
private readonly profileWaiters: (() => void)[] = [];
|
||||
private readonly friendProfiles: SingleFlightCache<number, PublicProfileFields> =
|
||||
createSingleFlightCache({
|
||||
ttlMs: FRIEND_PROFILE_TTL_MS,
|
||||
load: (uin) => this.loadFriendProfile(uin),
|
||||
});
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
dispose(): void {
|
||||
// Late roster responses must not start new profile loads after shutdown.
|
||||
this.memberListCache.dispose();
|
||||
this.friendProfiles.dispose();
|
||||
}
|
||||
|
||||
private fetchRobotUinRanges(groupId: number): Promise<RobotUinRangeSnapshot> {
|
||||
if (this.robotUinRangesPromise_) {
|
||||
return this.robotUinRangesPromise_;
|
||||
@@ -177,7 +225,73 @@ export class ContactsApi {
|
||||
return SendTuwenArk.invoke(this.ctx, params);
|
||||
}
|
||||
|
||||
private async fetchFriendRoster(): Promise<FriendRoster> {
|
||||
private async loadFriendProfile(uin: number): Promise<PublicProfileFields> {
|
||||
if (this.activeProfiles >= FRIEND_PROFILE_CONCURRENCY) {
|
||||
await new Promise<void>((resolve) => this.profileWaiters.push(resolve));
|
||||
} else {
|
||||
this.activeProfiles++;
|
||||
}
|
||||
|
||||
try {
|
||||
const profile = await this.fetchUserProfile(uin);
|
||||
|
||||
return profile.profile ?? {};
|
||||
} catch (cause) {
|
||||
log.warn(
|
||||
'friend profile query failed: user=%d error=%s',
|
||||
uin,
|
||||
cause instanceof Error ? cause.message : String(cause),
|
||||
);
|
||||
throw new Error(`friend profile query failed for ${uin}`, { cause });
|
||||
} finally {
|
||||
const next = this.profileWaiters.shift();
|
||||
|
||||
if (next) {
|
||||
next();
|
||||
} else {
|
||||
this.activeProfiles--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async enrichFriendProfiles(entries: FriendListPageEntry[]): Promise<void> {
|
||||
const started = Date.now();
|
||||
|
||||
for (let offset = 0; offset < entries.length; offset += FRIEND_PROFILE_CONCURRENCY) {
|
||||
const batch = entries.slice(offset, offset + FRIEND_PROFILE_CONCURRENCY);
|
||||
const results = await Promise.allSettled(
|
||||
batch.map(async ({ friend }) => {
|
||||
const extra = await this.friendProfiles.get(friend.uin);
|
||||
friend.profile = { ...structuredClone(extra), ...friend.profile };
|
||||
}),
|
||||
);
|
||||
const errors = results.filter(
|
||||
(result): result is PromiseRejectedResult => result.status === 'rejected',
|
||||
);
|
||||
|
||||
if (errors.length > 0) {
|
||||
log.warn(
|
||||
'friend profile enrichment failed: batch=%d failures=%d elapsedMs=%d',
|
||||
offset,
|
||||
errors.length,
|
||||
Date.now() - started,
|
||||
);
|
||||
throw new AggregateError(
|
||||
errors.map((result) => result.reason),
|
||||
'friend profile enrichment failed',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
log.debug(
|
||||
'friend profiles loaded: friends=%d elapsedMs=%d',
|
||||
entries.length,
|
||||
Date.now() - started,
|
||||
);
|
||||
}
|
||||
|
||||
private async fetchFriendRoster(options: FriendListOptions = {}): Promise<FriendRoster> {
|
||||
const generation = ++this.friendRosterGeneration;
|
||||
const entries: FriendListPageEntry[] = [];
|
||||
const categories = new Map<number, FriendListPageCategory>();
|
||||
const seenCookies = new Set<string>();
|
||||
@@ -207,18 +321,25 @@ export class ContactsApi {
|
||||
cookie = next;
|
||||
}
|
||||
|
||||
const friends = entries.map((entry) => entry.friend);
|
||||
this.ctx.identity.rememberFriends(friends);
|
||||
if (options.withProfile) {
|
||||
await this.enrichFriendProfiles(entries);
|
||||
}
|
||||
|
||||
if (generation > this.rememberedFriendRosterGeneration) {
|
||||
this.ctx.identity.rememberFriends(entries.map((entry) => entry.friend));
|
||||
this.rememberedFriendRosterGeneration = generation;
|
||||
}
|
||||
|
||||
return { entries, categories: [...categories.values()] };
|
||||
}
|
||||
|
||||
async fetchFriendList(): Promise<FriendInfo[]> {
|
||||
const roster = await this.fetchFriendRoster();
|
||||
async fetchFriendList(options: FriendListOptions = {}): Promise<FriendInfo[]> {
|
||||
const roster = await this.fetchFriendRoster(options);
|
||||
return roster.entries.map((entry) => entry.friend);
|
||||
}
|
||||
|
||||
async fetchFriendCategories(): Promise<FriendCategoryInfo[]> {
|
||||
const roster = await this.fetchFriendRoster();
|
||||
async fetchFriendCategories(options: FriendListOptions = {}): Promise<FriendCategoryInfo[]> {
|
||||
const roster = await this.fetchFriendRoster(options);
|
||||
const buckets = new Map(
|
||||
roster.categories.map((category) => [category.categoryId, [] as FriendInfo[]]),
|
||||
);
|
||||
@@ -402,8 +523,7 @@ export class ContactsApi {
|
||||
member.isRobot = isRobotUin(member.uin, robotSnapshot.ranges);
|
||||
}
|
||||
|
||||
this.ctx.identity.rememberGroupMembers(groupId, members);
|
||||
return members;
|
||||
return this.ctx.identity.rememberGroupMembers(groupId, members);
|
||||
}
|
||||
|
||||
async fetchUserProfile(uin: number): Promise<UserProfileInfo> {
|
||||
@@ -460,18 +580,6 @@ export class ContactsApi {
|
||||
this.ctx.identity.findUidByUin(operatorUin, groupId) ||
|
||||
this.ctx.identity.findUidByUin(operatorUin) ||
|
||||
'';
|
||||
const notifyType = raw.eventType ?? 0;
|
||||
const operationType = groupRequestOperationType(notifyType);
|
||||
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
|
||||
|
||||
if (operationType === null) {
|
||||
log.warn(
|
||||
'unsupported group-request notification type: group=%d sequence=%s type=%d',
|
||||
groupId,
|
||||
String(raw.sequence ?? 0n),
|
||||
notifyType,
|
||||
);
|
||||
}
|
||||
|
||||
requests.push({
|
||||
groupId,
|
||||
@@ -497,16 +605,7 @@ export class ContactsApi {
|
||||
this.ctx.identity.findUinByUid(operatorUid) ||
|
||||
0,
|
||||
operatorName: raw.operatorUser?.name ?? '',
|
||||
sequence,
|
||||
state: raw.state ?? 0,
|
||||
notifyType,
|
||||
eventType: operationType ?? 0,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
operateTransInfo:
|
||||
raw.operateTransInfo && raw.operateTransInfo.length > 0
|
||||
? raw.operateTransInfo
|
||||
: undefined,
|
||||
...groupRequestMetadata(raw, groupId, filtered),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -530,18 +629,6 @@ export class ContactsApi {
|
||||
const targetUid = raw.target?.uid ?? '';
|
||||
const invitorUid = raw.invitor?.uid ?? '';
|
||||
const operatorUid = raw.operatorUser?.uid ?? '';
|
||||
const notifyType = raw.eventType ?? 0;
|
||||
const operationType = groupRequestOperationType(notifyType);
|
||||
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
|
||||
|
||||
if (operationType === null) {
|
||||
log.warn(
|
||||
'unsupported group-request notification type: group=%d sequence=%s type=%d',
|
||||
groupId,
|
||||
String(raw.sequence ?? 0n),
|
||||
notifyType,
|
||||
);
|
||||
}
|
||||
|
||||
requests.push({
|
||||
groupId,
|
||||
@@ -564,16 +651,7 @@ export class ContactsApi {
|
||||
this.ctx.identity.findUinByUid(operatorUid) ??
|
||||
0,
|
||||
operatorName: raw.operatorUser?.name ?? '',
|
||||
sequence,
|
||||
state: raw.state ?? 0,
|
||||
notifyType,
|
||||
eventType: operationType ?? 0,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
operateTransInfo:
|
||||
raw.operateTransInfo && raw.operateTransInfo.length > 0
|
||||
? raw.operateTransInfo
|
||||
: undefined,
|
||||
...groupRequestMetadata(raw, groupId, filtered),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -581,30 +659,53 @@ export class ContactsApi {
|
||||
return requests;
|
||||
}
|
||||
|
||||
/** Live observation write. IncomingPacketPipeline and tests only. */
|
||||
rememberGroupInviteCardSequence(groupUin: number, sequence: number): void {
|
||||
if (groupUin > 0 && sequence > 0) {
|
||||
this.groupInviteCardSeqs_.set(groupUin, sequence);
|
||||
async resolveGroupJoinRequest(
|
||||
groupId: number,
|
||||
uid: string,
|
||||
subType: 'add' | 'invite',
|
||||
invitedUid?: string,
|
||||
): Promise<GroupRequestInfo | null> {
|
||||
const [main, filtered] = await Promise.allSettled([
|
||||
this.fetchGroupRequestsByUid(false),
|
||||
this.fetchGroupRequestsByUid(true),
|
||||
]);
|
||||
|
||||
if (main.status === 'rejected') {
|
||||
throw main.reason;
|
||||
}
|
||||
|
||||
if (filtered.status === 'rejected') {
|
||||
throw filtered.reason;
|
||||
}
|
||||
|
||||
return (
|
||||
[...main.value, ...filtered.value].find((request) => {
|
||||
if (
|
||||
request.groupId !== groupId ||
|
||||
request.state !== 1 ||
|
||||
groupRequestSubType(request) !== subType
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return subType === 'add'
|
||||
? request.targetUid === uid
|
||||
: request.invitorUid === uid && request.targetUid === invitedUid;
|
||||
}) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
/** Returns whether this live card introduces a new approval sequence. */
|
||||
rememberGroupInviteCardSequence(groupId: number, sequence: number): boolean {
|
||||
return this.groupInvites.receiveCard(groupId, sequence);
|
||||
}
|
||||
|
||||
/** The approval msgseq captured from a private "qun.invite" card for this
|
||||
* group, or undefined if none was seen. `set_group_add_request` uses it to
|
||||
* approve a bot self-invite via 0x10c8 (eventType=2). See issue #125. */
|
||||
getGroupInviteCardSequence(groupId: number): number | undefined {
|
||||
return this.groupInviteCardSeqs_.get(groupId);
|
||||
return this.groupInvites.getCardSequence(groupId);
|
||||
}
|
||||
|
||||
/** Resolve the group for a private invite-card msgseq. Numeric OneBot flags
|
||||
* use this path because the card sequence is absent from 0x10C0. */
|
||||
findGroupInviteCardGroupBySequence(sequence: number): number | undefined {
|
||||
for (const [groupUin, rememberedSequence] of this.groupInviteCardSeqs_) {
|
||||
if (rememberedSequence === sequence) {
|
||||
return groupUin;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
findGroupInviteCardGroupBySequence(sequence: number, groupId?: number): number | undefined {
|
||||
return this.groupInvites.findCardGroup(sequence, groupId);
|
||||
}
|
||||
|
||||
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
|
||||
|
||||
@@ -35,6 +35,9 @@ export interface PttTransInput {
|
||||
duration: number;
|
||||
size: number;
|
||||
format: number;
|
||||
/** Omitted by older callers for legacy voice media. */
|
||||
isNtv2?: boolean;
|
||||
storeRegion?: number;
|
||||
/** Group ptt numeric file id (group only; optional). */
|
||||
fileId?: number;
|
||||
}
|
||||
@@ -390,6 +393,8 @@ export class ExtrasApi {
|
||||
md5,
|
||||
},
|
||||
};
|
||||
req.isNtv2 = input.isNtv2 ? 1 : 0;
|
||||
req.storeRegion = input.isNtv2 ? (input.storeRegion ?? 0) : 0;
|
||||
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
|
||||
|
||||
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
|
||||
@@ -406,9 +411,11 @@ export class ExtrasApi {
|
||||
// sourced from cache, to tell a server-side ASR failure apart from our own
|
||||
// missing/zero field (md5/format/uuid). Behaviour unchanged — still throws.
|
||||
log.warn(
|
||||
'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d',
|
||||
'ptt translate errCode=%d isGroup=%s ntv2=%d region=%d md5=%s format=%d uuid=%s dur=%d size=%d',
|
||||
item.errCode,
|
||||
input.isGroup,
|
||||
req.isNtv2,
|
||||
req.storeRegion,
|
||||
input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY',
|
||||
input.format,
|
||||
input.uuid ? 'set' : 'EMPTY',
|
||||
|
||||
69
packages/core/src/bridge/apis/forward-cache.ts
Normal file
69
packages/core/src/bridge/apis/forward-cache.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { ForwardNodePayload } from '@snowluma/protocol/events';
|
||||
|
||||
const MAX_CACHED_FORWARDS = 512;
|
||||
const log = createLogger('Bridge.Forward');
|
||||
type ForwardLayers = Map<string, ForwardNodePayload[]>;
|
||||
|
||||
interface ForwardCacheHit {
|
||||
rootId: string;
|
||||
resId: string;
|
||||
layers: ForwardLayers;
|
||||
nodes: ForwardNodePayload[];
|
||||
}
|
||||
|
||||
/** Nested results share the lifetime and recency of the result that supplied them. */
|
||||
export class ForwardResultCache {
|
||||
private readonly entries = new Map<string, ForwardLayers>();
|
||||
|
||||
get(resId: string): ForwardCacheHit | undefined {
|
||||
let hit: ForwardCacheHit | undefined;
|
||||
|
||||
// A nested result can be supplied by several retained outer results.
|
||||
for (const [rootId, layers] of this.entries) {
|
||||
const nodes = layers.get(resId);
|
||||
|
||||
if (nodes) {
|
||||
hit = { rootId, resId, layers, nodes };
|
||||
}
|
||||
}
|
||||
|
||||
if (hit) {
|
||||
this.entries.delete(hit.rootId);
|
||||
this.entries.set(hit.rootId, hit.layers);
|
||||
}
|
||||
|
||||
return hit;
|
||||
}
|
||||
|
||||
set(rootId: string, layers: ReadonlyMap<string, ForwardNodePayload[]>): void {
|
||||
if (!layers.has(rootId)) {
|
||||
throw new Error('forward cache entry is missing its outer result');
|
||||
}
|
||||
|
||||
this.entries.delete(rootId);
|
||||
this.entries.set(rootId, new Map(layers));
|
||||
|
||||
while (this.entries.size > MAX_CACHED_FORWARDS) {
|
||||
const oldest = this.entries.entries().next().value!;
|
||||
this.entries.delete(oldest[0]);
|
||||
log.trace(
|
||||
'forward cache evicted: res_id=%s layers=%d remaining=%d',
|
||||
oldest[0],
|
||||
oldest[1].size,
|
||||
this.entries.size,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
update(hit: ForwardCacheHit, nodes: ForwardNodePayload[]): void {
|
||||
// Enrichment may finish after eviction or replacement. It must not revive
|
||||
// an old result or turn a nested result into an independent cache entry.
|
||||
if (
|
||||
this.entries.get(hit.rootId) === hit.layers &&
|
||||
hit.layers.get(hit.resId) === hit.nodes
|
||||
) {
|
||||
hit.layers.set(hit.resId, nodes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,16 +25,15 @@ import { randomUUID } from 'crypto';
|
||||
import { gunzipSync, gzipSync } from 'zlib';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext, UploadedFileMeta } from '../bridge-context';
|
||||
import { ForwardResultCache } from './forward-cache';
|
||||
import { resolveSelfUid, toInt } from './shared';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge {
|
||||
return ctx as unknown as Bridge;
|
||||
}
|
||||
|
||||
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
|
||||
// of the process — that's enough because OneBot clients typically
|
||||
// resolve a forward immediately after receiving the parent message.
|
||||
const forwardResCache = new Map<string, ForwardNodePayload[]>();
|
||||
// Share within a bridge without retaining disconnected accounts.
|
||||
const forwardCaches = new WeakMap<BridgeContext, ForwardResultCache>();
|
||||
|
||||
const log = createLogger('Bridge.Forward');
|
||||
|
||||
@@ -77,6 +76,7 @@ interface ForwardUploadResult {
|
||||
// callers concatenate these to their own actions list so the
|
||||
// outermost upload carries the full tree.
|
||||
innerActions: ForwardInnerAction[];
|
||||
cachedLayers: Map<string, ForwardNodePayload[]>;
|
||||
}
|
||||
|
||||
// Local hex-decode helper — avoids importing the heavyweight `pipeline`
|
||||
@@ -353,7 +353,18 @@ function assertNoWindowShakeInForward(nodes: ForwardNodePayload[]): void {
|
||||
}
|
||||
|
||||
export class ForwardApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
private readonly cache: ForwardResultCache;
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) {
|
||||
let cache = forwardCaches.get(ctx);
|
||||
|
||||
if (!cache) {
|
||||
cache = new ForwardResultCache();
|
||||
forwardCaches.set(ctx, cache);
|
||||
}
|
||||
|
||||
this.cache = cache;
|
||||
}
|
||||
|
||||
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
|
||||
// Reject the complete recursive tree before identity resolution, media
|
||||
@@ -367,7 +378,8 @@ export class ForwardApi {
|
||||
assertPrivateForwardFileCapacity(nodes);
|
||||
}
|
||||
|
||||
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
|
||||
const { resId, cachedLayers } = await this.uploadRecursive(nodes, groupId, userId);
|
||||
this.cache.set(resId, cachedLayers);
|
||||
return resId;
|
||||
}
|
||||
|
||||
@@ -394,6 +406,7 @@ export class ForwardApi {
|
||||
name: string,
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
allowTemporary = true,
|
||||
): Promise<MessageElementOf<'file'>> {
|
||||
if (groupId !== undefined) {
|
||||
const uploaded = await this.ctx.apis.groupFile.upload(
|
||||
@@ -403,6 +416,7 @@ export class ForwardApi {
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary },
|
||||
);
|
||||
|
||||
if (!uploaded.fileId) {
|
||||
@@ -470,6 +484,7 @@ export class ForwardApi {
|
||||
element: MessageElement,
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
allowTemporary = true,
|
||||
): Promise<MessageElement> {
|
||||
if (element.type !== 'file') {
|
||||
return element;
|
||||
@@ -483,6 +498,7 @@ export class ForwardApi {
|
||||
fileNameForUpload(element),
|
||||
groupId,
|
||||
userId,
|
||||
allowTemporary,
|
||||
);
|
||||
return {
|
||||
...stripFileSource(element),
|
||||
@@ -494,6 +510,14 @@ export class ForwardApi {
|
||||
const cached = this.ctx.recallUploadedFile(element.fileId);
|
||||
|
||||
if (isCachedFileUsableInTarget(cached, groupId, userId)) {
|
||||
if (groupId !== undefined && cached?.busId === 104 && !allowTemporary) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'temporary group files require only file or image segments in the same forward node',
|
||||
'file',
|
||||
);
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
@@ -503,6 +527,7 @@ export class ForwardApi {
|
||||
fileNameForUpload(element, cached),
|
||||
groupId,
|
||||
userId,
|
||||
allowTemporary,
|
||||
);
|
||||
return {
|
||||
...stripFileSource(element),
|
||||
@@ -520,9 +545,12 @@ export class ForwardApi {
|
||||
): Promise<ForwardNodePayload[]> {
|
||||
return Promise.all(
|
||||
nodes.map(async (node) => {
|
||||
const allowTemporary = node.elements.every(
|
||||
(element) => element.type === 'file' || element.type === 'image',
|
||||
);
|
||||
const elements = await Promise.all(
|
||||
node.elements.map((element) =>
|
||||
this.prepareForwardFileElement(element, groupId, userId),
|
||||
this.prepareForwardFileElement(element, groupId, userId, allowTemporary),
|
||||
),
|
||||
);
|
||||
return cloneNodeWithElements(node, elements);
|
||||
@@ -593,6 +621,7 @@ export class ForwardApi {
|
||||
// — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round-
|
||||
// trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`.
|
||||
const myInnerActions: ForwardInnerAction[] = [];
|
||||
const cachedLayers = new Map<string, ForwardNodePayload[]>();
|
||||
const processedNodes: ForwardNodePayload[] = [];
|
||||
const isGroup = groupId !== undefined;
|
||||
|
||||
@@ -605,6 +634,11 @@ export class ForwardApi {
|
||||
// and `inner.innerActions` already contains deeper layers.
|
||||
myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody });
|
||||
myInnerActions.push(...inner.innerActions);
|
||||
|
||||
for (const [resId, cached] of inner.cachedLayers) {
|
||||
cachedLayers.set(resId, cached);
|
||||
}
|
||||
|
||||
// Replace the inner placeholder element with a forward preview
|
||||
// pointing at the inner res_id. `forwardUuid: inner.uuid`
|
||||
// baked into the LightApp JSON's `meta.detail.uniseq` is what
|
||||
@@ -692,7 +726,7 @@ export class ForwardApi {
|
||||
throw new Error('upload forward message response missing res_id');
|
||||
}
|
||||
|
||||
forwardResCache.set(
|
||||
cachedLayers.set(
|
||||
resId,
|
||||
uploadReadyNodes.map((node) => ({
|
||||
...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)),
|
||||
@@ -714,20 +748,21 @@ export class ForwardApi {
|
||||
// from (1) — no separate fetch needed.
|
||||
uuid: randomUUID(),
|
||||
innerActions: myInnerActions,
|
||||
cachedLayers,
|
||||
};
|
||||
}
|
||||
|
||||
async fetch(resId: string): Promise<ForwardNodePayload[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const cached = forwardResCache.get(resId);
|
||||
const cached = this.cache.get(resId);
|
||||
|
||||
if (cached) {
|
||||
const nodes = cloneNodes(cached);
|
||||
const nodes = cloneNodes(cached.nodes);
|
||||
|
||||
// Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich
|
||||
// Bundled inner nodes are cached un-enriched; enrich
|
||||
// on read (a no-op once names are present) and persist so later hits skip.
|
||||
if (await this.enrichSenders(nodes)) {
|
||||
forwardResCache.set(resId, cloneNodes(nodes));
|
||||
this.cache.update(cached, cloneNodes(nodes));
|
||||
}
|
||||
|
||||
return nodes;
|
||||
@@ -820,9 +855,7 @@ export class ForwardApi {
|
||||
// matching piggyback body, decode it into inner nodes, and seed
|
||||
// the cache by the inner resId so a follow-up `fetch(innerResId)`
|
||||
// hits the cache instead of the wire.
|
||||
if (piggybackByUuid.size > 0) {
|
||||
this.consumePiggybacks(nodes, piggybackByUuid);
|
||||
}
|
||||
const cachedLayers = this.collectForwardLayers(resId, nodes, piggybackByUuid);
|
||||
|
||||
// Fill sender nickname/card for nodes the SsoRecvLongMsg payload left empty
|
||||
// or stamped with the "QQ用户" placeholder (#174) — the long-msg member name
|
||||
@@ -830,7 +863,8 @@ export class ForwardApi {
|
||||
await this.enrichSenders(nodes);
|
||||
|
||||
if (nodes.length > 0) {
|
||||
forwardResCache.set(resId, cloneNodes(nodes));
|
||||
cachedLayers.set(resId, cloneNodes(nodes));
|
||||
this.cache.set(resId, cachedLayers);
|
||||
}
|
||||
|
||||
return nodes;
|
||||
@@ -872,7 +906,7 @@ export class ForwardApi {
|
||||
}
|
||||
|
||||
for (const [groupId, groupNodes] of byGroup) {
|
||||
let byUin: Map<number, { nickname: string; card: string }>;
|
||||
let byUin: Map<number, { nickname: string; card?: string }>;
|
||||
|
||||
try {
|
||||
const members = await this.ctx.apis.contacts.fetchGroupMemberList(groupId);
|
||||
@@ -1017,20 +1051,22 @@ export class ForwardApi {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Recursively resolve forward previews against the piggyback table.
|
||||
/** Resolve forward previews against the piggyback table.
|
||||
* For every `{type: 'forward', resId, forwardUuid}` element we find,
|
||||
* look up the uniseq in the piggyback map; if hit, decode the
|
||||
* inner msgBody and cache it by inner resId, then descend into that
|
||||
* inner layer to resolve deeper nestings carried in the SAME
|
||||
* piggyback set (NapCat hoists the entire tree's piggybacks onto
|
||||
* the outermost action list). */
|
||||
private consumePiggybacks(
|
||||
private collectForwardLayers(
|
||||
resId: string,
|
||||
nodes: ForwardNodePayload[],
|
||||
piggybackByUuid: Map<string, PushMsgBody[]>,
|
||||
): void {
|
||||
const seen = new Set<string>();
|
||||
): Map<string, ForwardNodePayload[]> {
|
||||
const layers = new Map([[resId, cloneNodes(nodes)]]);
|
||||
const decodedByUuid = new Map<string, ForwardNodePayload[]>();
|
||||
|
||||
const visit = (chain: ForwardNodePayload[]): void => {
|
||||
for (const chain of layers.values()) {
|
||||
for (const node of chain) {
|
||||
for (const elem of node.elements) {
|
||||
if (elem.type !== 'forward') {
|
||||
@@ -1040,25 +1076,33 @@ export class ForwardApi {
|
||||
const uuid = elem.forwardUuid;
|
||||
const innerResId = elem.resId;
|
||||
|
||||
if (!uuid || !innerResId || seen.has(uuid)) {
|
||||
if (!uuid || !innerResId || layers.has(innerResId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const body = piggybackByUuid.get(uuid);
|
||||
const body =
|
||||
piggybackByUuid.get(uuid) ??
|
||||
(uuid.startsWith('MultiMsg_')
|
||||
? piggybackByUuid.get(uuid.slice('MultiMsg_'.length))
|
||||
: undefined);
|
||||
|
||||
if (!body) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(uuid);
|
||||
const innerNodes = this.decodeMsgBodiesToNodes(body);
|
||||
forwardResCache.set(innerResId, cloneNodes(innerNodes));
|
||||
visit(innerNodes);
|
||||
let innerNodes = decodedByUuid.get(uuid);
|
||||
|
||||
if (!innerNodes) {
|
||||
innerNodes = cloneNodes(this.decodeMsgBodiesToNodes(body));
|
||||
decodedByUuid.set(uuid, innerNodes);
|
||||
}
|
||||
|
||||
layers.set(innerResId, innerNodes);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
visit(nodes);
|
||||
return layers;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,14 @@ import { MuteMember } from '@snowluma/protocol/oidb-services/group-admin/mute-me
|
||||
import { SetAddOption } from '@snowluma/protocol/oidb-services/group-admin/set-add-option';
|
||||
import { SetAddRequest } from '@snowluma/protocol/oidb-services/group-admin/set-add-request';
|
||||
import { SetAdmin } from '@snowluma/protocol/oidb-services/group-admin/set-admin';
|
||||
import { GetAdminPermissions } from '@snowluma/protocol/oidb-services/group-admin/get-admin-permissions';
|
||||
import { GetAdminReceiveVerify } from '@snowluma/protocol/oidb-services/group-admin/get-admin-receive-verify';
|
||||
import {
|
||||
SetAdminPermissions,
|
||||
type GroupAdminPermissionPatch,
|
||||
} from '@snowluma/protocol/oidb-services/group-admin/set-admin-permissions';
|
||||
import { SetAdminReceiveVerify } from '@snowluma/protocol/oidb-services/group-admin/set-admin-receive-verify';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { SetGroupName } from '@snowluma/protocol/oidb-services/group-admin/set-group-name';
|
||||
import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set-group-remark';
|
||||
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
|
||||
@@ -39,6 +47,8 @@ import { ModifyGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin
|
||||
import { OidbError } from '@snowluma/protocol/oidb-service';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
const log = createLogger('Bridge.GroupAdmin');
|
||||
|
||||
/** QQ only accepts this write from the group owner (#411). */
|
||||
export const MEMBER_PERMISSIONS_OWNER_ONLY =
|
||||
'only the group owner can change group member permissions';
|
||||
@@ -343,6 +353,62 @@ export class GroupAdminApi {
|
||||
return SetAdmin.invoke(this.ctx, { groupId, userId, enable });
|
||||
}
|
||||
|
||||
async getAdminPermissions(groupId: number, userId: number) {
|
||||
const logger = log.child({ uin: Number(this.ctx.identity.uin) });
|
||||
logger.debug('Reading administrator permissions group=%s user=%s', groupId, userId);
|
||||
const [snapshot, receiveVerify] = await Promise.all([
|
||||
GetAdminPermissions.invoke(this.ctx, { groupId, userId }),
|
||||
GetAdminReceiveVerify.invoke(this.ctx, { groupId, userId }),
|
||||
]);
|
||||
logger.debug(
|
||||
'Administrator permissions received group=%s user=%s recall=%s kick=%s limit=%s receiveVerify=%s',
|
||||
groupId,
|
||||
userId,
|
||||
snapshot.recallMemberMessage,
|
||||
snapshot.kickMember,
|
||||
snapshot.kickMemberPerDay,
|
||||
receiveVerify,
|
||||
);
|
||||
return {
|
||||
group_id: groupId,
|
||||
user_id: userId,
|
||||
recall_member_message: snapshot.recallMemberMessage,
|
||||
kick_member: snapshot.kickMember,
|
||||
kick_member_per_day: snapshot.kickMemberPerDay,
|
||||
receive_verify: receiveVerify,
|
||||
};
|
||||
}
|
||||
|
||||
async setAdminPermissions(
|
||||
groupId: number,
|
||||
userId: number,
|
||||
patch: GroupAdminPermissionPatch,
|
||||
): Promise<void> {
|
||||
const logger = log.child({ uin: Number(this.ctx.identity.uin) });
|
||||
logger.debug(
|
||||
'Setting administrator permissions group=%s user=%s recall=%s kick=%s limit=%s',
|
||||
groupId,
|
||||
userId,
|
||||
patch.recallMemberMessage,
|
||||
patch.kickMember,
|
||||
patch.kickMemberPerDay,
|
||||
);
|
||||
await SetAdminPermissions.invoke(this.ctx, { groupId, userId, ...patch });
|
||||
logger.debug('Administrator permissions acknowledged group=%s user=%s', groupId, userId);
|
||||
}
|
||||
|
||||
async setAdminReceiveVerify(groupId: number, userId: number, enable: boolean): Promise<void> {
|
||||
const logger = log.child({ uin: Number(this.ctx.identity.uin) });
|
||||
logger.debug(
|
||||
'Setting administrator receive-verify group=%s user=%s enable=%s',
|
||||
groupId,
|
||||
userId,
|
||||
enable,
|
||||
);
|
||||
await SetAdminReceiveVerify.invoke(this.ctx, { groupId, userId, enable });
|
||||
logger.debug('Administrator receive-verify confirmed group=%s user=%s', groupId, userId);
|
||||
}
|
||||
|
||||
setCard(groupId: number, userId: number, card: string): Promise<void> {
|
||||
return SetMemberCard.invoke(this.ctx, { groupId, userId, card });
|
||||
}
|
||||
|
||||
@@ -76,6 +76,16 @@ export interface UploadFileResult {
|
||||
fileHash?: string | null;
|
||||
}
|
||||
|
||||
export interface GroupFileUploadResult {
|
||||
fileId: string;
|
||||
busId: number;
|
||||
}
|
||||
|
||||
export interface GroupFileUploadOptions {
|
||||
/** False when the enclosing message contains content a temporary file cannot carry. */
|
||||
allowTemporary?: boolean;
|
||||
}
|
||||
|
||||
// Re-export so callers don't have to dig into apis/shared.
|
||||
export type { MediaIndexNode } from './shared';
|
||||
|
||||
@@ -136,6 +146,7 @@ async function assertUnchanged(
|
||||
function buildGroupFileUploadExt(
|
||||
senderUin: number,
|
||||
groupId: number,
|
||||
busId: number,
|
||||
fileName: string,
|
||||
fileSize: number,
|
||||
md5: Uint8Array,
|
||||
@@ -150,7 +161,7 @@ function buildGroupFileUploadExt(
|
||||
unknown2: 1,
|
||||
entry: {
|
||||
busiBuff: {
|
||||
busId: 102,
|
||||
busId,
|
||||
senderUin: BigInt(senderUin),
|
||||
receiverUin: BigInt(groupId),
|
||||
groupCode: BigInt(groupId),
|
||||
@@ -255,12 +266,23 @@ export class GroupFileApi {
|
||||
|
||||
// ─────────────── publish (group file → chat) ───────────────
|
||||
|
||||
publish(groupId: number, fileId: string): Promise<void> {
|
||||
publish(groupId: number, fileId: string, busId?: number): Promise<void> {
|
||||
if (!fileId) {
|
||||
throw new Error('publish requires fileId');
|
||||
}
|
||||
|
||||
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
|
||||
return PublishGroupFile.invoke(this.ctx, {
|
||||
groupId,
|
||||
fileId,
|
||||
busId: busId ?? this.cachedBusId(groupId, fileId),
|
||||
});
|
||||
}
|
||||
|
||||
private cachedBusId(groupId: number, fileId: string): number {
|
||||
const cached = this.ctx.recallUploadedFile(fileId);
|
||||
return cached?.scope === 'group' && cached.groupId === groupId
|
||||
? (cached.busId ?? 102)
|
||||
: 102;
|
||||
}
|
||||
|
||||
trans(groupId: number, fileId: string): Promise<TransGroupFileResult> {
|
||||
@@ -290,7 +312,8 @@ export class GroupFileApi {
|
||||
folderId = '/',
|
||||
uploadFile = true,
|
||||
publishFile = uploadFile,
|
||||
): Promise<UploadFileResult> {
|
||||
options: GroupFileUploadOptions = {},
|
||||
): Promise<GroupFileUploadResult> {
|
||||
const bridge = this.ctx;
|
||||
// Group/private files may legitimately be up to 4 GiB on QQ's wire, so
|
||||
// override the default 1 GiB cap with the protocol ceiling. Stage onto a
|
||||
@@ -307,14 +330,36 @@ export class GroupFileApi {
|
||||
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
|
||||
const hashes = await hashFileStreaming(staged.filePath);
|
||||
|
||||
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
|
||||
const params: UploadGroupFileRequest.Params = {
|
||||
groupId,
|
||||
fileName,
|
||||
folderId: normalizeDirectory(folderId),
|
||||
fileSize: staged.fileSize,
|
||||
fileSha1: hashes.sha1,
|
||||
fileMd5: hashes.md5,
|
||||
});
|
||||
busId: 102,
|
||||
};
|
||||
let upload = await UploadGroupFileRequest.invoke(this.ctx, params);
|
||||
|
||||
// These are the storage-limit responses for which QQ switches to
|
||||
// temporary storage. Never retry transport, permission or arbitrary
|
||||
// service errors, and never retry the temporary request itself.
|
||||
if (upload.retCode === -403 || upload.retCode === -9801 || upload.retCode === -98090) {
|
||||
if (options.allowTemporary === false) {
|
||||
throw new Error(
|
||||
`temporary group files require only file or image segments; remove text and other content before retrying (group file upload code=${upload.retCode})`,
|
||||
);
|
||||
}
|
||||
|
||||
log.warn(
|
||||
'Group %d permanent file storage rejected upload (code=%d); retrying as a temporary file',
|
||||
groupId,
|
||||
upload.retCode,
|
||||
);
|
||||
params.busId = 104;
|
||||
upload = await UploadGroupFileRequest.invoke(this.ctx, params);
|
||||
}
|
||||
|
||||
ensureRetCodeZero(
|
||||
'group file upload',
|
||||
upload.retCode,
|
||||
@@ -322,6 +367,18 @@ export class GroupFileApi {
|
||||
upload.clientWording,
|
||||
);
|
||||
|
||||
const busId = upload.busId || params.busId;
|
||||
|
||||
if (busId !== 102 && busId !== 104) {
|
||||
throw new Error(`group file upload returned unsupported storage type: ${busId}`);
|
||||
}
|
||||
|
||||
if (busId === 104 && options.allowTemporary === false) {
|
||||
throw new Error(
|
||||
'temporary group files require only file or image segments; remove text and other content before retrying',
|
||||
);
|
||||
}
|
||||
|
||||
const fileId =
|
||||
typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
|
||||
|
||||
@@ -329,23 +386,6 @@ export class GroupFileApi {
|
||||
throw new Error('group file upload response missing file_id');
|
||||
}
|
||||
|
||||
// Remember the upload so a later `send_group_msg` carrying just the
|
||||
// file_id can route via `publish` without forcing the OneBot caller
|
||||
// to thread fileName/size/md5 separately. For groups the wire
|
||||
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
|
||||
// mainly for log-line correctness; the c2c counterpart in
|
||||
// `uploadPrivate` is where the cache is actually load-bearing.
|
||||
this.ctx.rememberUploadedFile({
|
||||
fileId,
|
||||
scope: 'group',
|
||||
groupId,
|
||||
fileName,
|
||||
fileSize: staged.fileSize,
|
||||
fileMd5: hashes.md5,
|
||||
fileSha1: hashes.sha1,
|
||||
rememberedAt: Date.now(),
|
||||
});
|
||||
|
||||
if (!upload.boolFileExist && uploadFile) {
|
||||
const senderUin = toInt(this.ctx.identity.uin);
|
||||
|
||||
@@ -366,6 +406,7 @@ export class GroupFileApi {
|
||||
const ext = buildGroupFileUploadExt(
|
||||
senderUin,
|
||||
groupId,
|
||||
busId,
|
||||
fileName,
|
||||
staged.fileSize,
|
||||
hashes.md5,
|
||||
@@ -386,6 +427,20 @@ export class GroupFileApi {
|
||||
await uploadHighwayHttp(bridge, session, 71, chunkSource, hashes.md5, ext);
|
||||
}
|
||||
|
||||
// Retain the storage type for later file_id publication and download.
|
||||
// A failed byte transfer must not leave a usable-looking cache entry.
|
||||
this.ctx.rememberUploadedFile({
|
||||
fileId,
|
||||
scope: 'group',
|
||||
groupId,
|
||||
busId,
|
||||
fileName,
|
||||
fileSize: staged.fileSize,
|
||||
fileMd5: hashes.md5,
|
||||
fileSha1: hashes.sha1,
|
||||
rememberedAt: Date.now(),
|
||||
});
|
||||
|
||||
// Stage 3: file is on the server, now publish it as a chat message.
|
||||
//
|
||||
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
|
||||
@@ -398,21 +453,18 @@ export class GroupFileApi {
|
||||
// tests can mock at the same Api boundary.
|
||||
if (publishFile) {
|
||||
try {
|
||||
await this.publish(groupId, fileId);
|
||||
await this.publish(groupId, fileId, busId);
|
||||
} catch (err) {
|
||||
// The bytes are already on the server and the fileId is valid —
|
||||
// fail loud but don't lose the upload result the action handler
|
||||
// committed to returning. Callers can still resolve the file by
|
||||
// id; they'll just have to re-publish it themselves.
|
||||
log.warn(
|
||||
'group file uploaded (fileId=%s) but chat post failed: %s',
|
||||
fileId,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
// Keep the completed upload identifiable, but a requested chat
|
||||
// publication must not be reported as a successful send.
|
||||
throw new Error(
|
||||
`group file uploaded (fileId=${fileId}) but chat post failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
{ cause: err },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { fileId };
|
||||
return { fileId, busId };
|
||||
} finally {
|
||||
await staged.cleanup();
|
||||
}
|
||||
@@ -714,8 +766,12 @@ export class GroupFileApi {
|
||||
|
||||
// ─────────────── url fetch (group / private files) ───────────────
|
||||
|
||||
async getUrl(groupId: number, fileId: string, busId = 102): Promise<string> {
|
||||
return GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId });
|
||||
async getUrl(groupId: number, fileId: string, busId?: number): Promise<string> {
|
||||
return GetGroupFileUrl.invoke(this.ctx, {
|
||||
groupId,
|
||||
fileId,
|
||||
busId: busId ?? this.cachedBusId(groupId, fileId),
|
||||
});
|
||||
}
|
||||
|
||||
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {
|
||||
|
||||
@@ -8,7 +8,7 @@ import type {
|
||||
SsoReadedReportReq,
|
||||
SsoReadedReportResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import { buildSendElems, encodePrivateRichText } from '@snowluma/protocol/element-builder';
|
||||
import { assertWindowShakeSendPolicy } from '@snowluma/protocol/element-manifest';
|
||||
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
|
||||
import { datalineTextFromElements, encodeDatalineText } from '@snowluma/protocol/dataline/codec';
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
fetchC2cRoamMessagePage,
|
||||
fetchGroupMessageRange,
|
||||
} from '@snowluma/protocol/msg-push';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { type bytes, protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
@@ -254,6 +254,7 @@ type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
|
||||
// ── Group-history fetch guards (the server frequency-limits / kicks abusive
|
||||
// pulls, so keep each request small, bound the loop, and space the sends). ──
|
||||
const HISTORY_MAX_COUNT = 200; // hard cap on messages returned per call
|
||||
const PRIVATE_HISTORY_PAGE_SIZE = 100;
|
||||
const HISTORY_CHUNK_SEQ = 30; // sequence span per server request (small packet)
|
||||
const HISTORY_MAX_REQUESTS = 12; // bound the walk-back loop
|
||||
const HISTORY_MIN_GAP_MS = 300; // minimum spacing between SsoGetGroupMsg sends
|
||||
@@ -547,15 +548,15 @@ export class MessageApi {
|
||||
userUid = await this.ctx.resolveUserUid(userUin);
|
||||
}
|
||||
|
||||
const protoElems = await buildSendElems(elements, {
|
||||
bridge: this.ctx as unknown as Bridge,
|
||||
const richText = await encodePrivateRichText(elements, {
|
||||
bridge: this.ctx,
|
||||
userUid,
|
||||
scene: 'direct-private',
|
||||
});
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
const clientSeq = this.ctx.nextClientSequence();
|
||||
|
||||
const request = protobuf_encode<SendMessageRequest>({
|
||||
const request = protobuf_encode<SendMessageRequest<bytes>>({
|
||||
routingHead: {
|
||||
c2c: {
|
||||
uin: userUin,
|
||||
@@ -567,11 +568,7 @@ export class MessageApi {
|
||||
subType: 0,
|
||||
c2cCmd: 11,
|
||||
},
|
||||
messageBody: {
|
||||
richText: {
|
||||
elems: protoElems,
|
||||
},
|
||||
},
|
||||
messageBody: { richText },
|
||||
clientSequence: clientSeq,
|
||||
random,
|
||||
syncCookie: new Uint8Array(0),
|
||||
@@ -1543,7 +1540,7 @@ export class MessageApi {
|
||||
selfUin,
|
||||
friendUid,
|
||||
cursor.time,
|
||||
want - collected.size,
|
||||
Math.min(want - collected.size, PRIVATE_HISTORY_PAGE_SIZE),
|
||||
cursor.random,
|
||||
),
|
||||
);
|
||||
@@ -1564,7 +1561,7 @@ export class MessageApi {
|
||||
break;
|
||||
}
|
||||
|
||||
if (page.cursor.time === 0 && page.cursor.random === 0) {
|
||||
if (page.isComplete || (page.cursor.time === 0 && page.cursor.random === 0)) {
|
||||
reachedEnd = true;
|
||||
break;
|
||||
}
|
||||
@@ -1572,11 +1569,6 @@ export class MessageApi {
|
||||
const nextCursorKey = `${page.cursor.time}:${page.cursor.random}`;
|
||||
|
||||
if (seenCursors.has(nextCursorKey)) {
|
||||
if (page.messages.length === 0) {
|
||||
reachedEnd = true;
|
||||
break;
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`private roam history cursor did not advance from ${cursor.time}/${cursor.random}`,
|
||||
);
|
||||
|
||||
@@ -1,33 +1,187 @@
|
||||
import type { JsonObject } from '@snowluma/common/json';
|
||||
import {
|
||||
commentQzoneMsg,
|
||||
deleteQzoneMsg,
|
||||
getQzoneFeeds,
|
||||
getQzoneMsgDetail,
|
||||
getQzoneMsgList,
|
||||
getQzoneProfile,
|
||||
publishQzoneMsg,
|
||||
replyQzoneComment,
|
||||
setQzoneBlack,
|
||||
setQzoneLike,
|
||||
setQzoneProfile,
|
||||
updateQzoneMsgRight,
|
||||
uploadQzoneImageFromSource,
|
||||
type QzoneCommentResult,
|
||||
type QzoneFeedsResult,
|
||||
type QzoneFeedsPage,
|
||||
type QzoneMsgDetailResult,
|
||||
type QzoneMsgListResult,
|
||||
type QzoneProfile,
|
||||
type QzoneProfileUpdate,
|
||||
type QzonePublishResult,
|
||||
type QzoneReplyTarget,
|
||||
type QzoneUpdateRightResult,
|
||||
type QzoneUploadImageResult,
|
||||
} from '@snowluma/protocol/web/qzone';
|
||||
import {
|
||||
getQzonePublicCapabilities,
|
||||
getQzoneHomeFeeds,
|
||||
getQzoneFeedDetail,
|
||||
type QzoneFeedDetail,
|
||||
getQzoneShareArk,
|
||||
type QzoneShareArk,
|
||||
getQzonePublicFeeds,
|
||||
getQzonePublicFeedDetail,
|
||||
getQzonePublicComments,
|
||||
getQzonePublicReplies,
|
||||
setQzonePublicUpvote,
|
||||
setQzonePublicLike,
|
||||
setQzonePublicCommentLike,
|
||||
commentQzonePublicFeed,
|
||||
replyQzonePublicFeed,
|
||||
deleteQzonePublicComment,
|
||||
deleteQzonePublicReply,
|
||||
setQzonePublicFollow,
|
||||
forwardQzonePublicFeed,
|
||||
type QzonePublicContent,
|
||||
type QzonePublicFeedsPage,
|
||||
} from '@snowluma/protocol/web/qzone-public';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
/**
|
||||
* Personal QQ-Zone (个人空间) web API: 说说 (feed) read/write, likes,
|
||||
* comments, image upload — all over the cookie-backed qzone.qq.com CGIs,
|
||||
* Personal QQ-Zone (个人空间) web API: 说说, public recommendations, likes,
|
||||
* comments and image upload over the cookie-backed Qzone web interfaces,
|
||||
* reusing the same `getCookies('qzone.qq.com')` plumbing as GroupAlbumApi.
|
||||
* Distinct from the group-album surface, which lives on GroupAlbumApi.
|
||||
*/
|
||||
export class QzoneApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
async getProfile(targetUin?: number): Promise<QzoneProfile> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzoneProfile(cookieObject, this.ctx.identity.uin, targetUin?.toString());
|
||||
}
|
||||
|
||||
async setProfile(profile: QzoneProfileUpdate): Promise<void> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await setQzoneProfile(cookieObject, this.ctx.identity.uin, profile);
|
||||
}
|
||||
|
||||
async getPublicCapabilities(): Promise<JsonObject> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzonePublicCapabilities(cookies, this.ctx.identity.uin);
|
||||
}
|
||||
|
||||
async getPublicFeeds(cursor?: string): Promise<QzonePublicFeedsPage> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzonePublicFeeds(cookies, this.ctx.identity.uin, cursor);
|
||||
}
|
||||
|
||||
async getHomeFeeds(targetUin?: number, cursor?: string): Promise<QzonePublicFeedsPage> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
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);
|
||||
}
|
||||
|
||||
async getPublicFeedDetail(feed: JsonObject): Promise<JsonObject> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzonePublicFeedDetail(cookies, feed);
|
||||
}
|
||||
|
||||
async getPublicComments(feed: JsonObject, cursor: string): Promise<JsonObject> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzonePublicComments(cookies, feed, cursor);
|
||||
}
|
||||
|
||||
async getPublicReplies(
|
||||
feed: JsonObject,
|
||||
comment: JsonObject,
|
||||
cursor = '',
|
||||
pageSize = 20,
|
||||
): Promise<JsonObject> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzonePublicReplies(cookies, feed, comment, cursor, pageSize);
|
||||
}
|
||||
|
||||
async setPublicUpvote(feed: JsonObject, enable = true): Promise<JsonObject> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return setQzonePublicUpvote(cookies, feed, enable);
|
||||
}
|
||||
|
||||
async setPublicLike(feed: JsonObject, enable = true): Promise<JsonObject> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return setQzonePublicLike(cookies, feed, enable);
|
||||
}
|
||||
|
||||
async setPublicCommentLike(
|
||||
feed: JsonObject,
|
||||
comment: JsonObject,
|
||||
enable = true,
|
||||
reply?: JsonObject,
|
||||
): Promise<JsonObject> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return setQzonePublicCommentLike(cookies, feed, comment, enable, reply);
|
||||
}
|
||||
|
||||
async commentPublicFeed(feed: JsonObject, content: QzonePublicContent): Promise<JsonObject> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
const user = {
|
||||
uin: this.ctx.identity.uin,
|
||||
uid: this.ctx.identity.selfUid ?? '',
|
||||
nick: this.ctx.identity.nickname,
|
||||
};
|
||||
return commentQzonePublicFeed(cookies, feed, user, content);
|
||||
}
|
||||
|
||||
async replyPublicFeed(
|
||||
feed: JsonObject,
|
||||
comment: JsonObject,
|
||||
content: QzonePublicContent,
|
||||
reply?: JsonObject,
|
||||
): Promise<JsonObject> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
const user = {
|
||||
uin: this.ctx.identity.uin,
|
||||
uid: this.ctx.identity.selfUid ?? '',
|
||||
nick: this.ctx.identity.nickname,
|
||||
};
|
||||
return replyQzonePublicFeed(cookies, feed, user, comment, content, reply);
|
||||
}
|
||||
|
||||
async deletePublicComment(feed: JsonObject, comment: JsonObject): Promise<JsonObject> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return deleteQzonePublicComment(cookies, feed, comment);
|
||||
}
|
||||
|
||||
async deletePublicReply(
|
||||
feed: JsonObject,
|
||||
comment: JsonObject,
|
||||
reply: JsonObject,
|
||||
): Promise<JsonObject> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return deleteQzonePublicReply(cookies, feed, comment, reply);
|
||||
}
|
||||
|
||||
async setPublicFollow(feed: JsonObject, enable = true): Promise<JsonObject> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return setQzonePublicFollow(cookies, feed, enable);
|
||||
}
|
||||
|
||||
async forwardPublicFeed(feed: JsonObject, reason = ''): Promise<JsonObject> {
|
||||
const cookies = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return forwardQzonePublicFeed(cookies, feed, reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取说说列表。`targetUin` 省略时取机器人自己的空间。
|
||||
* `pos` 为起始偏移,`num` 为本页数量(服务端上限约 20/页)。
|
||||
@@ -51,12 +205,12 @@ export class QzoneApi {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取好友动态(feed)。`pageNum` 为 1 起的页码,`count` 为本页数量。
|
||||
* 获取好友动态。页码调用从首页顺序定位;续页优先传上一页的 cursor。
|
||||
* 始终以机器人自己的身份拉取好友动态。
|
||||
*/
|
||||
async getFeeds(pageNum = 1, count = 10): Promise<QzoneFeedsResult> {
|
||||
async getFeeds(pageNum = 1, count = 10, cursor?: string): Promise<QzoneFeedsPage> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count);
|
||||
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count, cursor);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -133,6 +287,7 @@ export class QzoneApi {
|
||||
* 始终以机器人身份发表评论。返回新评论 id(尽力而为)。
|
||||
* `richType` / `richval`: 带图评论时传 richType=1 和图片直链 URL
|
||||
* (从 uploadImageFromSource 的 url 字段获取)。
|
||||
* `reply` 指定父评论及可选回复对象;楼中楼回复仅支持文字。
|
||||
*/
|
||||
async comment(
|
||||
tid: string,
|
||||
@@ -140,10 +295,20 @@ export class QzoneApi {
|
||||
targetUin: number | undefined,
|
||||
richType?: number,
|
||||
richval?: string,
|
||||
reply?: QzoneReplyTarget,
|
||||
): Promise<QzoneCommentResult> {
|
||||
if (reply !== undefined && (richType !== undefined || richval !== undefined)) {
|
||||
throw new Error('images are not supported for Qzone comment replies');
|
||||
}
|
||||
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
|
||||
if (reply !== undefined) {
|
||||
return replyQzoneComment(cookieObject, selfUin, owner, tid, content, reply);
|
||||
}
|
||||
|
||||
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content, richType, richval);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,13 +4,21 @@ import { packetTimeoutMs } from '@snowluma/bridge/packet-timeout';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { MSG_PUSH_CMD, parseMsgPushOrThrow, SysMsgDedup } from '@snowluma/protocol/msg-push';
|
||||
import {
|
||||
MSG_PUSH_CMD,
|
||||
parseMsgPushOrThrow,
|
||||
SysMsgDedup,
|
||||
decodeClientMessageReceipt,
|
||||
fetchClientMessage,
|
||||
} from '@snowluma/protocol/msg-push';
|
||||
import { KICK_NT_CMD, parseKickNT } from '@snowluma/protocol/kick-nt';
|
||||
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
|
||||
import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
|
||||
import { buildApiHub, type ApiHub } from './apis';
|
||||
import { AiVoiceChatType, type AiVoiceCategory, type StrangerStatus } from './apis/extras';
|
||||
import type { BridgeInterface, RosterWarmupResult } from './bridge-interface';
|
||||
import type { UploadedFileMeta } from './bridge-context';
|
||||
export type { UploadedFileMeta } from './bridge-context';
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
const runtimeLog = createLogger('Bridge.Runtime');
|
||||
@@ -38,6 +46,10 @@ export class Bridge implements BridgeInterface {
|
||||
private onlineClients_: readonly Readonly<OnlineDeviceInfo>[] | null = null;
|
||||
private disposePromise_: Promise<void> | null = null;
|
||||
private readonly pendingPackets_ = new Set<Promise<void>>();
|
||||
private readonly clientMessageTasks_ = new Map<
|
||||
string,
|
||||
{ connection: ProcessConnection; work: Promise<void> }
|
||||
>();
|
||||
private rosterWarmupStarted_ = false;
|
||||
private settleRosterWarmup!: (result: RosterWarmupResult) => void;
|
||||
private readonly rosterWarmup = new Promise<RosterWarmupResult>((resolve) => {
|
||||
@@ -61,72 +73,9 @@ export class Bridge implements BridgeInterface {
|
||||
fetchGroupMemberList: async (groupId) => {
|
||||
await this.apis.contacts.fetchGroupMemberList(groupId);
|
||||
},
|
||||
resolveGroupJoinRequest: async (groupId, uid, subType) => {
|
||||
const [main, filtered] = await Promise.allSettled([
|
||||
this.apis.contacts.fetchGroupRequestsByUid(false),
|
||||
this.apis.contacts.fetchGroupRequestsByUid(true),
|
||||
]);
|
||||
|
||||
if (main.status === 'rejected') {
|
||||
log.warn(
|
||||
'group-request enrichment main inbox failed: group=%d uid=%s err=%s',
|
||||
groupId,
|
||||
uid,
|
||||
main.reason instanceof Error ? main.reason.message : String(main.reason),
|
||||
);
|
||||
}
|
||||
|
||||
if (filtered.status === 'rejected') {
|
||||
log.warn(
|
||||
'group-request enrichment filtered inbox failed: group=%d uid=%s err=%s',
|
||||
groupId,
|
||||
uid,
|
||||
filtered.reason instanceof Error
|
||||
? filtered.reason.message
|
||||
: String(filtered.reason),
|
||||
);
|
||||
}
|
||||
|
||||
if (main.status === 'rejected' && filtered.status === 'rejected') {
|
||||
throw new Error('failed to fetch group requests from both inboxes');
|
||||
}
|
||||
|
||||
const requests = [
|
||||
...(main.status === 'fulfilled' ? main.value : []),
|
||||
...(filtered.status === 'fulfilled' ? filtered.value : []),
|
||||
];
|
||||
const matches = requests.filter((r) => {
|
||||
if (r.groupId !== groupId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
|
||||
});
|
||||
|
||||
if (subType === 'invite') {
|
||||
return matches.find((r) => r.notifyType === 1) ?? matches[0] ?? null;
|
||||
}
|
||||
|
||||
return matches.find((r) => r.notifyType === 7) ?? matches[0] ?? null;
|
||||
},
|
||||
resolveGroupInviteCardSequence: async (groupId) => {
|
||||
const deadline = Date.now() + 1_000;
|
||||
|
||||
do {
|
||||
const sequence = this.apis.contacts.getGroupInviteCardSequence(groupId);
|
||||
|
||||
if (sequence) {
|
||||
return sequence;
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
} while (Date.now() < deadline);
|
||||
|
||||
return null;
|
||||
},
|
||||
rememberGroupInviteCardSequence: (groupUin, sequence) => {
|
||||
this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence);
|
||||
},
|
||||
resolveGroupJoinRequest: (groupId, uid, subType, invitedUid) =>
|
||||
this.apis.contacts.resolveGroupJoinRequest(groupId, uid, subType, invitedUid),
|
||||
groupInvites: this.apis.contacts.groupInvites,
|
||||
});
|
||||
this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) =>
|
||||
parseMsgPushOrThrow(pkt, identity, this.sysMsgDedup_),
|
||||
@@ -155,6 +104,7 @@ export class Bridge implements BridgeInterface {
|
||||
this.disposePromise_ = (async () => {
|
||||
try {
|
||||
await Promise.allSettled(this.pendingPackets_);
|
||||
this.apis.contacts.dispose();
|
||||
await this.identity.close();
|
||||
} finally {
|
||||
this.events.clear();
|
||||
@@ -173,9 +123,13 @@ export class Bridge implements BridgeInterface {
|
||||
|
||||
bindPid(pid: number, client: PacketSender): void {
|
||||
const previous = this.activeConnection;
|
||||
const existing = this.connections.get(pid);
|
||||
this.connections.delete(pid);
|
||||
// A new login stays healthy until the watchdog confirms a failure.
|
||||
this.connections.set(pid, { pid, client, receiveHealthy: true });
|
||||
const connection =
|
||||
existing?.client === client ? existing : { pid, client, receiveHealthy: true };
|
||||
connection.receiveHealthy = true;
|
||||
this.connections.set(pid, connection);
|
||||
|
||||
if (previous?.pid !== pid || previous.client !== client) {
|
||||
runtimeLog.trace(
|
||||
@@ -252,12 +206,85 @@ export class Bridge implements BridgeInterface {
|
||||
return Promise.reject(new Error('Bridge is disposed'));
|
||||
}
|
||||
|
||||
const work = this.identity.initialization.then(() => this.pipeline.process(pkt));
|
||||
const connection = this.connections.get(pkt.pid);
|
||||
const work = this.identity.initialization.then(() =>
|
||||
pkt.source === 'client-message'
|
||||
? this.processClientMessage(pkt, connection)
|
||||
: this.pipeline.process(pkt),
|
||||
);
|
||||
this.pendingPackets_.add(work);
|
||||
void work.finally(() => this.pendingPackets_.delete(work)).catch(() => undefined);
|
||||
return work;
|
||||
}
|
||||
|
||||
private async processClientMessage(
|
||||
pkt: PacketInfo,
|
||||
connection: ProcessConnection | undefined,
|
||||
): Promise<void> {
|
||||
const requireConnection = (): ProcessConnection => {
|
||||
if (
|
||||
this.disposePromise_ ||
|
||||
!connection ||
|
||||
this.connections.get(pkt.pid) !== connection
|
||||
) {
|
||||
throw new Error('Client message receipt belongs to an inactive connection');
|
||||
}
|
||||
|
||||
return connection;
|
||||
};
|
||||
|
||||
const current = requireConnection();
|
||||
const receipt = decodeClientMessageReceipt(pkt, this.identity.uin);
|
||||
const key = JSON.stringify([
|
||||
pkt.pid,
|
||||
receipt.peerUid,
|
||||
receipt.sequence,
|
||||
receipt.clientSequence,
|
||||
receipt.timestamp,
|
||||
]);
|
||||
const pending = this.clientMessageTasks_.get(key);
|
||||
|
||||
if (pending?.connection === current) {
|
||||
return pending.work;
|
||||
}
|
||||
|
||||
if (this.clientMessageTasks_.size >= 256) {
|
||||
throw new Error('Too many pending client message lookups');
|
||||
}
|
||||
|
||||
runtimeLog.trace(
|
||||
'client_message_lookup_start uin=%j pid=%d seqId=%d',
|
||||
this.identity.uin,
|
||||
pkt.pid,
|
||||
pkt.seqId,
|
||||
);
|
||||
const work = (async () => {
|
||||
const source: PacketSender = {
|
||||
sendPacket: (cmd, body, timeout) =>
|
||||
requireConnection().client.sendPacket(cmd, body, timeout),
|
||||
};
|
||||
const event = await fetchClientMessage(source, this.identity, receipt);
|
||||
requireConnection();
|
||||
await this.pipeline.processEvents(pkt, [event]);
|
||||
runtimeLog.trace(
|
||||
'client_message_lookup_complete uin=%j pid=%d seqId=%d',
|
||||
this.identity.uin,
|
||||
pkt.pid,
|
||||
pkt.seqId,
|
||||
);
|
||||
})();
|
||||
const task = { connection: current, work };
|
||||
this.clientMessageTasks_.set(key, task);
|
||||
|
||||
try {
|
||||
await work;
|
||||
} finally {
|
||||
if (this.clientMessageTasks_.get(key) === task) {
|
||||
this.clientMessageTasks_.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rememberUploadedFile(meta: UploadedFileMeta): void {
|
||||
if (!meta.fileId) {
|
||||
return;
|
||||
@@ -569,23 +596,6 @@ export interface SendMessageReceipt {
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface UploadedFileMeta {
|
||||
fileId: string;
|
||||
scope: 'group' | 'private';
|
||||
/** Group id if scope='group', else `undefined`. */
|
||||
groupId?: number;
|
||||
/** Friend uin if scope='private', else `undefined`. */
|
||||
userId?: number;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
fileMd5: Uint8Array;
|
||||
fileSha1: Uint8Array;
|
||||
/** Server-issued hash returned alongside the upload (private only). */
|
||||
fileHash?: string;
|
||||
/** Insert time — used to evict the oldest entry when the cache fills. */
|
||||
rememberedAt: number;
|
||||
}
|
||||
|
||||
export interface DownloadRKeyInfo {
|
||||
rkey: string;
|
||||
ttlSeconds: number;
|
||||
|
||||
@@ -434,7 +434,13 @@ export class BridgeManager implements BridgeSessionSource {
|
||||
}
|
||||
|
||||
const closing = this.closingSessions_.get(uin);
|
||||
const beforeOpen = closing ? Promise.all(closing).then(() => undefined) : undefined;
|
||||
// allSettled, not all: a failed close stays in the bookkeeping (so
|
||||
// dispose can still report it) but must not reject this gate — a
|
||||
// rejected gate would keep the identity DB of every future session
|
||||
// for this UIN closed until the process restarts.
|
||||
const beforeOpen = closing
|
||||
? Promise.allSettled(closing).then(() => undefined)
|
||||
: undefined;
|
||||
const bridge = new Bridge(IdentityService.openForUin(uin, 'data', beforeOpen));
|
||||
this.bridges.set(uin, bridge);
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { getRuntimeIntegrity, HookManager } from '@snowluma/bridge';
|
||||
import { APP_VERSION } from '@snowluma/common/version';
|
||||
import { configureFileTransport } from '@snowluma/common/log-file-transport';
|
||||
import { closeLogger, createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
@@ -23,7 +22,6 @@ import { createNotificationManager } from './notifications/manager';
|
||||
import { createStateWiring } from './webui/state-wiring';
|
||||
import { initWebUI } from './webui/server';
|
||||
import { bindSystemFaceCatalog } from './sys-face-catalog';
|
||||
import { startNativeStageSync, tempStagePath } from './native-stage-sync';
|
||||
import { logRuntimeIntegrity } from './runtime-integrity-log';
|
||||
import { RESTART_EXIT_CODE, runApplication } from './update/startup';
|
||||
|
||||
@@ -60,11 +58,6 @@ async function main() {
|
||||
});
|
||||
log.info('SnowLuma starting');
|
||||
logRuntimeIntegrity(await getRuntimeIntegrity());
|
||||
const stopNativeStageSync = startNativeStageSync({
|
||||
version: APP_VERSION,
|
||||
dataDir: 'data',
|
||||
tempPath: tempStagePath(),
|
||||
});
|
||||
|
||||
// One-shot: lift a legacy per-UIN musicSignUrl into the global store before
|
||||
// any session (and thus any per-UIN config rewrite) can drop it.
|
||||
@@ -193,16 +186,6 @@ async function main() {
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
stopNativeStageSync.stop();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error(
|
||||
'stage sync shutdown failed: %s',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
hookManager.dispose();
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,347 +0,0 @@
|
||||
import {
|
||||
readFileSync,
|
||||
writeFileSync,
|
||||
mkdirSync,
|
||||
statSync,
|
||||
openSync,
|
||||
readSync,
|
||||
closeSync,
|
||||
fstatSync,
|
||||
} from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
|
||||
export const STAGE_FILE_NAME = 's7.log';
|
||||
export const MIRROR_LIMIT_BYTES = 1024 * 1024;
|
||||
|
||||
const VERSION_HEADER = /^v\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
|
||||
|
||||
export function isVersionHeader(line: string): boolean {
|
||||
return VERSION_HEADER.test(line);
|
||||
}
|
||||
|
||||
export function lineSeverity(line: string): 'info' | 'error' {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
return parts.length >= 4 && parts[3] === '1' ? 'error' : 'info';
|
||||
}
|
||||
|
||||
export function publicLine(version: string, raw: string): string {
|
||||
return `${version} ${raw.trim()}`;
|
||||
}
|
||||
|
||||
function byteSize(lines: readonly string[]): number {
|
||||
if (lines.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return Buffer.byteLength(`${lines.join('\n')}\n`, 'utf8');
|
||||
}
|
||||
|
||||
export function trimMirror(text: string, limit = MIRROR_LIMIT_BYTES): string {
|
||||
const lines = text.split('\n').filter((line) => line.length > 0);
|
||||
const size = () => byteSize(lines);
|
||||
|
||||
while (lines.length > 0 && size() > limit) {
|
||||
const body = lines.findIndex((line) => !isVersionHeader(line));
|
||||
|
||||
if (body >= 0) {
|
||||
lines.splice(body, 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lines.length <= 1) {
|
||||
break;
|
||||
}
|
||||
|
||||
lines.shift();
|
||||
}
|
||||
|
||||
if (lines.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
|
||||
export function appendEvents(
|
||||
mirror: string,
|
||||
version: string,
|
||||
events: readonly string[],
|
||||
limit = MIRROR_LIMIT_BYTES,
|
||||
): string {
|
||||
const fresh = events.map((line) => line.trim()).filter((line) => line.length > 0);
|
||||
|
||||
if (fresh.length === 0) {
|
||||
return mirror;
|
||||
}
|
||||
|
||||
const header = `v${version}`;
|
||||
const lines = mirror.split('\n').filter((line) => line.length > 0);
|
||||
let lastHeader = '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (isVersionHeader(line)) {
|
||||
lastHeader = line;
|
||||
}
|
||||
}
|
||||
|
||||
const next = [...lines];
|
||||
|
||||
if (lastHeader !== header) {
|
||||
next.push(header);
|
||||
}
|
||||
|
||||
next.push(...fresh);
|
||||
return trimMirror(`${next.join('\n')}\n`, limit);
|
||||
}
|
||||
|
||||
export function tempStagePath(
|
||||
platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): string {
|
||||
if (platform === 'win32') {
|
||||
const base = env.TMP || env.TEMP || os.tmpdir();
|
||||
return path.join(base, STAGE_FILE_NAME);
|
||||
}
|
||||
|
||||
const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
|
||||
return `/tmp/sl-${uid}/${STAGE_FILE_NAME}`;
|
||||
}
|
||||
|
||||
export function errorCode(error: unknown): string {
|
||||
if (error && typeof error === 'object' && 'code' in error) {
|
||||
const code = (error as { code?: unknown }).code;
|
||||
|
||||
if (typeof code === 'string' && code) {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
return 'ERR';
|
||||
}
|
||||
|
||||
export interface StageSyncOptions {
|
||||
version: string;
|
||||
dataDir: string;
|
||||
tempPath: string;
|
||||
log?: Logger;
|
||||
intervalMs?: number;
|
||||
}
|
||||
|
||||
interface IngestResult {
|
||||
mirror: string;
|
||||
offset: number;
|
||||
lines: string[];
|
||||
missing: boolean;
|
||||
errorCode?: string;
|
||||
}
|
||||
|
||||
export function ingestTemp(args: {
|
||||
tempText: string;
|
||||
offset: number;
|
||||
mirror: string;
|
||||
version: string;
|
||||
missing?: boolean;
|
||||
errorCode?: string;
|
||||
}): IngestResult {
|
||||
if (args.missing) {
|
||||
return { mirror: args.mirror, offset: args.offset, lines: [], missing: true };
|
||||
}
|
||||
|
||||
if (args.errorCode) {
|
||||
return {
|
||||
mirror: args.mirror,
|
||||
offset: args.offset,
|
||||
lines: [],
|
||||
missing: false,
|
||||
errorCode: args.errorCode,
|
||||
};
|
||||
}
|
||||
|
||||
const start = args.offset > args.tempText.length ? 0 : args.offset;
|
||||
const chunk = args.tempText.slice(start);
|
||||
const newline = chunk.lastIndexOf('\n');
|
||||
|
||||
if (newline < 0) {
|
||||
return { mirror: args.mirror, offset: start, lines: [], missing: false };
|
||||
}
|
||||
|
||||
const complete = chunk.slice(0, newline + 1);
|
||||
const lines = complete
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
return {
|
||||
mirror: appendEvents(args.mirror, args.version, lines),
|
||||
offset: start + newline + 1,
|
||||
lines,
|
||||
missing: false,
|
||||
};
|
||||
}
|
||||
|
||||
function readOffset(file: string): number {
|
||||
try {
|
||||
const raw = readFileSync(file, 'utf8').trim();
|
||||
const value = Number(raw);
|
||||
return Number.isSafeInteger(value) && value >= 0 ? value : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function readTemp(file: string): { text: string; missing: boolean; errorCode?: string } {
|
||||
let fd: number | undefined;
|
||||
|
||||
try {
|
||||
fd = openSync(file, 'r');
|
||||
const info = fstatSync(fd);
|
||||
const size = info.size;
|
||||
|
||||
if (size > 8 * 1024 * 1024) {
|
||||
return { text: '', missing: false, errorCode: 'E2BIG' };
|
||||
}
|
||||
|
||||
const buf = Buffer.alloc(size);
|
||||
let got = 0;
|
||||
|
||||
while (got < size) {
|
||||
const n = readSync(fd, buf, got, size - got, got);
|
||||
|
||||
if (n <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
got += n;
|
||||
}
|
||||
|
||||
return { text: buf.subarray(0, got).toString('utf8'), missing: false };
|
||||
} catch (error) {
|
||||
const code = errorCode(error);
|
||||
|
||||
if (code === 'ENOENT') {
|
||||
return { text: '', missing: true };
|
||||
}
|
||||
|
||||
return { text: '', missing: false, errorCode: code };
|
||||
} finally {
|
||||
if (fd !== undefined) {
|
||||
closeSync(fd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function startNativeStageSync(options: StageSyncOptions): { stop: () => void } {
|
||||
const log = options.log ?? createLogger('native');
|
||||
const mirrorPath = path.join(options.dataDir, STAGE_FILE_NAME);
|
||||
const offsetPath = path.join(options.dataDir, 's7.off');
|
||||
let offset = readOffset(offsetPath);
|
||||
let failed = false;
|
||||
let stopped = false;
|
||||
|
||||
const tick = () => {
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
|
||||
let tempSize = 0;
|
||||
|
||||
try {
|
||||
tempSize = statSync(options.tempPath).size;
|
||||
} catch (error) {
|
||||
const code = errorCode(error);
|
||||
|
||||
if (code === 'ENOENT') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!failed) {
|
||||
failed = true;
|
||||
log.error('sync failed %s', code);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (tempSize < offset) {
|
||||
offset = 0;
|
||||
}
|
||||
|
||||
const temp = readTemp(options.tempPath);
|
||||
|
||||
if (temp.missing) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (temp.errorCode) {
|
||||
if (!failed) {
|
||||
failed = true;
|
||||
log.error('sync failed %s', temp.errorCode);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
let mirror = '';
|
||||
|
||||
try {
|
||||
mirror = readFileSync(mirrorPath, 'utf8');
|
||||
} catch (error) {
|
||||
if (errorCode(error) !== 'ENOENT') {
|
||||
if (!failed) {
|
||||
failed = true;
|
||||
log.error('sync failed %s', errorCode(error));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const ingested = ingestTemp({
|
||||
tempText: temp.text,
|
||||
offset,
|
||||
mirror,
|
||||
version: options.version,
|
||||
});
|
||||
|
||||
if (ingested.lines.length === 0 && ingested.offset === offset) {
|
||||
failed = false;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
mkdirSync(options.dataDir, { recursive: true });
|
||||
writeFileSync(mirrorPath, ingested.mirror);
|
||||
writeFileSync(offsetPath, `${ingested.offset}\n`);
|
||||
offset = ingested.offset;
|
||||
failed = false;
|
||||
} catch (error) {
|
||||
if (!failed) {
|
||||
failed = true;
|
||||
log.error('sync failed %s', errorCode(error));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
for (const line of ingested.lines) {
|
||||
const text = publicLine(options.version, line);
|
||||
|
||||
if (lineSeverity(line) === 'error') {
|
||||
log.error('%s', text);
|
||||
} else {
|
||||
log.info('%s', text);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
tick();
|
||||
const timer = setInterval(tick, options.intervalMs ?? 500);
|
||||
timer.unref();
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -2,10 +2,12 @@ import { APP_VERSION } from '@snowluma/common/version';
|
||||
import { compareVersions, parseVersion } from '@snowluma/common/semver';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { createSingleFlightCache } from '@snowluma/common/single-flight-cache';
|
||||
import type { UpdateSourceConfig } from '@snowluma/common/update-source';
|
||||
import { fetchRelease } from './release';
|
||||
import { readUpdateSource } from './sources';
|
||||
|
||||
const log = createLogger('Update');
|
||||
|
||||
const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest';
|
||||
const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6h — comfortably under the rate limit
|
||||
const FETCH_TIMEOUT_MS = 8_000;
|
||||
const NOTES_MAX = 4_000; // cap the release-body we hand back to the client
|
||||
@@ -29,13 +31,6 @@ export interface UpdateCheckResult {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface GithubRelease {
|
||||
tag_name?: string;
|
||||
html_url?: string;
|
||||
body?: string;
|
||||
published_at?: string;
|
||||
}
|
||||
|
||||
function isEnabled(): boolean {
|
||||
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
|
||||
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
|
||||
@@ -47,8 +42,10 @@ function isEnabled(): boolean {
|
||||
const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
|
||||
ttlMs: CACHE_TTL_MS,
|
||||
shouldCache: (r) => !r.error,
|
||||
load: async (current) => {
|
||||
const result = await fetchLatest(current);
|
||||
load: async (key) => {
|
||||
// This key is constructed below from our version and normalized settings.
|
||||
const [current, source] = JSON.parse(key) as [string, UpdateSourceConfig];
|
||||
const result = await fetchLatest(current, source);
|
||||
|
||||
if (result.error) {
|
||||
log.debug('update check failed: %s', result.error);
|
||||
@@ -60,7 +57,10 @@ const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
|
||||
},
|
||||
});
|
||||
|
||||
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
||||
async function fetchLatest(
|
||||
current: string,
|
||||
source: UpdateSourceConfig,
|
||||
): Promise<UpdateCheckResult> {
|
||||
const base: UpdateCheckResult = {
|
||||
current,
|
||||
latest: null,
|
||||
@@ -74,21 +74,19 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
||||
try {
|
||||
// `/releases/latest` already excludes drafts and prereleases, so this is
|
||||
// stable-channel by construction.
|
||||
const res = await fetch(LATEST_RELEASE_URL, {
|
||||
headers: {
|
||||
Accept: 'application/vnd.github+json',
|
||||
'User-Agent': `SnowLuma/${current}`,
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
},
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
const { data: rel } = await fetchRelease(
|
||||
undefined,
|
||||
source,
|
||||
`SnowLuma/${current}`,
|
||||
FETCH_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
return { ...base, error: `github ${res.status}` };
|
||||
if (!rel || typeof rel !== 'object' || Array.isArray(rel)) {
|
||||
return { ...base, error: 'invalid release info' };
|
||||
}
|
||||
|
||||
const rel = (await res.json()) as GithubRelease;
|
||||
const tag = typeof rel.tag_name === 'string' ? rel.tag_name.trim() : '';
|
||||
const tag =
|
||||
'tag_name' in rel && typeof rel.tag_name === 'string' ? rel.tag_name.trim() : '';
|
||||
|
||||
if (!tag) {
|
||||
return { ...base, error: 'no tag' };
|
||||
@@ -104,9 +102,15 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
||||
current,
|
||||
latest,
|
||||
hasUpdate: compareVersions(latest, current) > 0,
|
||||
htmlUrl: rel.html_url ?? null,
|
||||
notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null,
|
||||
publishedAt: rel.published_at ?? null,
|
||||
htmlUrl: 'html_url' in rel && typeof rel.html_url === 'string' ? rel.html_url : null,
|
||||
notes:
|
||||
'body' in rel && typeof rel.body === 'string' && rel.body
|
||||
? rel.body.slice(0, NOTES_MAX)
|
||||
: null,
|
||||
publishedAt:
|
||||
'published_at' in rel && typeof rel.published_at === 'string'
|
||||
? rel.published_at
|
||||
: null,
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
} catch (e) {
|
||||
@@ -120,14 +124,26 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
||||
* failures come back as a result with `error` set and `hasUpdate: false`, and
|
||||
* are not cached so the next check retries.
|
||||
*/
|
||||
export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
|
||||
export async function getUpdateInfo(
|
||||
force = false,
|
||||
source?: UpdateSourceConfig,
|
||||
): Promise<UpdateCheckResult> {
|
||||
const current = APP_VERSION;
|
||||
|
||||
if (!isEnabled()) {
|
||||
return { ...emptyResult(current), error: 'disabled' };
|
||||
}
|
||||
|
||||
return updateCache.get(current, { force });
|
||||
try {
|
||||
return await updateCache.get(JSON.stringify([current, source ?? readUpdateSource()]), {
|
||||
force,
|
||||
});
|
||||
} catch (error) {
|
||||
return {
|
||||
...emptyResult(current),
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function emptyResult(current: string): UpdateCheckResult {
|
||||
|
||||
@@ -1,43 +1,30 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createWriteStream } from 'node:fs';
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import { mkdir, readFile, writeFile, rm } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { Readable, Transform } from 'node:stream';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { unzipSync } from 'fflate';
|
||||
import { x as extractTar } from 'tar';
|
||||
import { isRuntimeEntry, readManifest } from './files';
|
||||
import { assetName, fetchRelease } from './release';
|
||||
export { assetName } from './release';
|
||||
import { readUpdateSource, sourceUrls } from './sources';
|
||||
import type { UpdateSourceConfig } from '@snowluma/common/update-source';
|
||||
|
||||
interface ReleaseAsset {
|
||||
url: string;
|
||||
size: number;
|
||||
size: number | null;
|
||||
digest: string;
|
||||
}
|
||||
|
||||
export function assetName(version: string, target: string): string {
|
||||
const platform = target.replace('win32', 'win');
|
||||
return `SnowLuma-v${version}-${platform}-lite.${target.startsWith('win32') ? 'zip' : 'tar.gz'}`;
|
||||
}
|
||||
|
||||
async function releaseAsset(version: string, target: string): Promise<ReleaseAsset> {
|
||||
async function releaseAsset(
|
||||
version: string,
|
||||
target: string,
|
||||
source: UpdateSourceConfig,
|
||||
): Promise<ReleaseAsset> {
|
||||
const name = assetName(version, target);
|
||||
const response = await fetch(
|
||||
`https://api.github.com/repos/SnowLuma/SnowLuma/releases/tags/v${version}`,
|
||||
{
|
||||
headers: {
|
||||
Accept: 'application/vnd.github+json',
|
||||
'User-Agent': 'SnowLuma',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
},
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`获取更新失败: GitHub ${response.status}`);
|
||||
}
|
||||
|
||||
const release: unknown = await response.json();
|
||||
const { data: release, fromPage } = await fetchRelease(version, source);
|
||||
|
||||
if (
|
||||
!release ||
|
||||
@@ -58,9 +45,10 @@ async function releaseAsset(version: string, target: string): Promise<ReleaseAss
|
||||
!asset ||
|
||||
typeof asset !== 'object' ||
|
||||
!('size' in asset) ||
|
||||
typeof asset.size !== 'number' ||
|
||||
!Number.isSafeInteger(asset.size) ||
|
||||
asset.size <= 0 ||
|
||||
!(
|
||||
(fromPage && asset.size === null) ||
|
||||
(typeof asset.size === 'number' && Number.isSafeInteger(asset.size) && asset.size > 0)
|
||||
) ||
|
||||
!('digest' in asset) ||
|
||||
typeof asset.digest !== 'string' ||
|
||||
!/^sha256:[a-f0-9]{64}$/.test(asset.digest)
|
||||
@@ -94,37 +82,98 @@ export async function downloadUpdate(
|
||||
directory: string,
|
||||
version: string,
|
||||
target: string,
|
||||
source = readUpdateSource(),
|
||||
): Promise<void> {
|
||||
const asset = await releaseAsset(version, target);
|
||||
const response = await fetch(asset.url, { signal: AbortSignal.timeout(10 * 60_000) });
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
throw new Error(`下载更新失败: HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const asset = await releaseAsset(version, target, source);
|
||||
const archive = path.join(directory, 'archive');
|
||||
const hash = createHash('sha256');
|
||||
let received = 0;
|
||||
await pipeline(
|
||||
Readable.fromWeb(response.body),
|
||||
new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
received += chunk.length;
|
||||
const urls = sourceUrls(asset.url, source);
|
||||
const failures: string[] = [];
|
||||
|
||||
if (received > asset.size) {
|
||||
callback(new Error('更新包大小不匹配'));
|
||||
return;
|
||||
}
|
||||
for (const [index, url] of urls.entries()) {
|
||||
let created = false;
|
||||
|
||||
hash.update(chunk);
|
||||
callback(null, chunk);
|
||||
},
|
||||
}),
|
||||
createWriteStream(archive, { flags: 'wx' }),
|
||||
);
|
||||
try {
|
||||
const headersTimeout = new AbortController();
|
||||
const timer = setTimeout(() => headersTimeout.abort(), 8_000);
|
||||
let response: Response;
|
||||
|
||||
if (received !== asset.size || `sha256:${hash.digest('hex')}` !== asset.digest) {
|
||||
throw new Error('更新包校验失败');
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
signal: AbortSignal.any([
|
||||
headersTimeout.signal,
|
||||
AbortSignal.timeout(10 * 60_000),
|
||||
]),
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
await response.body?.cancel();
|
||||
throw new Error(`下载更新失败: HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
if (/text\/html/i.test(response.headers.get('content-type') ?? '')) {
|
||||
await response.body.cancel();
|
||||
throw new Error('下载源返回了 HTML 页面,而不是更新包');
|
||||
}
|
||||
|
||||
const hash = createHash('sha256');
|
||||
const length = response.headers.get('content-length');
|
||||
const size =
|
||||
asset.size ?? (length === null ? null : /^\d+$/.test(length) ? Number(length) : 0);
|
||||
|
||||
if (size !== null && (!Number.isSafeInteger(size) || size <= 0)) {
|
||||
await response.body.cancel();
|
||||
throw new Error('下载源返回了无效的更新包大小');
|
||||
}
|
||||
|
||||
let received = 0;
|
||||
const output = createWriteStream(archive, { flags: 'wx' });
|
||||
output.once('open', () => {
|
||||
created = true;
|
||||
});
|
||||
await pipeline(
|
||||
Readable.fromWeb(response.body),
|
||||
new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
received += chunk.length;
|
||||
|
||||
if (received > (size ?? 256 * 1024 * 1024)) {
|
||||
callback(new Error('更新包大小不匹配'));
|
||||
return;
|
||||
}
|
||||
|
||||
hash.update(chunk);
|
||||
callback(null, chunk);
|
||||
},
|
||||
}),
|
||||
output,
|
||||
);
|
||||
|
||||
if (
|
||||
(size !== null && received !== size) ||
|
||||
`sha256:${hash.digest('hex')}` !== asset.digest
|
||||
) {
|
||||
throw new Error('更新包校验失败');
|
||||
}
|
||||
|
||||
break;
|
||||
} catch (error) {
|
||||
if (error && typeof error === 'object' && 'code' in error && error.code === 'EEXIST') {
|
||||
throw error;
|
||||
}
|
||||
|
||||
failures.push(error instanceof Error ? error.message : String(error));
|
||||
|
||||
if (index === urls.length - 1) {
|
||||
throw new Error([...new Set(failures)].join(';'));
|
||||
}
|
||||
|
||||
if (created) {
|
||||
await rm(archive);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const payload = path.join(directory, 'payload');
|
||||
|
||||
196
packages/core/src/update/release.ts
Normal file
196
packages/core/src/update/release.ts
Normal file
@@ -0,0 +1,196 @@
|
||||
import { parseVersion } from '@snowluma/common/semver';
|
||||
import type { UpdateSourceConfig } from '@snowluma/common/update-source';
|
||||
import { RELEASE_ROOT, sourceUrls } from './sources';
|
||||
|
||||
export function assetName(version: string, target: string): string {
|
||||
const platform = target.replace('win32', 'win');
|
||||
return `SnowLuma-v${version}-${platform}-lite.${target.startsWith('win32') ? 'zip' : 'tar.gz'}`;
|
||||
}
|
||||
|
||||
async function readText(response: Response, limit: number): Promise<string> {
|
||||
if (!response.body) {
|
||||
throw new Error('发布信息为空');
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let size = 0;
|
||||
|
||||
try {
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read();
|
||||
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
size += value.length;
|
||||
|
||||
if (size > limit) {
|
||||
await reader.cancel();
|
||||
throw new Error('发布信息过大');
|
||||
}
|
||||
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
return Buffer.concat(chunks).toString('utf8');
|
||||
}
|
||||
|
||||
function attribute(tag: string, name: string): string | undefined {
|
||||
return new RegExp(`\\s${name}\\s*=\\s*(["'])(.*?)\\1`, 'i')
|
||||
.exec(tag)?.[2]
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll(''', "'")
|
||||
.replaceAll('"', '"');
|
||||
}
|
||||
|
||||
export function parseLatestReleasePage(html: string) {
|
||||
const meta = html
|
||||
.match(/<meta\b[^>]*>/gi)
|
||||
?.find((tag) => attribute(tag, 'property') === 'og:url');
|
||||
const canonical = meta && attribute(meta, 'content');
|
||||
|
||||
if (!canonical) {
|
||||
throw new Error('发布页面缺少版本信息');
|
||||
}
|
||||
|
||||
const url = new URL(canonical, 'https://github.com');
|
||||
const tag = /^\/SnowLuma\/SnowLuma\/releases\/tag\/([^/]+)$/.exec(url.pathname)?.[1];
|
||||
const decoded = tag && decodeURIComponent(tag);
|
||||
const version = decoded?.startsWith('v') ? decoded.slice(1) : undefined;
|
||||
const parsed = parseVersion(version);
|
||||
|
||||
if (url.origin !== 'https://github.com' || !parsed || parsed.prerelease.length) {
|
||||
throw new Error('发布页面不是 SnowLuma 正式版本');
|
||||
}
|
||||
|
||||
return { tag_name: `v${parsed.raw}`, html_url: `${RELEASE_ROOT}/tag/v${parsed.raw}` };
|
||||
}
|
||||
|
||||
/** Match the digest in the same asset row; never borrow a neighbouring asset's hash. */
|
||||
export function parseReleaseAssetsPage(html: string, version: string) {
|
||||
const assets: { name: string; size: null; digest: string }[] = [];
|
||||
const expected = ['win32-x64', 'linux-x64', 'linux-arm64'].map((target) =>
|
||||
assetName(version, target),
|
||||
);
|
||||
|
||||
for (const row of html.match(/<li\b[^>]*>[\s\S]*?<\/li>/gi) ?? []) {
|
||||
const links = row.match(/<a\b[^>]*>/gi) ?? [];
|
||||
const name = expected.find((candidate) =>
|
||||
links.some((link) => {
|
||||
const href = attribute(link, 'href');
|
||||
return (
|
||||
href === `/SnowLuma/SnowLuma/releases/download/v${version}/${candidate}` ||
|
||||
href === `${RELEASE_ROOT}/download/v${version}/${candidate}`
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const digests = (row.match(/<clipboard-copy\b[^>]*>/gi) ?? [])
|
||||
.map((tag) => attribute(tag, 'value'))
|
||||
.filter((value): value is string =>
|
||||
Boolean(value && /^sha256:[a-f0-9]{64}$/.test(value)),
|
||||
);
|
||||
|
||||
if (digests.length !== 1 || assets.some((asset) => asset.name === name)) {
|
||||
throw new Error('发布页面缺少唯一的文件校验信息');
|
||||
}
|
||||
|
||||
// GitHub renders a rounded size in HTML. Verify the exact digest even
|
||||
// when a proxy streams the asset without Content-Length.
|
||||
assets.push({ name, size: null, digest: digests[0]! });
|
||||
}
|
||||
|
||||
if (!assets.length) {
|
||||
throw new Error('发布页面没有可验证的更新包');
|
||||
}
|
||||
|
||||
return { tag_name: `v${version}`, assets };
|
||||
}
|
||||
|
||||
export interface ReleaseResult {
|
||||
data: unknown;
|
||||
fromPage: boolean;
|
||||
}
|
||||
|
||||
export async function fetchRelease(
|
||||
version: string | undefined,
|
||||
source: UpdateSourceConfig,
|
||||
userAgent = 'SnowLuma',
|
||||
timeoutMs = 8_000,
|
||||
): Promise<ReleaseResult> {
|
||||
const apiUrl = `https://api.github.com/repos/SnowLuma/SnowLuma/releases/${version ? `tags/v${version}` : 'latest'}`;
|
||||
let primaryError: unknown;
|
||||
|
||||
try {
|
||||
const response = await fetch(apiUrl, {
|
||||
headers: {
|
||||
Accept: 'application/vnd.github+json',
|
||||
'User-Agent': userAgent,
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
},
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel();
|
||||
throw new Error(`GitHub ${response.status}`);
|
||||
}
|
||||
|
||||
return {
|
||||
data: JSON.parse(await readText(response, 256 * 1024)) as unknown,
|
||||
fromPage: false,
|
||||
};
|
||||
} catch (error) {
|
||||
primaryError = error;
|
||||
}
|
||||
|
||||
const originalUrl = version
|
||||
? `${RELEASE_ROOT}/expanded_assets/v${version}`
|
||||
: `${RELEASE_ROOT}/latest`;
|
||||
const controller = new AbortController();
|
||||
|
||||
try {
|
||||
// Only a parsed release page can win. Fast errors and HTML interstitials
|
||||
// cannot cancel a slower working source.
|
||||
// Download proxies often only support assets. Always retain GitHub's
|
||||
// release page for version/digest lookup, even with a pinned download mirror.
|
||||
const urls = [...new Set([originalUrl, ...sourceUrls(originalUrl, source)])];
|
||||
const data = await Promise.any(
|
||||
urls.map(async (url) => {
|
||||
const response = await fetch(url, {
|
||||
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel();
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const html = await readText(response, 1024 * 1024);
|
||||
return version
|
||||
? parseReleaseAssetsPage(html, version)
|
||||
: parseLatestReleasePage(html);
|
||||
}),
|
||||
);
|
||||
return { data, fromPage: true };
|
||||
} catch (error) {
|
||||
const failures = error instanceof AggregateError ? error.errors : [error];
|
||||
const details = [primaryError, ...failures]
|
||||
.filter(Boolean)
|
||||
.map((failure: unknown) =>
|
||||
failure instanceof Error ? failure.message : String(failure),
|
||||
);
|
||||
throw new Error(`${[...new Set(details)].join(';')};请在更新来源中检测或指定可用镜像`);
|
||||
} finally {
|
||||
controller.abort();
|
||||
}
|
||||
}
|
||||
125
packages/core/src/update/sources.ts
Normal file
125
packages/core/src/update/sources.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
import { APP_VERSION } from '@snowluma/common/version';
|
||||
import { readRuntimeConfig, updateRuntimeConfig } from '@snowluma/common/runtime';
|
||||
import {
|
||||
normalizeUpdateSourceConfig,
|
||||
type UpdateSourceConfig,
|
||||
} from '@snowluma/common/update-source';
|
||||
|
||||
export const RELEASE_ROOT = 'https://github.com/SnowLuma/SnowLuma/releases';
|
||||
export const DEFAULT_UPDATE_SOURCE: UpdateSourceConfig = {
|
||||
mode: 'auto',
|
||||
mirror: '',
|
||||
mirrors: [
|
||||
'https://ghfast.top',
|
||||
'https://ghproxy.net',
|
||||
'https://gh-proxy.com',
|
||||
'https://github.chenc.dev',
|
||||
'https://fastgit.cc',
|
||||
'https://gh.noki.icu',
|
||||
'https://cors.isteed.cc',
|
||||
'https://gh-proxy.org',
|
||||
'https://githubproxy.gohj99.site',
|
||||
'https://github.xxlab.tech',
|
||||
],
|
||||
};
|
||||
|
||||
export function readUpdateSource(): UpdateSourceConfig {
|
||||
return normalizeUpdateSourceConfig(readRuntimeConfig().updateSource ?? DEFAULT_UPDATE_SOURCE);
|
||||
}
|
||||
|
||||
export function saveUpdateSource(value: unknown): UpdateSourceConfig {
|
||||
const config = normalizeUpdateSourceConfig(value);
|
||||
updateRuntimeConfig({ updateSource: config });
|
||||
return config;
|
||||
}
|
||||
|
||||
export function sourceUrls(url: string, config: UpdateSourceConfig): string[] {
|
||||
if (config.mode === 'direct') {
|
||||
return [url];
|
||||
}
|
||||
|
||||
if (config.mode === 'mirror') {
|
||||
return [`${config.mirror}/${url}`];
|
||||
}
|
||||
|
||||
return [url, ...config.mirrors.map((mirror) => `${mirror}/${url}`)];
|
||||
}
|
||||
|
||||
export interface MirrorProbeResult {
|
||||
mirror: string;
|
||||
available: boolean;
|
||||
latencyMs: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export async function testUpdateSources(value: unknown): Promise<MirrorProbeResult[]> {
|
||||
const config = normalizeUpdateSourceConfig(value);
|
||||
const mirrors = [
|
||||
...new Set(['', ...config.mirrors, ...(config.mirror ? [config.mirror] : [])]),
|
||||
];
|
||||
const target = process.platform === 'win32' ? 'win-x64' : `linux-${process.arch}`;
|
||||
const extension = process.platform === 'win32' ? 'zip' : 'tar.gz';
|
||||
const probeUrl = `${RELEASE_ROOT}/download/v${APP_VERSION}/SnowLuma-v${APP_VERSION}-${target}-lite.${extension}`;
|
||||
const results = await Promise.all(
|
||||
mirrors.map(async (mirror): Promise<MirrorProbeResult> => {
|
||||
const start = performance.now();
|
||||
|
||||
try {
|
||||
const response = await fetch(mirror ? `${mirror}/${probeUrl}` : probeUrl, {
|
||||
headers: { Range: 'bytes=0-3' },
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
});
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
await response.body?.cancel();
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
if (/text\/html/i.test(response.headers.get('content-type') ?? '')) {
|
||||
await response.body.cancel();
|
||||
throw new Error('返回了 HTML 页面,而不是更新包');
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const prefix: number[] = [];
|
||||
|
||||
try {
|
||||
while (prefix.length < 4) {
|
||||
const { value, done } = await reader.read();
|
||||
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
prefix.push(...value.subarray(0, 4 - prefix.length));
|
||||
}
|
||||
} finally {
|
||||
await reader.cancel();
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
const signature = extension === 'zip' ? [0x50, 0x4b, 0x03, 0x04] : [0x1f, 0x8b];
|
||||
|
||||
if (!signature.every((byte, index) => prefix[index] === byte)) {
|
||||
throw new Error('返回内容不是有效的更新包');
|
||||
}
|
||||
|
||||
return {
|
||||
mirror,
|
||||
available: true,
|
||||
latencyMs: Math.round(performance.now() - start),
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
mirror,
|
||||
available: false,
|
||||
latencyMs: Math.round(performance.now() - start),
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
return results.sort(
|
||||
(a, b) => Number(b.available) - Number(a.available) || a.latencyMs - b.latencyMs,
|
||||
);
|
||||
}
|
||||
@@ -527,6 +527,10 @@ function prepareGlobalSettingsJson(
|
||||
const normalized = normalizeGlobalSettings(raw);
|
||||
const canonical: Record<string, unknown> = { rkey: normalized.rkey };
|
||||
|
||||
if (isPlainObject(raw) && Object.prototype.hasOwnProperty.call(raw, 'videoUploadConcurrency')) {
|
||||
canonical.videoUploadConcurrency = normalized.videoUploadConcurrency;
|
||||
}
|
||||
|
||||
// Missing is the existing one-shot migration sentinel: startup scans legacy
|
||||
// onebot*.json only until snowluma.json first carries this key.
|
||||
if (isPlainObject(raw) && Object.prototype.hasOwnProperty.call(raw, 'musicSignUrl')) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { APP_VERSION } from '@snowluma/common/version';
|
||||
import { serve } from '@hono/node-server';
|
||||
import { serveStatic } from '@hono/node-server/serve-static';
|
||||
import { resolveWebuiTarget } from '@snowluma/common/webui-target';
|
||||
import { registerStaticFrontend } from './static-frontend';
|
||||
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
|
||||
import { getRuntimeIntegrity, hasLowProcessIntegrity } from '@snowluma/bridge';
|
||||
import {
|
||||
@@ -636,6 +637,15 @@ export async function initWebUI(
|
||||
updateRoot?: string;
|
||||
} = {},
|
||||
): Promise<{ port: number; stop: () => Promise<void> }> {
|
||||
const webuiTarget = resolveWebuiTarget(process.env.SNOWLUMA_WEBUI_TARGET);
|
||||
|
||||
if (webuiTarget) {
|
||||
log.info(
|
||||
'presentation target enabled: %s (runtime override; saved appearance is preserved)',
|
||||
webuiTarget,
|
||||
);
|
||||
}
|
||||
|
||||
const host = listener.host || '127.0.0.1';
|
||||
const tlsEnabled = listener.tlsEnabled === true;
|
||||
const bootCheck = checkListenerExposure({
|
||||
@@ -2163,6 +2173,11 @@ export async function initWebUI(
|
||||
'save global config failed: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
|
||||
if (err instanceof RangeError) {
|
||||
return c.json({ success: false, message: err.message }, 400);
|
||||
}
|
||||
|
||||
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
|
||||
}
|
||||
});
|
||||
@@ -2267,29 +2282,7 @@ export async function initWebUI(
|
||||
// Build path is relative to the bundled / dev __dirname. SPA fallback to
|
||||
// index.html so client-side routes (if any) keep working.
|
||||
const staticRoot = path.resolve(__dirname, 'client');
|
||||
app.use('/*', serveStatic({ root: staticRoot }));
|
||||
|
||||
const indexHtmlPath = path.join(staticRoot, 'index.html');
|
||||
app.get('*', (c) => {
|
||||
// SPA fallback: only for navigations that didn't hit a static asset.
|
||||
if (
|
||||
c.req.path.startsWith('/api/') ||
|
||||
c.req.path.startsWith('/avatar/') ||
|
||||
c.req.path.startsWith('/ui-asset/')
|
||||
) {
|
||||
return c.text('not found', 404);
|
||||
}
|
||||
|
||||
if (existsSync(indexHtmlPath)) {
|
||||
const html = readFileSync(indexHtmlPath, 'utf8');
|
||||
return c.html(html);
|
||||
}
|
||||
|
||||
return c.text(
|
||||
'WebUI client bundle not found. Run `pnpm --filter webui build` (or use the dev server on :5178).',
|
||||
404,
|
||||
);
|
||||
});
|
||||
registerStaticFrontend(app, staticRoot, webuiTarget);
|
||||
|
||||
const finalPort = await findAvailablePort(desiredPort, { host });
|
||||
|
||||
|
||||
34
packages/core/src/webui/static-frontend.ts
Normal file
34
packages/core/src/webui/static-frontend.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Hono, Context } from 'hono';
|
||||
import { serveStatic } from '@hono/node-server/serve-static';
|
||||
import { injectWebuiTarget, type WebuiTarget } from '@snowluma/common/webui-target';
|
||||
|
||||
/** All document entry paths share runtime injection, including direct index.html requests. */
|
||||
export function registerStaticFrontend(app: Hono, root: string, target: WebuiTarget | null): void {
|
||||
const indexPath = path.join(root, 'index.html');
|
||||
|
||||
const document = (c: Context) => {
|
||||
if (!existsSync(indexPath)) {
|
||||
return c.text(
|
||||
'WebUI client bundle not found. Run `pnpm --filter webui build` (or use the dev server on :5178).',
|
||||
404,
|
||||
);
|
||||
}
|
||||
|
||||
// A packaged frontend can be reused with a different deployment target on restart.
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.html(injectWebuiTarget(readFileSync(indexPath, 'utf8'), target));
|
||||
};
|
||||
|
||||
app.get('/', document);
|
||||
app.get('/index.html', document);
|
||||
app.use('/*', serveStatic({ root }));
|
||||
app.get('*', (c) => {
|
||||
if (['/api/', '/avatar/', '/ui-asset/'].some((prefix) => c.req.path.startsWith(prefix))) {
|
||||
return c.text('not found', 404);
|
||||
}
|
||||
|
||||
return document(c);
|
||||
});
|
||||
}
|
||||
@@ -44,7 +44,7 @@ export type SidebarStyle = 'follow' | 'panel' | 'accent';
|
||||
export type BackgroundType = 'none' | 'solid' | 'gradient' | 'image';
|
||||
export type Density = 'cozy' | 'compact';
|
||||
export type TimeFormat = '12h' | '24h';
|
||||
/** Full color scheme. 'default' keeps the sky theme (driven by `mode`); the
|
||||
/** Full color scheme. 'default' keeps the lavender theme (driven by `mode`); the
|
||||
* Catppuccin flavors are complete palettes that also fix light/dark. */
|
||||
export type Palette =
|
||||
| 'default'
|
||||
@@ -85,7 +85,7 @@ export interface UiAppearance {
|
||||
accentCustom: string;
|
||||
accentScope: AccentScope;
|
||||
darkIntensity: DarkIntensity;
|
||||
/** Full color scheme; 'default' = the built-in sky theme. */
|
||||
/** Full color scheme; 'default' = the built-in lavender theme. */
|
||||
palette: Palette;
|
||||
sidebarStyle: SidebarStyle;
|
||||
background: UiBackground;
|
||||
@@ -203,12 +203,12 @@ export interface UiConfig {
|
||||
}
|
||||
|
||||
// ─── Defaults ────────────────────────────────────────────────────────────
|
||||
// Mirror the pre-existing ThemeContext defaults so an upgrade is a no-op
|
||||
// visually until the operator changes something.
|
||||
// Keep these defaults aligned with ThemeContext. Saved appearance choices
|
||||
// are normalized independently and remain the operator's preference.
|
||||
|
||||
const DEFAULT_BACKGROUND: UiBackground = {
|
||||
type: 'none',
|
||||
color: '#0ea5e9',
|
||||
color: '#b99ae6',
|
||||
gradient: 'none',
|
||||
imageOpacity: 0.15,
|
||||
imageBlur: 0,
|
||||
@@ -220,8 +220,8 @@ const DEFAULT_BACKGROUND: UiBackground = {
|
||||
const DEFAULT_APPEARANCE: UiAppearance = {
|
||||
mode: 'system',
|
||||
accentMode: 'preset',
|
||||
accentPreset: 'sky',
|
||||
accentCustom: '#38bdf8',
|
||||
accentPreset: 'lavender',
|
||||
accentCustom: '#8561bd',
|
||||
accentScope: 'global',
|
||||
darkIntensity: 'soft',
|
||||
palette: 'default',
|
||||
|
||||
@@ -1,10 +1,52 @@
|
||||
import { Hono } from 'hono';
|
||||
import type { HttpBindings } from '@hono/node-server';
|
||||
import type { UpdateService } from '../update/service';
|
||||
import { readUpdateSource, saveUpdateSource, testUpdateSources } from '../update/sources';
|
||||
import {
|
||||
normalizeUpdateSourceConfig,
|
||||
type UpdateSourceConfig,
|
||||
} from '@snowluma/common/update-source';
|
||||
|
||||
export function updateRoutes(service: UpdateService, restart: () => void) {
|
||||
const app = new Hono<{ Bindings: HttpBindings }>();
|
||||
app.get('/status', (c) => c.json(service.status()));
|
||||
app.get('/sources', (c) => {
|
||||
try {
|
||||
return c.json({ config: readUpdateSource() });
|
||||
} catch (error) {
|
||||
return c.json({ message: error instanceof Error ? error.message : String(error) }, 500);
|
||||
}
|
||||
});
|
||||
app.post('/sources', async (c) => {
|
||||
let config: UpdateSourceConfig;
|
||||
|
||||
try {
|
||||
config = normalizeUpdateSourceConfig(await c.req.json());
|
||||
} catch (error) {
|
||||
return c.json({ message: error instanceof Error ? error.message : String(error) }, 400);
|
||||
}
|
||||
|
||||
try {
|
||||
saveUpdateSource(config);
|
||||
return c.json({
|
||||
config,
|
||||
saved: true,
|
||||
applied: true,
|
||||
online: true,
|
||||
errors: [],
|
||||
message: '更新来源已保存',
|
||||
});
|
||||
} catch (error) {
|
||||
return c.json({ message: error instanceof Error ? error.message : String(error) }, 500);
|
||||
}
|
||||
});
|
||||
app.post('/sources/test', async (c) => {
|
||||
try {
|
||||
return c.json({ results: await testUpdateSources(await c.req.json()) });
|
||||
} catch (error) {
|
||||
return c.json({ message: error instanceof Error ? error.message : String(error) }, 400);
|
||||
}
|
||||
});
|
||||
app.post('/download', async (c) => {
|
||||
let body: unknown;
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { pb, pb_repeated, uint_32, uint_64 } from '@snowluma/proton';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { GroupMemberInfo } from '@snowluma/protocol/qq-info';
|
||||
import type {
|
||||
OidbBase,
|
||||
OidbEmpty,
|
||||
@@ -67,8 +68,8 @@ function friend(
|
||||
type: 1,
|
||||
layer1: {
|
||||
properties: [
|
||||
{ code: 20002, value: nickname },
|
||||
{ code: 103, value: remark },
|
||||
{ code: 20002, value: Buffer.from(nickname) },
|
||||
{ code: 103, value: Buffer.from(remark) },
|
||||
],
|
||||
},
|
||||
},
|
||||
@@ -397,7 +398,7 @@ describe('apis/contacts / group requests', () => {
|
||||
requests: [
|
||||
{
|
||||
sequence: 1_785_525_232_784_291n,
|
||||
eventType: 7,
|
||||
eventType: 1,
|
||||
state: 1,
|
||||
group: { groupUin: 1_095_186_374, groupName: 'group' },
|
||||
target: { uin: 1_234_567_890, name: 'requester' },
|
||||
@@ -439,7 +440,7 @@ describe('apis/contacts / group requests', () => {
|
||||
requests: [
|
||||
{
|
||||
sequence: 42n,
|
||||
eventType: 7,
|
||||
eventType: 1,
|
||||
state: 1,
|
||||
group: { groupUin: 999, groupName: 'group' },
|
||||
target: { uid: 'target_uid', name: 'requester' },
|
||||
@@ -462,6 +463,8 @@ describe('apis/contacts / group requests', () => {
|
||||
targetUin: 1_234_567_890,
|
||||
invitorUid: 'inviter_uid',
|
||||
operatorUid: 'operator_uid',
|
||||
notifyType: 7,
|
||||
eventType: 1,
|
||||
filtered: true,
|
||||
}),
|
||||
]);
|
||||
@@ -478,8 +481,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 +511,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 +538,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 },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -648,7 +653,9 @@ describe('apis/contacts / categorized friend roster', () => {
|
||||
|
||||
describe('apis/contacts / robot group-member classification', () => {
|
||||
it('loads QQ robot ranges once and marks every fetched member', async () => {
|
||||
const rememberGroupMembers = vi.fn();
|
||||
const rememberGroupMembers = vi.fn(
|
||||
(_groupId: number, members: GroupMemberInfo[]) => members,
|
||||
);
|
||||
const sendRawPacket = vi.fn(
|
||||
async (cmd: string, _data: Uint8Array): Promise<SendPacketResult> => {
|
||||
if (cmd === 'OidbSvcTrpcTcp.0x496_0') {
|
||||
@@ -731,7 +738,9 @@ describe('apis/contacts / robot group-member classification', () => {
|
||||
throw new Error(`unexpected command: ${cmd}`);
|
||||
},
|
||||
);
|
||||
const rememberGroupMembers = vi.fn();
|
||||
const rememberGroupMembers = vi.fn(
|
||||
(_groupId: number, members: GroupMemberInfo[]) => members,
|
||||
);
|
||||
const api = new ContactsApi({
|
||||
sendRawPacket,
|
||||
identity: { uin: '10001', rememberGroupMembers },
|
||||
@@ -754,12 +763,20 @@ describe('apis/contacts / invite-card pending application', () => {
|
||||
const api = new ContactsApi({ identity: { uin: '10001' } } as any);
|
||||
expect(api.getGroupInviteCardSequence(12345)).toBeUndefined();
|
||||
|
||||
api.rememberGroupInviteCardSequence(12345, 778899);
|
||||
api.rememberGroupInviteCardSequence(0, 1);
|
||||
api.rememberGroupInviteCardSequence(1, 0);
|
||||
expect(api.rememberGroupInviteCardSequence(12345, 778899)).toBe(true);
|
||||
expect(api.rememberGroupInviteCardSequence(12345, 778899)).toBe(false);
|
||||
|
||||
expect(api.getGroupInviteCardSequence(12345)).toBe(778899);
|
||||
expect(api.findGroupInviteCardGroupBySequence(778899)).toBe(12345);
|
||||
expect(api.findGroupInviteCardGroupBySequence(1)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('requires a group when different groups have the same card sequence', () => {
|
||||
const api = new ContactsApi({ identity: { uin: '10001' } } as any);
|
||||
api.rememberGroupInviteCardSequence(12345, 778899);
|
||||
api.rememberGroupInviteCardSequence(67890, 778899);
|
||||
|
||||
expect(() => api.findGroupInviteCardGroupBySequence(778899)).toThrow('multiple groups');
|
||||
expect(api.findGroupInviteCardGroupBySequence(778899, 67890)).toBe(67890);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -73,6 +73,64 @@ function decodeLongMsgRequest(rawBytes: Uint8Array): LongMsgResult {
|
||||
}
|
||||
|
||||
describe('actions/forward — file segment inside forward node', () => {
|
||||
it('rejects cached temporary files mixed with text before building a forward payload', async () => {
|
||||
buildSendElemsMock.mockClear();
|
||||
const bridge = mockBridge({
|
||||
recallUploadedFile: vi.fn(() => ({ scope: 'group', groupId: 12345, busId: 104 })),
|
||||
});
|
||||
await expect(
|
||||
new ForwardApi(bridge as any).upload(
|
||||
[
|
||||
{
|
||||
userUin: 10001,
|
||||
nickname: 'alice',
|
||||
elements: [
|
||||
{ type: 'text', text: 'caption' },
|
||||
{ type: 'file', fileId: 'temp' },
|
||||
],
|
||||
},
|
||||
],
|
||||
12345,
|
||||
),
|
||||
).rejects.toThrow(/temporary group files.*only file or image/i);
|
||||
expect(buildSendElemsMock).not.toHaveBeenCalled();
|
||||
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disallows temporary fallback when a forward node mixes a new file with text', async () => {
|
||||
buildSendElemsMock.mockClear();
|
||||
const bridge = mockBridge();
|
||||
bridge.apis.groupFile.upload.mockRejectedValueOnce(
|
||||
new Error('temporary group files require only file or image segments'),
|
||||
);
|
||||
await expect(
|
||||
new ForwardApi(bridge as any).upload(
|
||||
[
|
||||
{
|
||||
userUin: 10001,
|
||||
nickname: 'alice',
|
||||
elements: [
|
||||
{ type: 'text', text: 'caption' },
|
||||
{ type: 'file', url: 'base64://AQID', fileName: 'note.txt' },
|
||||
],
|
||||
},
|
||||
],
|
||||
12345,
|
||||
),
|
||||
).rejects.toThrow(/temporary group files/);
|
||||
expect(bridge.apis.groupFile.upload).toHaveBeenCalledWith(
|
||||
12345,
|
||||
'base64://AQID',
|
||||
'note.txt',
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary: false },
|
||||
);
|
||||
expect(buildSendElemsMock).not.toHaveBeenCalled();
|
||||
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a recursive window shake before identity resolution or upload', async () => {
|
||||
buildSendElemsMock.mockClear();
|
||||
const resolveUserUid = vi.fn();
|
||||
@@ -288,7 +346,9 @@ describe('actions/forward — file segment inside forward node', () => {
|
||||
12345,
|
||||
);
|
||||
|
||||
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false);
|
||||
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false, {
|
||||
allowTemporary: true,
|
||||
});
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
const [elements] = buildSendElemsMock.mock.calls[0]!;
|
||||
expect(elements).toEqual([
|
||||
@@ -513,6 +573,7 @@ describe('actions/forward — file segment inside forward node', () => {
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary: true },
|
||||
);
|
||||
const [elements] = buildSendElemsMock.mock.calls[0]!;
|
||||
expect(elements).toEqual([
|
||||
|
||||
@@ -6,7 +6,7 @@ import { ForwardApi } from '../../src/bridge/apis/forward';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
vi.mock('@snowluma/protocol/highway/image-upload', () => ({ uploadImageMsgInfo: vi.fn() }));
|
||||
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ uploadPttMsgInfo: vi.fn() }));
|
||||
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ uploadPtt: vi.fn() }));
|
||||
vi.mock('@snowluma/protocol/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn() }));
|
||||
|
||||
describe('forward metadata through upload and cached reads', () => {
|
||||
|
||||
389
packages/core/tests/actions/forward-nested-fetch.test.ts
Normal file
389
packages/core/tests/actions/forward-nested-fetch.test.ts
Normal file
@@ -0,0 +1,389 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { deflateSync, gzipSync } from 'zlib';
|
||||
import { buildApiContext, type OneBotInstanceContext } from '@snowluma/onebot/instance-context';
|
||||
import type { Elem } from '@snowluma/proto-defs/element';
|
||||
import type { LongMsgResult, RecvLongMsgReq, RecvLongMsgResp } from '@snowluma/proto-defs/longmsg';
|
||||
import type { PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { ForwardApi } from '../../src/bridge/apis/forward';
|
||||
import type { BridgeContext } from '../../src/bridge/bridge-context';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function forwardCard(format: 'xml' | 'lightApp', resId: string, key?: string): Elem {
|
||||
const content =
|
||||
format === 'xml'
|
||||
? `<msg serviceID="35" m_resid="${resId}"${key ? ` m_fileName="${key}"` : ''} />`
|
||||
: JSON.stringify({
|
||||
app: 'com.tencent.multimsg',
|
||||
meta: { detail: { resid: resId, uniseq: key } },
|
||||
});
|
||||
const data = Buffer.concat([Buffer.from([1]), deflateSync(Buffer.from(content))]);
|
||||
return format === 'xml'
|
||||
? { richMsg: { serviceId: 35, template1: data } }
|
||||
: { lightApp: { data } };
|
||||
}
|
||||
|
||||
function message(...elems: Elem[]): PushMsgBody {
|
||||
return {
|
||||
responseHead: {
|
||||
fromUin: 20002,
|
||||
fromUid: 'sender-uid',
|
||||
grp: { groupUin: 12345, memberCard: Buffer.from('alice') },
|
||||
},
|
||||
contentHead: { msgType: 82, sequence: 10, timestamp: 1700000000 },
|
||||
body: { richText: { elems } },
|
||||
};
|
||||
}
|
||||
|
||||
function setup(downloads: Map<string, LongMsgResult>, selfUin = '10001') {
|
||||
const requested: string[] = [];
|
||||
const bridge = mockBridge({
|
||||
sendRawPacket: vi.fn(async (command: string, bytes: Uint8Array) => {
|
||||
expect(command).toBe('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg');
|
||||
const resId = protobuf_decode<RecvLongMsgReq>(bytes).info!.resId!;
|
||||
requested.push(resId);
|
||||
const data = downloads.get(resId);
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(
|
||||
protobuf_encode<RecvLongMsgResp>({
|
||||
result: {
|
||||
resId,
|
||||
payload: data
|
||||
? gzipSync(protobuf_encode<LongMsgResult>(data))
|
||||
: undefined,
|
||||
},
|
||||
}),
|
||||
),
|
||||
};
|
||||
}),
|
||||
});
|
||||
bridge.identity.uin = selfUin;
|
||||
const forward = new ForwardApi(bridge as unknown as BridgeContext);
|
||||
const ctx = {
|
||||
selfId: Number(selfUin),
|
||||
bridge: { apis: { forward } },
|
||||
converterCtx: {
|
||||
selfId: Number(selfUin),
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
} as unknown as OneBotInstanceContext;
|
||||
return { api: buildApiContext(ctx), requested, bridge, forward };
|
||||
}
|
||||
|
||||
function plainResult(text: string): LongMsgResult {
|
||||
return {
|
||||
action: [
|
||||
{
|
||||
actionCommand: 'MultiMsg',
|
||||
actionData: { msgBody: [message({ text: { str: text } })] },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function nestedResult(inner: string, key: string, body?: PushMsgBody): LongMsgResult {
|
||||
return {
|
||||
action: [
|
||||
{
|
||||
actionCommand: 'MultiMsg',
|
||||
actionData: { msgBody: [message(forwardCard('xml', inner, key))] },
|
||||
},
|
||||
{
|
||||
actionCommand: key,
|
||||
actionData: { msgBody: [body ?? message({ text: { str: 'inner content' } })] },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
async function fillCache(
|
||||
api: ReturnType<typeof setup>['api'],
|
||||
downloads: Map<string, LongMsgResult>,
|
||||
prefix: string,
|
||||
count: number,
|
||||
): Promise<void> {
|
||||
for (let index = 0; index < count; index++) {
|
||||
const id = `${prefix}-${index}`;
|
||||
downloads.set(id, plainResult(id));
|
||||
await api.getForwardMsg(id);
|
||||
}
|
||||
}
|
||||
|
||||
describe('get_forward_msg / cache lifetime', () => {
|
||||
it('bounds cached results while refreshing recently read results', async () => {
|
||||
const downloads = new Map([
|
||||
['cache-cold', plainResult('cold')],
|
||||
['cache-hot', plainResult('hot')],
|
||||
]);
|
||||
const { api, requested } = setup(downloads);
|
||||
await api.getForwardMsg('cache-cold');
|
||||
await api.getForwardMsg('cache-hot');
|
||||
await fillCache(api, downloads, 'cache-pressure', 510);
|
||||
await api.getForwardMsg('cache-hot');
|
||||
await fillCache(api, downloads, 'cache-overflow', 1);
|
||||
requested.length = 0;
|
||||
await api.getForwardMsg('cache-hot');
|
||||
await api.getForwardMsg('cache-cold');
|
||||
expect(requested).toEqual(['cache-cold']);
|
||||
});
|
||||
|
||||
it('isolates cached content between bridge accounts', async () => {
|
||||
const first = setup(new Map([['same-resource', plainResult('account one')]]));
|
||||
const second = setup(new Map([['same-resource', plainResult('account two')]]), '10002');
|
||||
await first.api.getForwardMsg('same-resource');
|
||||
expect((await second.api.getForwardMsg('same-resource'))[0]?.message).toEqual([
|
||||
{ type: 'text', data: { text: 'account two' } },
|
||||
]);
|
||||
expect(second.requested).toEqual(['same-resource']);
|
||||
});
|
||||
|
||||
it('keeps nested results with a hot outer result under cache pressure', async () => {
|
||||
const downloads = new Map([['hot-outer', nestedResult('hot-inner', 'hot-inner-key')]]);
|
||||
const { api, requested } = setup(downloads);
|
||||
await api.getForwardMsg('hot-outer');
|
||||
await fillCache(api, downloads, 'nested-pressure', 511);
|
||||
await api.getForwardMsg('hot-inner');
|
||||
await fillCache(api, downloads, 'nested-overflow', 1);
|
||||
requested.length = 0;
|
||||
expect((await api.getForwardMsg('hot-outer'))[0]?.message).toEqual([
|
||||
{ type: 'forward', data: { id: 'hot-inner' } },
|
||||
]);
|
||||
expect((await api.getForwardMsg('hot-inner'))[0]?.message).toEqual([
|
||||
{ type: 'text', data: { text: 'inner content' } },
|
||||
]);
|
||||
expect(requested).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps an inner result attached to its outer result after sender enrichment', async () => {
|
||||
const nameless = message({ text: { str: 'unnamed sender' } });
|
||||
nameless.responseHead!.grp!.memberCard = new Uint8Array();
|
||||
const downloads = new Map([
|
||||
['enrich-outer', nestedResult('enrich-inner', 'enrich-key', nameless)],
|
||||
]);
|
||||
const { api, requested, bridge } = setup(downloads);
|
||||
bridge.apis.contacts.fetchGroupMemberList.mockResolvedValue([
|
||||
{ uin: 20002, nickname: 'resolved nickname', card: 'resolved card' },
|
||||
]);
|
||||
await api.getForwardMsg('enrich-outer');
|
||||
await fillCache(api, downloads, 'enrich-pressure', 511);
|
||||
requested.length = 0;
|
||||
expect((await api.getForwardMsg('enrich-inner'))[0]).toMatchObject({
|
||||
sender: { nickname: 'resolved card' },
|
||||
});
|
||||
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce();
|
||||
await api.getForwardMsg('enrich-outer');
|
||||
await api.getForwardMsg('enrich-inner');
|
||||
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce();
|
||||
expect(requested).toEqual([]);
|
||||
});
|
||||
|
||||
it('retains a shared inner result while another containing outer result remains cached', async () => {
|
||||
const downloads = new Map([
|
||||
['shared-outer-a', nestedResult('shared-inner', 'shared-key-a')],
|
||||
['shared-outer-b', nestedResult('shared-inner', 'shared-key-b')],
|
||||
]);
|
||||
const { api, requested } = setup(downloads);
|
||||
await api.getForwardMsg('shared-outer-a');
|
||||
await api.getForwardMsg('shared-outer-b');
|
||||
await fillCache(api, downloads, 'shared-pressure', 510);
|
||||
await api.getForwardMsg('shared-outer-a');
|
||||
await fillCache(api, downloads, 'shared-overflow', 1);
|
||||
requested.length = 0;
|
||||
expect((await api.getForwardMsg('shared-inner'))[0]?.message).toEqual([
|
||||
{ type: 'text', data: { text: 'inner content' } },
|
||||
]);
|
||||
expect(requested).toEqual([]);
|
||||
});
|
||||
|
||||
it('restores all nested results when an evicted outer result is downloaded again', async () => {
|
||||
const downloads = new Map([
|
||||
['restore-outer', nestedResult('restore-inner', 'restore-key')],
|
||||
]);
|
||||
const { api, requested } = setup(downloads);
|
||||
await api.getForwardMsg('restore-outer');
|
||||
await api.getForwardMsg('restore-inner');
|
||||
await fillCache(api, downloads, 'restore-pressure', 512);
|
||||
requested.length = 0;
|
||||
await api.getForwardMsg('restore-outer');
|
||||
expect((await api.getForwardMsg('restore-inner'))[0]?.message).toEqual([
|
||||
{ type: 'text', data: { text: 'inner content' } },
|
||||
]);
|
||||
expect(requested).toEqual(['restore-outer']);
|
||||
});
|
||||
|
||||
it('does not resurrect evicted nested results when enrichment finishes late', async () => {
|
||||
const nameless = message({ text: { str: 'late sender' } });
|
||||
nameless.responseHead!.grp!.memberCard = new Uint8Array();
|
||||
const downloads = new Map([
|
||||
['late-outer', nestedResult('late-inner', 'late-key', nameless)],
|
||||
]);
|
||||
const { api, requested, bridge } = setup(downloads);
|
||||
const members = [{ uin: 20002, nickname: 'late name', card: '' }];
|
||||
let finishEnrichment!: () => void;
|
||||
const enrichment = new Promise<typeof members>((resolve) => {
|
||||
finishEnrichment = () => resolve(members);
|
||||
});
|
||||
bridge.apis.contacts.fetchGroupMemberList.mockReturnValueOnce(enrichment);
|
||||
await api.getForwardMsg('late-outer');
|
||||
const pending = api.getForwardMsg('late-inner');
|
||||
await vi.waitFor(() =>
|
||||
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce(),
|
||||
);
|
||||
await fillCache(api, downloads, 'late-pressure', 512);
|
||||
finishEnrichment();
|
||||
expect((await pending)[0]).toMatchObject({ sender: { nickname: 'late name' } });
|
||||
requested.length = 0;
|
||||
await expect(api.getForwardMsg('late-inner')).rejects.toThrow('payload is empty');
|
||||
await api.getForwardMsg('late-outer');
|
||||
expect((await api.getForwardMsg('late-inner'))[0]?.message).toEqual([
|
||||
{ type: 'text', data: { text: 'late sender' } },
|
||||
]);
|
||||
expect(requested).toEqual(['late-inner', 'late-outer']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('get_forward_msg / nested downloads (#529)', () => {
|
||||
it.each(['xml', 'lightApp'] as const)(
|
||||
'resolves siblings and three levels of %s forwards from one outer payload',
|
||||
async (format) => {
|
||||
const outer = `nested-fetch-${format}-outer`;
|
||||
const inner = `nested-fetch-${format}-inner`;
|
||||
const sibling = `nested-fetch-${format}-sibling`;
|
||||
const leaf = `nested-fetch-${format}-leaf`;
|
||||
const { api, requested } = setup(
|
||||
new Map([
|
||||
[
|
||||
outer,
|
||||
{
|
||||
action: [
|
||||
{
|
||||
actionCommand: 'MultiMsg',
|
||||
actionData: {
|
||||
msgBody: [
|
||||
message(forwardCard(format, inner, 'inner-key')),
|
||||
message(forwardCard(format, sibling, 'sibling-key')),
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
actionCommand: 'leaf-key',
|
||||
actionData: {
|
||||
msgBody: [
|
||||
message(
|
||||
{ text: { str: 'deepest content' } },
|
||||
{
|
||||
customFace: {
|
||||
md5: Buffer.alloc(16, 0xab),
|
||||
origUrl: 'https://example.com/forward.png',
|
||||
width: 32,
|
||||
height: 24,
|
||||
},
|
||||
},
|
||||
),
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
actionCommand: 'sibling-key',
|
||||
actionData: {
|
||||
msgBody: [message({ text: { str: 'sibling content' } })],
|
||||
},
|
||||
},
|
||||
{
|
||||
actionCommand: 'inner-key',
|
||||
actionData: {
|
||||
msgBody: [message(forwardCard(format, leaf, 'leaf-key'))],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
const parent = await api.getForwardMsg(outer);
|
||||
expect(parent.map((node) => node.message)).toEqual([
|
||||
[{ type: 'forward', data: { id: inner } }],
|
||||
[{ type: 'forward', data: { id: sibling } }],
|
||||
]);
|
||||
const middle = await api.getForwardMsg(inner);
|
||||
expect(middle[0]!.message).toEqual([{ type: 'forward', data: { id: leaf } }]);
|
||||
expect((await api.getForwardMsg(leaf))[0]).toMatchObject({
|
||||
sender: { user_id: 20002, nickname: 'alice' },
|
||||
time: 1700000000,
|
||||
message: [
|
||||
{ type: 'text', data: { text: 'deepest content' } },
|
||||
{ type: 'image', data: { url: 'https://example.com/forward.png' } },
|
||||
],
|
||||
});
|
||||
expect((await api.getForwardMsg(sibling))[0]!.message).toEqual([
|
||||
{ type: 'text', data: { text: 'sibling content' } },
|
||||
]);
|
||||
expect(requested).toEqual([outer]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([undefined, 'unmatched-key'])(
|
||||
'downloads by resId when the XML filename is %s and preserves empty-payload errors',
|
||||
async (key) => {
|
||||
const outer = `nested-fetch-fallback-${key}-outer`;
|
||||
const inner = `nested-fetch-fallback-${key}-inner`;
|
||||
const empty = `nested-fetch-fallback-${key}-empty`;
|
||||
const { api, requested } = setup(
|
||||
new Map([
|
||||
[
|
||||
outer,
|
||||
{
|
||||
action: [
|
||||
{
|
||||
actionCommand: 'MultiMsg',
|
||||
actionData: {
|
||||
msgBody: [
|
||||
message(forwardCard('xml', inner, key)),
|
||||
message(forwardCard('xml', empty, key)),
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
actionCommand: 'unrelated-key',
|
||||
actionData: {
|
||||
msgBody: [message({ text: { str: 'unrelated content' } })],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
inner,
|
||||
{
|
||||
action: [
|
||||
{
|
||||
actionCommand: 'MultiMsg',
|
||||
actionData: {
|
||||
msgBody: [message({ text: { str: 'downloaded content' } })],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
]),
|
||||
);
|
||||
|
||||
await api.getForwardMsg(outer);
|
||||
expect((await api.getForwardMsg(inner))[0]!.message).toEqual([
|
||||
{ type: 'text', data: { text: 'downloaded content' } },
|
||||
]);
|
||||
await expect(api.getForwardMsg(empty)).rejects.toThrow(
|
||||
'download forward message payload is empty',
|
||||
);
|
||||
expect(requested).toEqual([outer, inner, empty]);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -33,13 +33,14 @@ vi.mock('@snowluma/protocol/highway/image-upload', () => ({
|
||||
uploadImageMsgInfo: vi.fn(async () => new Uint8Array()),
|
||||
}));
|
||||
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({
|
||||
uploadPttMsgInfo: vi.fn(async () => new Uint8Array()),
|
||||
uploadPtt: vi.fn(async () => ({ msgInfo: new Uint8Array() })),
|
||||
}));
|
||||
vi.mock('@snowluma/protocol/highway/video-upload', () => ({
|
||||
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array()),
|
||||
}));
|
||||
|
||||
import { ForwardApi } from '../../src/bridge/apis/forward';
|
||||
import type { BridgeContext } from '../../src/bridge/bridge-context';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function uploadResponseWithResId(resId: string) {
|
||||
@@ -107,6 +108,49 @@ function findLightAppJson(msgBody: PushMsgBody[]): {
|
||||
}
|
||||
|
||||
describe('forward / nested upload wire alignment', () => {
|
||||
it('bounds uploaded results while keeping a recently read nested upload together', async () => {
|
||||
let sequence = 0;
|
||||
const sendRawPacket = vi.fn(async (command: string) => {
|
||||
if (command !== 'trpc.group.long_msg_interface.MsgService.SsoSendLongMsg') {
|
||||
throw new Error('test cache miss');
|
||||
}
|
||||
|
||||
return uploadResponseWithResId(`upload-cache-${++sequence}`);
|
||||
});
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
const forward = new ForwardApi(bridge as unknown as BridgeContext);
|
||||
const outer = await forward.upload([
|
||||
{
|
||||
userUin: 111,
|
||||
nickname: 'outer',
|
||||
elements: [],
|
||||
innerForward: [
|
||||
{
|
||||
userUin: 222,
|
||||
nickname: 'inner',
|
||||
elements: [{ type: 'text', text: 'nested upload' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
const filler = [{ userUin: 111, nickname: 'filler', elements: [] }];
|
||||
|
||||
for (let index = 0; index < 511; index++) {
|
||||
await forward.upload(filler);
|
||||
}
|
||||
|
||||
await forward.fetch('upload-cache-1');
|
||||
await forward.upload(filler);
|
||||
const uploadedCount = sendRawPacket.mock.calls.length;
|
||||
const sameBridgeApi = new ForwardApi(bridge as unknown as BridgeContext);
|
||||
expect((await sameBridgeApi.fetch(outer))[0]?.elements[0]?.resId).toBe('upload-cache-1');
|
||||
expect((await sameBridgeApi.fetch('upload-cache-1'))[0]?.elements).toEqual([
|
||||
{ type: 'text', text: 'nested upload' },
|
||||
]);
|
||||
expect(sendRawPacket).toHaveBeenCalledTimes(uploadedCount);
|
||||
await expect(forward.fetch('upload-cache-3')).rejects.toThrow('test cache miss');
|
||||
});
|
||||
|
||||
it('outer LongMsgResult contains both MultiMsg and the inner uuid piggyback action', async () => {
|
||||
// Inner upload returns inner-res; outer upload returns outer-res.
|
||||
const responses = ['inner-res', 'outer-res'];
|
||||
|
||||
188
packages/core/tests/actions/forward-resid-less.test.ts
Normal file
188
packages/core/tests/actions/forward-resid-less.test.ts
Normal file
@@ -0,0 +1,188 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { deflateSync, gunzipSync, gzipSync } from 'node:zlib';
|
||||
import type { Elem } from '@snowluma/proto-defs/element';
|
||||
import type {
|
||||
LongMsgResult,
|
||||
RecvLongMsgReq,
|
||||
RecvLongMsgResp,
|
||||
SendLongMsgReq,
|
||||
SendLongMsgResp,
|
||||
} from '@snowluma/proto-defs/longmsg';
|
||||
import type { PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import { buildApiContext, type OneBotInstanceContext } from '@snowluma/onebot/instance-context';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { ForwardApi } from '../../src/bridge/apis/forward';
|
||||
import type { BridgeContext } from '../../src/bridge/bridge-context';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
const OUTER_RES_ID = 'outer-resid';
|
||||
const INNER_UUID = 'C125CE25-AE7E-4E1A-ABDC-9750918162EB';
|
||||
const INNER_FILE_NAME = `MultiMsg_${INNER_UUID}`;
|
||||
|
||||
function packetResult(responseData: Uint8Array) {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(responseData),
|
||||
};
|
||||
}
|
||||
|
||||
function residLessForwardCard(): Elem {
|
||||
const xml =
|
||||
`<msg serviceID="35" templateID="1" action="viewMultiMsg" ` +
|
||||
`m_fileName="${INNER_FILE_NAME}" tSum="2" flag="3" />`;
|
||||
const data = Buffer.concat([Buffer.from([1]), deflateSync(Buffer.from(xml))]);
|
||||
return { richMsg: { serviceId: 35, template1: data } };
|
||||
}
|
||||
|
||||
function message(...elems: Elem[]): PushMsgBody {
|
||||
return {
|
||||
responseHead: {
|
||||
fromUin: 20002,
|
||||
fromUid: 'sender-uid',
|
||||
grp: { groupUin: 12345, memberCard: Buffer.from('alice') },
|
||||
},
|
||||
contentHead: { msgType: 82, sequence: 10, timestamp: 1700000000 },
|
||||
body: { richText: { elems } },
|
||||
};
|
||||
}
|
||||
|
||||
function outerResult(innerActionCommand?: string): LongMsgResult {
|
||||
return {
|
||||
action: [
|
||||
{
|
||||
actionCommand: 'MultiMsg',
|
||||
actionData: { msgBody: [message(residLessForwardCard())] },
|
||||
},
|
||||
...(innerActionCommand
|
||||
? [
|
||||
{
|
||||
actionCommand: innerActionCommand,
|
||||
actionData: {
|
||||
msgBody: [
|
||||
message({ text: { str: 'inner one' } }),
|
||||
message({ text: { str: 'inner two' } }),
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function setup(innerActionCommand?: string) {
|
||||
const requested: string[] = [];
|
||||
const uploads: SendLongMsgReq[] = [];
|
||||
const sendRawPacket = vi.fn(async (command: string, bytes: Uint8Array) => {
|
||||
if (command.endsWith('SsoRecvLongMsg')) {
|
||||
const resId = protobuf_decode<RecvLongMsgReq>(bytes).info!.resId!;
|
||||
requested.push(resId);
|
||||
return packetResult(
|
||||
protobuf_encode<RecvLongMsgResp>({
|
||||
result: {
|
||||
resId,
|
||||
payload:
|
||||
resId === OUTER_RES_ID
|
||||
? gzipSync(
|
||||
protobuf_encode<LongMsgResult>(
|
||||
outerResult(innerActionCommand),
|
||||
),
|
||||
)
|
||||
: undefined,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
expect(command).toMatch(/SsoSendLongMsg$/);
|
||||
const upload = protobuf_decode<SendLongMsgReq>(bytes);
|
||||
uploads.push(upload);
|
||||
return packetResult(
|
||||
protobuf_encode<SendLongMsgResp>({ result: { resId: `rebuilt-${uploads.length}` } }),
|
||||
);
|
||||
});
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
const forward = new ForwardApi(bridge as unknown as BridgeContext);
|
||||
const sendGroup = vi.fn(async (_groupId: number, _elements: MessageElement[]) => ({
|
||||
messageId: 1,
|
||||
sequence: 2,
|
||||
clientSequence: 3,
|
||||
random: 4,
|
||||
timestamp: 1700000001,
|
||||
}));
|
||||
const ctx = {
|
||||
selfId: 10001,
|
||||
bridge: {
|
||||
identity: { nickname: 'SnowLuma' },
|
||||
apis: { forward, message: { sendGroup } },
|
||||
},
|
||||
messageStore: {
|
||||
findEvent: () => ({
|
||||
message: [{ type: 'forward', data: { id: OUTER_RES_ID } }],
|
||||
}),
|
||||
storeEvent: vi.fn(),
|
||||
},
|
||||
converterCtx: {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
cacheMessageMeta: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
} as unknown as OneBotInstanceContext;
|
||||
|
||||
return { api: buildApiContext(ctx), requested, uploads, sendGroup };
|
||||
}
|
||||
|
||||
describe('resid-less nested forwards (#589)', () => {
|
||||
it.each([INNER_UUID, INNER_FILE_NAME])(
|
||||
'resolves an outer piggyback keyed by %s without another download',
|
||||
async (innerActionCommand) => {
|
||||
const { api, requested } = setup(innerActionCommand);
|
||||
const outer = await api.getForwardMsg(OUTER_RES_ID);
|
||||
expect(outer[0]?.message).toEqual([{ type: 'forward', data: { id: INNER_FILE_NAME } }]);
|
||||
|
||||
const inner = await api.getForwardMsg(INNER_FILE_NAME);
|
||||
expect(inner.map((node) => node.message)).toEqual([
|
||||
[{ type: 'text', data: { text: 'inner one' } }],
|
||||
[{ type: 'text', data: { text: 'inner two' } }],
|
||||
]);
|
||||
expect(requested).toEqual([OUTER_RES_ID]);
|
||||
},
|
||||
);
|
||||
|
||||
it('rebuilds both layers before sending to another group', async () => {
|
||||
const { api, requested, uploads, sendGroup } = setup(INNER_UUID);
|
||||
await expect(api.forwardSingleMsg(77, { groupId: 65432 })).resolves.toHaveProperty(
|
||||
'messageId',
|
||||
);
|
||||
|
||||
expect(requested).toEqual([OUTER_RES_ID]);
|
||||
expect(uploads).toHaveLength(2);
|
||||
const outerBytes = gunzipSync(Buffer.from(uploads[1]!.info!.payload!));
|
||||
const outer = protobuf_decode<LongMsgResult>(outerBytes);
|
||||
expect(outer.action).toHaveLength(2);
|
||||
expect(outerBytes.toString()).not.toContain(INNER_FILE_NAME);
|
||||
expect(sendGroup).toHaveBeenCalledOnce();
|
||||
expect(sendGroup.mock.calls[0]![1]).toEqual([
|
||||
expect.objectContaining({ type: 'forward', resId: 'rebuilt-2' }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('fails before upload or send when the inner piggyback is unavailable', async () => {
|
||||
const { api, requested, uploads, sendGroup } = setup();
|
||||
await expect(api.forwardSingleMsg(77, { groupId: 65432 })).rejects.toThrow(
|
||||
'download forward message payload is empty',
|
||||
);
|
||||
|
||||
expect(requested).toEqual([OUTER_RES_ID, INNER_FILE_NAME]);
|
||||
expect(uploads).toHaveLength(0);
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -71,7 +71,7 @@ function setup(id: string) {
|
||||
responseHead: {
|
||||
fromUin: 20002,
|
||||
fromUid: 'sender-uid',
|
||||
grp: { groupUin: 12345, memberCard: 'alice' },
|
||||
grp: { groupUin: 12345, memberCard: Buffer.from('alice') },
|
||||
},
|
||||
contentHead: { msgType: 82, sequence: 10, timestamp: 1700000000 },
|
||||
body: {
|
||||
|
||||
@@ -190,7 +190,7 @@ describe('actions/forward', () => {
|
||||
responseHead: {
|
||||
fromUin: 1787882683,
|
||||
fromUid: 'u_x',
|
||||
grp: { groupUin: 284840486, memberCard: '墨梓柒' },
|
||||
grp: { groupUin: 284840486, memberCard: Buffer.from('墨梓柒') },
|
||||
},
|
||||
contentHead: { msgType: 82, sequence: 1, timestamp: 100 }, // 82 = PkgType.GroupMessage
|
||||
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
|
||||
|
||||
277
packages/core/tests/actions/friend-profiles.test.ts
Normal file
277
packages/core/tests/actions/friend-profiles.test.ts
Normal file
@@ -0,0 +1,277 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type {
|
||||
OidbBase,
|
||||
OidbFriend,
|
||||
OidbSvcTrpcTcp0xFD4_1Response,
|
||||
} from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
OidbUserInfoRequest,
|
||||
OidbUserInfoResponse,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { Bridge } from '../../src/bridge/bridge';
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
let reject!: (reason: Error) => void;
|
||||
const promise = new Promise<void>((yes, no) => {
|
||||
resolve = yes;
|
||||
reject = no;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
const bridges: Bridge[] = [];
|
||||
afterEach(async () => {
|
||||
await Promise.all(bridges.splice(0).map((bridge) => bridge.dispose()));
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function friend(uin: number, name = 'Roster'): OidbFriend {
|
||||
return {
|
||||
uin,
|
||||
uid: `u_${uin}`,
|
||||
customGroup: 7,
|
||||
additional: [
|
||||
{
|
||||
type: 1,
|
||||
layer1: {
|
||||
properties: [
|
||||
{ code: 20002, value: Buffer.from(name) },
|
||||
{ code: 102, value: Buffer.from('') },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function setup(roster: () => OidbFriend[], load: (uin: number) => Promise<void> = async () => {}) {
|
||||
const bridge = new Bridge(IdentityService.memory('90001'));
|
||||
bridges.push(bridge);
|
||||
const profileCalls: number[] = [];
|
||||
let active = 0;
|
||||
let peak = 0;
|
||||
const send = vi.spyOn(bridge, 'sendRawPacket').mockImplementation(async (cmd, payload) => {
|
||||
let responseData: Uint8Array;
|
||||
|
||||
if (cmd === 'OidbSvcTrpcTcp.0xfd4_1') {
|
||||
const friends = roster();
|
||||
responseData = protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>({
|
||||
body: {
|
||||
friends,
|
||||
categories: [
|
||||
{ categoryId: 7, categoryName: 'Friends', memberCount: friends.length },
|
||||
],
|
||||
},
|
||||
});
|
||||
} else if (cmd === 'OidbSvcTrpcTcp.0xfe1_2') {
|
||||
const uin = protobuf_decode<OidbBase<OidbUserInfoRequest>>(payload).body!.uin!;
|
||||
profileCalls.push(uin);
|
||||
peak = Math.max(peak, ++active);
|
||||
|
||||
try {
|
||||
await load(uin);
|
||||
} finally {
|
||||
active--;
|
||||
}
|
||||
|
||||
responseData = protobuf_encode<OidbBase<OidbUserInfoResponse>>({
|
||||
body: {
|
||||
body: {
|
||||
uin,
|
||||
uid: `u_${uin}`,
|
||||
properties: {
|
||||
bytesProperties: [
|
||||
{ code: 102, value: Buffer.from('Profile sign') },
|
||||
{ code: 20020, value: Buffer.from('City') },
|
||||
],
|
||||
numberProperties: [
|
||||
{ number1: 20037, number2: 0 },
|
||||
{ number1: 41756, number2: 0 },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
} else {
|
||||
throw new Error(`unexpected request ${cmd}`);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(responseData),
|
||||
};
|
||||
});
|
||||
return {
|
||||
bridge,
|
||||
api: bridge.apis.contacts,
|
||||
send,
|
||||
profileCalls,
|
||||
peak: () => peak,
|
||||
active: () => active,
|
||||
};
|
||||
}
|
||||
|
||||
describe('explicit friend profile enrichment', () => {
|
||||
it('releases profile cache timers when its Bridge is disposed', async () => {
|
||||
vi.useFakeTimers();
|
||||
const { api, bridge, profileCalls } = setup(() => [friend(10001)]);
|
||||
await api.fetchFriendList({ withProfile: true });
|
||||
expect(profileCalls).toEqual([10001]);
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
|
||||
await bridge.dispose();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not start profile cache loads when a roster response arrives after disposal', async () => {
|
||||
vi.useFakeTimers();
|
||||
const { api, bridge, send, profileCalls } = setup(() => [friend(10001)]);
|
||||
const response = await send.getMockImplementation()!(
|
||||
'OidbSvcTrpcTcp.0xfd4_1',
|
||||
new Uint8Array(),
|
||||
);
|
||||
let resolve!: (value: typeof response) => void;
|
||||
send.mockReturnValueOnce(
|
||||
new Promise((yes) => {
|
||||
resolve = yes;
|
||||
}),
|
||||
);
|
||||
const pending = api.fetchFriendList({ withProfile: true });
|
||||
const checked = expect(pending).rejects.toThrow('friend profile enrichment failed');
|
||||
await bridge.dispose();
|
||||
|
||||
resolve(response);
|
||||
await checked;
|
||||
expect(profileCalls).toEqual([]);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not fan out on a cold 160-friend ordinary or categorized list', async () => {
|
||||
const { api, profileCalls, send } = setup(() =>
|
||||
Array.from({ length: 160 }, (_, i) => friend(10000 + i)),
|
||||
);
|
||||
expect(await api.fetchFriendList()).toHaveLength(160);
|
||||
expect((await api.fetchFriendCategories())[0]?.friends).toHaveLength(160);
|
||||
expect(profileCalls).toEqual([]);
|
||||
expect(send).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('shares the cache across list forms, preserves roster values and isolates accounts', async () => {
|
||||
let now = Date.now();
|
||||
vi.spyOn(Date, 'now').mockImplementation(() => now);
|
||||
const one = setup(() => [friend(10001)]);
|
||||
const first = await one.api.fetchFriendList({ withProfile: true });
|
||||
expect(first[0]).toMatchObject({
|
||||
nickname: 'Roster',
|
||||
profile: { sign: '', age: 0, vipFlag: false, city: 'City' },
|
||||
});
|
||||
first[0]!.profile!.city = 'caller mutation';
|
||||
const grouped = await one.api.fetchFriendCategories({ withProfile: true });
|
||||
expect(grouped[0]?.friends[0]?.profile?.city).toBe('City');
|
||||
expect(one.profileCalls).toEqual([10001]);
|
||||
const two = setup(() => [friend(10001)]);
|
||||
await two.api.fetchFriendList({ withProfile: true });
|
||||
expect(two.profileCalls).toEqual([10001]);
|
||||
now += 300_001;
|
||||
await one.api.fetchFriendList({ withProfile: true });
|
||||
expect(one.profileCalls).toEqual([10001, 10001]);
|
||||
});
|
||||
|
||||
it('deduplicates overlapping lists and caps total concurrent queries at four', async () => {
|
||||
const gates = new Map<number, ReturnType<typeof deferred>>();
|
||||
let page = 0;
|
||||
const { api, profileCalls, peak } = setup(
|
||||
() => (page++ === 0 ? [1, 2, 3, 4] : [3, 4, 5, 6]).map((id) => friend(10000 + id)),
|
||||
(uin) => {
|
||||
const gate = deferred();
|
||||
gates.set(uin, gate);
|
||||
return gate.promise;
|
||||
},
|
||||
);
|
||||
const first = api.fetchFriendList({ withProfile: true });
|
||||
const second = api.fetchFriendCategories({ withProfile: true });
|
||||
await vi.waitFor(() => expect(profileCalls).toHaveLength(4));
|
||||
|
||||
for (const gate of gates.values()) {
|
||||
gate.resolve();
|
||||
}
|
||||
|
||||
await vi.waitFor(() => expect(profileCalls).toHaveLength(6));
|
||||
|
||||
for (const gate of gates.values()) {
|
||||
gate.resolve();
|
||||
}
|
||||
|
||||
await Promise.all([first, second]);
|
||||
expect(new Set(profileCalls).size).toBe(6);
|
||||
expect(peak()).toBe(4);
|
||||
});
|
||||
|
||||
it('drains a failed batch, surfaces the failure and retries only on a later request', async () => {
|
||||
const gates = new Map<number, ReturnType<typeof deferred>>();
|
||||
let blocking = true;
|
||||
const { api, bridge, profileCalls, active } = setup(
|
||||
() => [1, 2, 3, 4, 5].map((id) => friend(10000 + id)),
|
||||
(uin) => {
|
||||
if (!blocking) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
const gate = deferred();
|
||||
gates.set(uin, gate);
|
||||
return gate.promise;
|
||||
},
|
||||
);
|
||||
let finished = false;
|
||||
const result = api.fetchFriendList({ withProfile: true });
|
||||
const checked = expect(result).rejects.toThrow('friend profile enrichment failed');
|
||||
void result.then(
|
||||
() => {
|
||||
finished = true;
|
||||
},
|
||||
() => {
|
||||
finished = true;
|
||||
},
|
||||
);
|
||||
await vi.waitFor(() => expect(profileCalls).toHaveLength(4));
|
||||
gates.get(10001)!.reject(new Error('synthetic timeout'));
|
||||
await Promise.resolve();
|
||||
expect(finished).toBe(false);
|
||||
|
||||
for (const [uin, gate] of gates) {
|
||||
if (uin !== 10001) {
|
||||
gate.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
await checked;
|
||||
expect(active()).toBe(0);
|
||||
expect(profileCalls).toHaveLength(4);
|
||||
expect(bridge.identity.friends).toEqual([]);
|
||||
blocking = false;
|
||||
await api.fetchFriendList({ withProfile: true });
|
||||
expect(profileCalls).toEqual([10001, 10002, 10003, 10004, 10001, 10005]);
|
||||
});
|
||||
|
||||
it('does not let a slow enriched snapshot replace a newer ordinary roster', async () => {
|
||||
const gate = deferred();
|
||||
let page = 0;
|
||||
const { api, bridge, profileCalls } = setup(
|
||||
() => [friend(10001, page++ === 0 ? 'Old' : 'New')],
|
||||
() => gate.promise,
|
||||
);
|
||||
const old = api.fetchFriendList({ withProfile: true });
|
||||
await vi.waitFor(() => expect(profileCalls).toHaveLength(1));
|
||||
await api.fetchFriendList();
|
||||
gate.resolve();
|
||||
expect((await old)[0]?.nickname).toBe('Old');
|
||||
expect(bridge.identity.findFriend(10001)?.nickname).toBe('New');
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,14 @@ import { describe, it, expect, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase, OidbSvcTrpcTcp0x88D_0Response } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbGetGroupExtResp } from '@snowluma/proto-defs/oidb-actions/group-ext';
|
||||
import type {
|
||||
GetGroupAdminPermissionsResponse,
|
||||
GetGroupAdminReceiveVerifyResponse,
|
||||
SetGroupAdminPermissionsRequest,
|
||||
SetGroupAdminReceiveVerifyRequest,
|
||||
SetGroupAdminReceiveVerifyResponse,
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-admin-permissions';
|
||||
import type { BridgeContext } from '../../src/bridge/bridge-context';
|
||||
import type {
|
||||
Oidb0x8a0Req,
|
||||
Oidb0x8a7Resp,
|
||||
@@ -113,6 +121,160 @@ function packRobotExt(robotMemberSwitch?: number, robotMemberExamine?: number) {
|
||||
}
|
||||
|
||||
describe('apis/group-admin', () => {
|
||||
it.each([
|
||||
[0, true],
|
||||
[64, false],
|
||||
[undefined, null],
|
||||
] as const)(
|
||||
'maps receive-verification state %s without inventing missing permissions',
|
||||
async (flag, enabled) => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(
|
||||
packResponse(
|
||||
protobuf_encode<OidbBase<GetGroupAdminPermissionsResponse>>({
|
||||
body: {
|
||||
groupCode: 12345n,
|
||||
members: [
|
||||
{
|
||||
memberUin: 67890n,
|
||||
ext: { permissions: { items: [{ item: 1, value: 2 }] } },
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(
|
||||
packResponse(
|
||||
protobuf_encode<OidbBase<GetGroupAdminReceiveVerifyResponse>>({
|
||||
body: {
|
||||
groupCode: 12345n,
|
||||
members: [
|
||||
{
|
||||
identity: { uid: 'resolved-uid', uin: 67890n },
|
||||
memberFlagExt: flag,
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as unknown as BridgeContext).getAdminPermissions(
|
||||
12345,
|
||||
67890,
|
||||
),
|
||||
).resolves.toEqual({
|
||||
group_id: 12345,
|
||||
user_id: 67890,
|
||||
recall_member_message: null,
|
||||
kick_member: false,
|
||||
kick_member_per_day: null,
|
||||
receive_verify: enabled,
|
||||
});
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
|
||||
expect(bridge.resolveUserUid).toHaveBeenCalledExactlyOnceWith(67890, 12345);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(['OidbSvcTrpcTcp.0x9164_2', 'OidbSvcTrpcTcp.0xfe7_4'])(
|
||||
'rejects the combined snapshot when %s fails',
|
||||
async (failedCommand) => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(async (command: string) => {
|
||||
if (command === failedCommand) {
|
||||
return packOidbFail(1287);
|
||||
}
|
||||
|
||||
if (command === 'OidbSvcTrpcTcp.0x9164_2') {
|
||||
return packResponse(
|
||||
protobuf_encode<OidbBase<GetGroupAdminPermissionsResponse>>({
|
||||
body: { groupCode: 12345n, members: [{ memberUin: 67890n }] },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return packResponse(
|
||||
protobuf_encode<OidbBase<GetGroupAdminReceiveVerifyResponse>>({
|
||||
body: {
|
||||
groupCode: 12345n,
|
||||
members: [{ identity: { uid: 'resolved-uid' }, memberFlagExt: 0 }],
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as unknown as BridgeContext).getAdminPermissions(
|
||||
12345,
|
||||
67890,
|
||||
),
|
||||
).rejects.toThrow('OIDB error 1287');
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
|
||||
},
|
||||
);
|
||||
|
||||
it('propagates identity resolution failures when reading administrator permissions', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.resolveUserUid.mockRejectedValueOnce(new Error('identity unavailable'));
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(
|
||||
packResponse(
|
||||
protobuf_encode<OidbBase<GetGroupAdminPermissionsResponse>>({
|
||||
body: { groupCode: 12345n, members: [{ memberUin: 67890n }] },
|
||||
}),
|
||||
),
|
||||
);
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as unknown as BridgeContext).getAdminPermissions(12345, 67890),
|
||||
).rejects.toThrow('identity unavailable');
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('writes administrator capabilities and receive-verification through separate services', async () => {
|
||||
const bridge = mockBridge();
|
||||
const api = new GroupAdminApi(bridge as unknown as BridgeContext);
|
||||
await api.setAdminPermissions(12345, 67890, { recallMemberMessage: false });
|
||||
const [permissionCmd, permissionBytes] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
expect(permissionCmd).toBe('OidbSvcTrpcTcp.0x9c1c_2');
|
||||
expect(
|
||||
protobuf_decode<OidbBase<SetGroupAdminPermissionsRequest>>(permissionBytes).body,
|
||||
).toEqual({
|
||||
groupCode: 12345n,
|
||||
memberUin: 67890n,
|
||||
permissions: [{ item: 2, value: 2, extra: null }],
|
||||
});
|
||||
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(
|
||||
packResponse(
|
||||
protobuf_encode<OidbBase<SetGroupAdminReceiveVerifyResponse>>({
|
||||
body: { groupCode: 12345n, result: { successfulUins: [67890n] } },
|
||||
}),
|
||||
),
|
||||
);
|
||||
await api.setAdminReceiveVerify(12345, 67890, false);
|
||||
const [verifyCmd, verifyBytes] = bridge.sendRawPacket.mock.calls[1]!;
|
||||
expect(verifyCmd).toBe('OidbSvcTrpcTcp.0x904_1');
|
||||
expect(
|
||||
protobuf_decode<OidbBase<SetGroupAdminReceiveVerifyRequest>>(verifyBytes).body,
|
||||
).toEqual({
|
||||
groupCode: 12345n,
|
||||
operation: { adminUins: [67890n], authority: 1, operate: 0 },
|
||||
});
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
|
||||
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not swallow an unconfirmed receive-verification response', async () => {
|
||||
const bridge = mockBridge();
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as unknown as BridgeContext).setAdminReceiveVerify(
|
||||
12345,
|
||||
67890,
|
||||
true,
|
||||
),
|
||||
).rejects.toThrow('missing or mismatched group');
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('muteMember resolves UID and dispatches 0x1253_1', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new GroupAdminApi(bridge as any).muteMember(12345, 67890, 600);
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
|
||||
import type {
|
||||
OidbGroupFileCountViewResp,
|
||||
OidbGroupFileReq,
|
||||
OidbGroupFileResp,
|
||||
OidbGroupFileUploadResp,
|
||||
OidbGroupFileViewResp,
|
||||
OidbGroupFileFolderResp,
|
||||
OidbGroupSendFileReq,
|
||||
@@ -70,6 +72,10 @@ function packResponse(body: Uint8Array) {
|
||||
};
|
||||
}
|
||||
|
||||
function uploadResponse(upload: OidbGroupFileUploadResp) {
|
||||
return packResponse(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: { upload } }));
|
||||
}
|
||||
|
||||
let STAGED_FILE: string;
|
||||
|
||||
describe('apis/group-file', () => {
|
||||
@@ -138,7 +144,7 @@ describe('apis/group-file', () => {
|
||||
const api = new GroupFileApi(bridge as any);
|
||||
vi.spyOn(api, 'publish').mockResolvedValue();
|
||||
const out = await api.upload(12345, '/path/file.bin');
|
||||
expect(out).toEqual({ fileId: 'fid-xyz' });
|
||||
expect(out).toEqual({ fileId: 'fid-xyz', busId: 102 });
|
||||
expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled();
|
||||
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -224,8 +230,180 @@ describe('apis/group-file', () => {
|
||||
await expect(
|
||||
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
|
||||
).rejects.toThrow(/code=999/);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
|
||||
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([-403, -9801, -98090])(
|
||||
'retries capacity error %s as a temporary group file',
|
||||
async (retCode) => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(
|
||||
uploadResponse({ retCode, retMsg: 'permanent storage full' }),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
uploadResponse({ fileId: 'temporary-file', busId: 104, boolFileExist: true }),
|
||||
);
|
||||
const api = new GroupFileApi(bridge as any);
|
||||
const result = await api.upload(12345, '/path/file.bin', 'doc.bin', '/folder');
|
||||
expect(result).toMatchObject({ fileId: 'temporary-file', busId: 104 });
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
|
||||
const requests = bridge.sendRawPacket.mock.calls
|
||||
.slice(0, 2)
|
||||
.map(([, bytes]) => protobuf_decode<OidbBase<OidbGroupFileReq>>(bytes).body?.file);
|
||||
expect(requests[0]).toMatchObject({ busId: 102, targetDirectory: '/folder' });
|
||||
expect(requests[1]).toEqual({ ...requests[0], busId: 104 });
|
||||
const publish = protobuf_decode<OidbBase<OidbGroupSendFileReq>>(
|
||||
bridge.sendRawPacket.mock.calls[2]![1],
|
||||
);
|
||||
expect(publish.body?.body?.info).toMatchObject({
|
||||
fileId: 'temporary-file',
|
||||
busiType: 104,
|
||||
});
|
||||
expect(bridge.rememberUploadedFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ busId: 104, groupId: 12345 }),
|
||||
);
|
||||
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('carries the server-selected storage type through bytes, publication and cached reuse', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(
|
||||
uploadResponse({
|
||||
fileId: 'temporary-file',
|
||||
busId: 104,
|
||||
uploadIp: '127.0.0.1',
|
||||
uploadPort: 8080,
|
||||
fileKey: new Uint8Array([7]),
|
||||
checkKey: new Uint8Array([8]),
|
||||
}),
|
||||
);
|
||||
bridge.recallUploadedFile.mockImplementation(
|
||||
() => bridge.rememberUploadedFile.mock.calls.at(-1)?.[0],
|
||||
);
|
||||
const api = new GroupFileApi(bridge as any);
|
||||
await api.upload(12345, '/path/file.bin');
|
||||
const ext = protobuf_decode<FileUploadExt>(
|
||||
vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]![5],
|
||||
);
|
||||
expect(ext.entry?.busiBuff?.busId).toBe(104);
|
||||
await api.publish(12345, 'temporary-file');
|
||||
|
||||
for (const [, bytes] of bridge.sendRawPacket.mock.calls.slice(1)) {
|
||||
expect(
|
||||
protobuf_decode<OidbBase<OidbGroupSendFileReq>>(bytes).body?.body?.info?.busiType,
|
||||
).toBe(104);
|
||||
}
|
||||
});
|
||||
|
||||
it('stops after a failed temporary attempt and releases the staged file', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(uploadResponse({ retCode: -403 }))
|
||||
.mockResolvedValueOnce(
|
||||
uploadResponse({ retCode: -9801, retMsg: 'temporary storage rejected' }),
|
||||
);
|
||||
await expect(
|
||||
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
|
||||
).rejects.toThrow(/code=-9801/);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
|
||||
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
|
||||
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
|
||||
const staged = await vi.mocked(stageMod.stageSourceToDisk).mock.results.at(-1)!.value;
|
||||
expect(staged.cleanup).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('retains temporary mode when the successful retry omits its storage type', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(uploadResponse({ retCode: -403 }))
|
||||
.mockResolvedValueOnce(uploadResponse({ fileId: 'temp', boolFileExist: true }));
|
||||
const api = new GroupFileApi(bridge as any);
|
||||
const publish = vi.spyOn(api, 'publish').mockResolvedValue();
|
||||
await expect(api.upload(12345, '/path/file.bin')).resolves.toEqual({
|
||||
fileId: 'temp',
|
||||
busId: 104,
|
||||
});
|
||||
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'temp', 104);
|
||||
});
|
||||
|
||||
it('rejects an unknown server storage type before bytes or publication', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(
|
||||
uploadResponse({ fileId: 'bad', busId: 777, boolFileExist: true }),
|
||||
);
|
||||
await expect(
|
||||
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
|
||||
).rejects.toThrow(/unsupported storage type: 777/);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
|
||||
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
|
||||
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ scope: 'group', groupId: 12345, expected: 104 },
|
||||
{ scope: 'group', groupId: 54321, expected: 102 },
|
||||
{ scope: 'private', groupId: undefined, expected: 102 },
|
||||
] as const)(
|
||||
'scopes cached storage to the target group for download and reuse (%j)',
|
||||
async ({ scope, groupId, expected }) => {
|
||||
const bridge = mockBridge();
|
||||
bridge.recallUploadedFile.mockReturnValue({
|
||||
fileId: 'temp',
|
||||
scope,
|
||||
groupId,
|
||||
busId: 104,
|
||||
});
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(
|
||||
packResponse(
|
||||
protobuf_encode<OidbBase<OidbGroupFileResp>>({
|
||||
body: {
|
||||
download: {
|
||||
downloadDns: 'download.example.com',
|
||||
downloadUrl: new Uint8Array([1]),
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
const api = new GroupFileApi(bridge as any);
|
||||
await api.getUrl(12345, 'temp');
|
||||
await api.publish(12345, 'temp');
|
||||
const requests = bridge.sendRawPacket.mock.calls;
|
||||
expect(
|
||||
protobuf_decode<OidbBase<OidbGroupFileReq>>(requests[0]![1]).body?.download?.busId,
|
||||
).toBe(expected);
|
||||
expect(
|
||||
protobuf_decode<OidbBase<OidbGroupSendFileReq>>(requests[1]![1]).body?.body?.info
|
||||
?.busiType,
|
||||
).toBe(expected);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([{ retCode: -403 }, { fileId: 'temp', busId: 104, boolFileExist: true }])(
|
||||
'rejects a disallowed temporary upload before transferring bytes or publishing (%j)',
|
||||
async (response) => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(uploadResponse(response));
|
||||
await expect(
|
||||
new GroupFileApi(bridge as any).upload(
|
||||
12345,
|
||||
'/path/file.bin',
|
||||
'',
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
{ allowTemporary: false },
|
||||
),
|
||||
).rejects.toThrow(/temporary group files.*only file or image/i);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
|
||||
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
|
||||
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('upload publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => {
|
||||
// Reproduces the bug report: OIDB upload + highway PUT alone only
|
||||
// stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB
|
||||
@@ -287,7 +465,7 @@ describe('apis/group-file', () => {
|
||||
expect(publishSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('upload returns success even when the chat post fails (file is still uploaded)', async () => {
|
||||
it('upload reports chat publication failure while retaining the completed file identity', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(
|
||||
packResponse(
|
||||
@@ -297,14 +475,64 @@ describe('apis/group-file', () => {
|
||||
),
|
||||
);
|
||||
const api = new GroupFileApi(bridge as any);
|
||||
const publishSpy = vi
|
||||
.spyOn(api, 'publish')
|
||||
.mockRejectedValueOnce(new Error('message rejected'));
|
||||
const out = await api.upload(12345, '/path/file.bin');
|
||||
expect(out).toEqual({ fileId: 'fid-tolerant' });
|
||||
const cause = new Error('message rejected');
|
||||
const publishSpy = vi.spyOn(api, 'publish').mockRejectedValueOnce(cause);
|
||||
await expect(api.upload(12345, '/path/file.bin')).rejects.toMatchObject({
|
||||
message:
|
||||
'group file uploaded (fileId=fid-tolerant) but chat post failed: message rejected',
|
||||
cause,
|
||||
});
|
||||
expect(publishSpy).toHaveBeenCalledOnce();
|
||||
const staged = await vi.mocked(stageMod.stageSourceToDisk).mock.results.at(-1)!.value;
|
||||
expect(staged.cleanup).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
'publishes only after the upload is confirmed (confirmed=%s)',
|
||||
async (confirmed) => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(
|
||||
packResponse(
|
||||
protobuf_encode<OidbBase<OidbGroupFileResp>>({
|
||||
body: {
|
||||
upload: {
|
||||
fileId: 'fid-confirm',
|
||||
uploadIp: '127.0.0.1',
|
||||
uploadPort: 443,
|
||||
fileKey: new Uint8Array([1]),
|
||||
checkKey: new Uint8Array([2]),
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
const api = new GroupFileApi(bridge as any);
|
||||
const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue();
|
||||
const failure = new Error('highway upload transport failed; current chunk unconfirmed');
|
||||
vi.mocked(highwayClient.uploadHighwayHttp).mockImplementationOnce(async () => {
|
||||
expect(publishSpy).not.toHaveBeenCalled();
|
||||
|
||||
if (!confirmed) {
|
||||
throw failure;
|
||||
}
|
||||
});
|
||||
const upload = api.upload(12345, 'base64://AQID', 'confirmed.txt');
|
||||
|
||||
if (confirmed) {
|
||||
await expect(upload).resolves.toEqual({ fileId: 'fid-confirm', busId: 102 });
|
||||
expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm', 102);
|
||||
} else {
|
||||
await expect(upload).rejects.toBe(failure);
|
||||
expect(publishSpy).not.toHaveBeenCalled();
|
||||
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
|
||||
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
|
||||
},
|
||||
);
|
||||
|
||||
it('upload caches the upload metadata for later resend by file_id', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(
|
||||
|
||||
@@ -352,12 +352,12 @@ describe('apis/profile', () => {
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(
|
||||
protobuf_encode<OidbBase<Oidb0xe17Resp>>({
|
||||
body: {
|
||||
jsonBody: JSON.stringify({
|
||||
rpt_block_list: [{ uin: 10001 }, { uin: 10002 }],
|
||||
}),
|
||||
} as any,
|
||||
protobuf_encode<Oidb0xe17Resp>({
|
||||
jsonBody: JSON.stringify({
|
||||
ActionStatus: 'OK',
|
||||
ErrorCode: 0,
|
||||
rpt_block_list: [{ uin: 10001 }, { uin: 10002 }],
|
||||
}),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
214
packages/core/tests/actions/qzone-public.test.ts
Normal file
214
packages/core/tests/actions/qzone-public.test.ts
Normal file
@@ -0,0 +1,214 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import * as qzonePublic from '@snowluma/protocol/web/qzone-public';
|
||||
import { QzoneApi } from '../../src/bridge/apis/qzone';
|
||||
import { mockApiHub, mockBridge } from './_helpers';
|
||||
|
||||
const cookies = { p_skey: 'PSK' };
|
||||
const feed = {
|
||||
cell_common: { union_id: { feed_id: 'opaque-id' } },
|
||||
cell_feed_transfer: { future: true },
|
||||
};
|
||||
const comment = { id: 'comment-id', user: { uid: 'commenter' }, unknown: [1, 2] };
|
||||
const reply = { id: 'reply-id', user: { uid: 'recipient' } };
|
||||
const content = [{ type: 0, content: 'text', future: { enabled: true } }];
|
||||
const user = { uin: '10001', uid: 'self-uid', nick: 'self-nick' };
|
||||
const result = { feeds: [], has_more: false, next_cursor: null, unknown: { preserved: true } };
|
||||
|
||||
function makeApi() {
|
||||
const getCookies = vi.fn().mockResolvedValue(cookies);
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
return { api: new QzoneApi(bridge as never), bridge, getCookies };
|
||||
}
|
||||
|
||||
const cases = [
|
||||
{
|
||||
method: 'getQzoneHomeFeeds',
|
||||
invoke: (api: QzoneApi) => api.getHomeFeeds(20002, 'cursor'),
|
||||
args: [cookies, '10001', '20002', 'cursor'],
|
||||
},
|
||||
{
|
||||
method: 'getQzonePublicCapabilities',
|
||||
invoke: (api: QzoneApi) => api.getPublicCapabilities(),
|
||||
args: [cookies, '10001'],
|
||||
},
|
||||
{
|
||||
method: 'getQzonePublicFeeds',
|
||||
invoke: (api: QzoneApi) => api.getPublicFeeds('cursor'),
|
||||
args: [cookies, '10001', 'cursor'],
|
||||
},
|
||||
{
|
||||
method: 'getQzonePublicFeedDetail',
|
||||
invoke: (api: QzoneApi) => api.getPublicFeedDetail(feed),
|
||||
args: [cookies, feed],
|
||||
},
|
||||
{
|
||||
method: 'getQzonePublicComments',
|
||||
invoke: (api: QzoneApi) => api.getPublicComments(feed, 'cursor'),
|
||||
args: [cookies, feed, 'cursor'],
|
||||
},
|
||||
{
|
||||
method: 'getQzonePublicReplies',
|
||||
invoke: (api: QzoneApi) => api.getPublicReplies(feed, comment, 'cursor', 5),
|
||||
args: [cookies, feed, comment, 'cursor', 5],
|
||||
},
|
||||
{
|
||||
method: 'setQzonePublicUpvote',
|
||||
invoke: (api: QzoneApi) => api.setPublicUpvote(feed, false),
|
||||
args: [cookies, feed, false],
|
||||
},
|
||||
{
|
||||
method: 'setQzonePublicLike',
|
||||
invoke: (api: QzoneApi) => api.setPublicLike(feed, false),
|
||||
args: [cookies, feed, false],
|
||||
},
|
||||
{
|
||||
method: 'setQzonePublicCommentLike',
|
||||
invoke: (api: QzoneApi) => api.setPublicCommentLike(feed, comment, false, reply),
|
||||
args: [cookies, feed, comment, false, reply],
|
||||
},
|
||||
{
|
||||
method: 'commentQzonePublicFeed',
|
||||
invoke: (api: QzoneApi) => api.commentPublicFeed(feed, content),
|
||||
args: [cookies, feed, user, content],
|
||||
},
|
||||
{
|
||||
method: 'replyQzonePublicFeed',
|
||||
invoke: (api: QzoneApi) => api.replyPublicFeed(feed, comment, content, reply),
|
||||
args: [cookies, feed, user, comment, content, reply],
|
||||
},
|
||||
{
|
||||
method: 'deleteQzonePublicComment',
|
||||
invoke: (api: QzoneApi) => api.deletePublicComment(feed, comment),
|
||||
args: [cookies, feed, comment],
|
||||
},
|
||||
{
|
||||
method: 'deleteQzonePublicReply',
|
||||
invoke: (api: QzoneApi) => api.deletePublicReply(feed, comment, reply),
|
||||
args: [cookies, feed, comment, reply],
|
||||
},
|
||||
{
|
||||
method: 'setQzonePublicFollow',
|
||||
invoke: (api: QzoneApi) => api.setPublicFollow(feed, false),
|
||||
args: [cookies, feed, false],
|
||||
},
|
||||
{
|
||||
method: 'forwardQzonePublicFeed',
|
||||
invoke: (api: QzoneApi) => api.forwardPublicFeed(feed, 'reason'),
|
||||
args: [cookies, feed, 'reason'],
|
||||
},
|
||||
] as const;
|
||||
|
||||
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: '所有人可见' };
|
||||
const request = vi.spyOn(qzonePublic, 'getQzoneShareArk').mockResolvedValue(card);
|
||||
expect(await api.getShareArk(feed)).toBe(card);
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(request).toHaveBeenCalledExactlyOnceWith(cookies, feed);
|
||||
request.mockRejectedValueOnce(new Error('share denied'));
|
||||
await expect(api.getShareArk(feed)).rejects.toThrow('share denied');
|
||||
});
|
||||
|
||||
it.each(cases)(
|
||||
'$method uses current-account cookies and preserves upstream objects',
|
||||
async ({ method, invoke, args }) => {
|
||||
const { api, getCookies } = makeApi();
|
||||
const request = vi.spyOn(qzonePublic, method).mockResolvedValue(result);
|
||||
|
||||
expect(await invoke(api)).toBe(result);
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(request).toHaveBeenCalledExactlyOnceWith(...args);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(cases)(
|
||||
'$method propagates cookie and upstream failures without replay',
|
||||
async ({ method, invoke }) => {
|
||||
const { api, getCookies } = makeApi();
|
||||
const request = vi
|
||||
.spyOn(qzonePublic, method)
|
||||
.mockRejectedValue(new Error('upstream denied'));
|
||||
|
||||
await expect(invoke(api)).rejects.toThrow('upstream denied');
|
||||
getCookies.mockRejectedValueOnce(new Error('cookie failure'));
|
||||
await expect(invoke(api)).rejects.toThrow('cookie failure');
|
||||
expect(request).toHaveBeenCalledTimes(1);
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps documented defaults and omits an optional reply target', async () => {
|
||||
const { api } = makeApi();
|
||||
const feeds = vi.spyOn(qzonePublic, 'getQzonePublicFeeds').mockResolvedValue(result);
|
||||
const replies = vi.spyOn(qzonePublic, 'getQzonePublicReplies').mockResolvedValue(result);
|
||||
const upvote = vi.spyOn(qzonePublic, 'setQzonePublicUpvote').mockResolvedValue(result);
|
||||
const like = vi.spyOn(qzonePublic, 'setQzonePublicLike').mockResolvedValue(result);
|
||||
const commentLike = vi
|
||||
.spyOn(qzonePublic, 'setQzonePublicCommentLike')
|
||||
.mockResolvedValue(result);
|
||||
const follow = vi.spyOn(qzonePublic, 'setQzonePublicFollow').mockResolvedValue(result);
|
||||
const forward = vi.spyOn(qzonePublic, 'forwardQzonePublicFeed').mockResolvedValue(result);
|
||||
const replyRequest = vi
|
||||
.spyOn(qzonePublic, 'replyQzonePublicFeed')
|
||||
.mockResolvedValue(result);
|
||||
|
||||
await api.getPublicFeeds();
|
||||
await api.getPublicReplies(feed, comment);
|
||||
await api.setPublicUpvote(feed);
|
||||
await api.setPublicLike(feed);
|
||||
await api.setPublicCommentLike(feed, comment);
|
||||
await api.setPublicFollow(feed);
|
||||
await api.forwardPublicFeed(feed);
|
||||
await api.replyPublicFeed(feed, comment, 'text');
|
||||
|
||||
expect(feeds).toHaveBeenCalledWith(cookies, '10001', undefined);
|
||||
expect(replies).toHaveBeenCalledWith(cookies, feed, comment, '', 20);
|
||||
expect(upvote).toHaveBeenCalledWith(cookies, feed, true);
|
||||
expect(like).toHaveBeenCalledWith(cookies, feed, true);
|
||||
expect(commentLike).toHaveBeenCalledWith(cookies, feed, comment, true, undefined);
|
||||
expect(follow).toHaveBeenCalledWith(cookies, feed, true);
|
||||
expect(forward).toHaveBeenCalledWith(cookies, feed, '');
|
||||
expect(replyRequest).toHaveBeenCalledWith(cookies, feed, user, comment, 'text', undefined);
|
||||
});
|
||||
|
||||
it('binds comment authors to the current account even when its uid is unavailable', async () => {
|
||||
const { api, bridge } = makeApi();
|
||||
Object.assign(bridge.identity, { selfUid: undefined });
|
||||
const request = vi.spyOn(qzonePublic, 'commentQzonePublicFeed').mockResolvedValue(result);
|
||||
|
||||
await api.commentPublicFeed(feed, 'text');
|
||||
expect(request).toHaveBeenCalledWith(
|
||||
cookies,
|
||||
feed,
|
||||
{ uin: '10001', uid: '', nick: 'self-nick' },
|
||||
'text',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,61 @@ describe('apis/qzone', () => {
|
||||
return { bridge, getCookies, fetchSpy };
|
||||
}
|
||||
|
||||
it.each([undefined, 20002])(
|
||||
'getProfile reads owner %s with the current account credentials',
|
||||
async (targetUin) => {
|
||||
const { bridge, getCookies } = bridgeWithWeb();
|
||||
const profile = { name: 'My space', description: 'Notes' };
|
||||
const getProfile = vi.spyOn(qzoneWeb, 'getQzoneProfile').mockResolvedValue(profile);
|
||||
|
||||
expect(await new QzoneApi(bridge as never).getProfile(targetUin)).toEqual(profile);
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(getProfile).toHaveBeenCalledWith(
|
||||
{ p_skey: 'PSK' },
|
||||
'10001',
|
||||
targetUin?.toString(),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('getProfile propagates cookie and protocol failures', async () => {
|
||||
const { bridge, getCookies } = bridgeWithWeb();
|
||||
const api = new QzoneApi(bridge as never);
|
||||
const getProfile = vi
|
||||
.spyOn(qzoneWeb, 'getQzoneProfile')
|
||||
.mockRejectedValue(new Error('denied'));
|
||||
|
||||
await expect(api.getProfile(20002)).rejects.toThrow('denied');
|
||||
getCookies.mockRejectedValueOnce(new Error('cookie failure'));
|
||||
await expect(api.getProfile()).rejects.toThrow('cookie failure');
|
||||
expect(getProfile).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each([{ name: 'New name' }, { description: '' }, { name: '', description: 'New notes' }])(
|
||||
'setProfile writes only the supplied fields to the current account (%j)',
|
||||
async (profile) => {
|
||||
const { bridge, getCookies } = bridgeWithWeb();
|
||||
const setProfile = vi.spyOn(qzoneWeb, 'setQzoneProfile').mockResolvedValue();
|
||||
|
||||
await new QzoneApi(bridge as never).setProfile(profile);
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(setProfile).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', profile);
|
||||
},
|
||||
);
|
||||
|
||||
it('setProfile propagates cookie and protocol failures', async () => {
|
||||
const { bridge, getCookies } = bridgeWithWeb();
|
||||
const api = new QzoneApi(bridge as never);
|
||||
const setProfile = vi
|
||||
.spyOn(qzoneWeb, 'setQzoneProfile')
|
||||
.mockRejectedValue(new Error('captcha required'));
|
||||
|
||||
await expect(api.setProfile({ name: 'New name' })).rejects.toThrow('captcha required');
|
||||
getCookies.mockRejectedValueOnce(new Error('cookie failure'));
|
||||
await expect(api.setProfile({ description: 'Notes' })).rejects.toThrow('cookie failure');
|
||||
expect(setProfile).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each([undefined, 20002])(
|
||||
'getMsgDetail uses current-account credentials for owner %s',
|
||||
async (targetUin) => {
|
||||
@@ -77,10 +132,18 @@ describe('apis/qzone', () => {
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const feedsSpy = vi
|
||||
.spyOn(qzoneWeb, 'getQzoneFeeds')
|
||||
.mockResolvedValue({ feeds: [], has_more: false });
|
||||
.mockResolvedValue({ feeds: [], has_more: false, next_cursor: null });
|
||||
await new QzoneApi(bridge as never).getFeeds(3, 20);
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(feedsSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 3, 20);
|
||||
expect(feedsSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 3, 20, undefined);
|
||||
await new QzoneApi(bridge as never).getFeeds(1, 20, 'opaque-cursor');
|
||||
expect(feedsSpy).toHaveBeenLastCalledWith(
|
||||
{ p_skey: 'PSK' },
|
||||
'10001',
|
||||
1,
|
||||
20,
|
||||
'opaque-cursor',
|
||||
);
|
||||
});
|
||||
|
||||
it('uploadImageFromSource uploads from file:// http:// base64:// and returns richval + url', async () => {
|
||||
@@ -290,4 +353,53 @@ describe('apis/qzone', () => {
|
||||
richval,
|
||||
);
|
||||
});
|
||||
|
||||
it.each([undefined, 20002])(
|
||||
'routes replies with the account cookies and post owner (%s)',
|
||||
async (targetUin) => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const target = {
|
||||
commentId: '0',
|
||||
commentUin: '30003',
|
||||
replyTo: { uin: '40004', name: 'Reader' },
|
||||
};
|
||||
const result = { comment_id: '8', parent_comment_id: '0', parent_comment_uin: 30003 };
|
||||
const replySpy = vi.spyOn(qzoneWeb, 'replyQzoneComment').mockResolvedValue(result);
|
||||
const commentSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg');
|
||||
|
||||
const out = await new QzoneApi(bridge as never).comment(
|
||||
'TIDX',
|
||||
'Reply',
|
||||
targetUin,
|
||||
undefined,
|
||||
undefined,
|
||||
target,
|
||||
);
|
||||
|
||||
expect(out).toEqual(result);
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(replySpy).toHaveBeenCalledWith(
|
||||
{ p_skey: 'PSK' },
|
||||
'10001',
|
||||
String(targetUin ?? 10001),
|
||||
'TIDX',
|
||||
'Reply',
|
||||
target,
|
||||
);
|
||||
expect(commentSpy).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('rejects reply images before acquiring cookies or sending', async () => {
|
||||
const getCookies = vi.fn();
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
await expect(
|
||||
new QzoneApi(bridge as never).comment('TIDX', 'Reply', undefined, 1, 'URL', {
|
||||
commentId: '0',
|
||||
commentUin: '30003',
|
||||
}),
|
||||
).rejects.toThrow('images are not supported');
|
||||
expect(getCookies).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
234
packages/core/tests/bridge-client-message.test.ts
Normal file
234
packages/core/tests/bridge-client-message.test.ts
Normal file
@@ -0,0 +1,234 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { CLIENT_MESSAGE_RECEIPT_CMD, type PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { SendMessageResponse } from '@snowluma/proto-defs/action';
|
||||
import type { SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { Bridge } from '../src/bridge/bridge';
|
||||
|
||||
const bridges: Bridge[] = [];
|
||||
const timestamp = 1_700_000_000;
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((accept) => {
|
||||
resolve = accept;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(bridges.splice(0).map((bridge) => bridge.dispose()));
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function packet(): PacketInfo {
|
||||
const uid = Buffer.from('u_test_peer');
|
||||
const header = Buffer.alloc(8);
|
||||
header[0] = 1;
|
||||
header[1] = uid.length;
|
||||
header.writeUInt32LE(9, 4);
|
||||
return {
|
||||
pid: 1234,
|
||||
uin: '10001',
|
||||
source: 'client-message',
|
||||
serviceCmd: CLIENT_MESSAGE_RECEIPT_CMD,
|
||||
seqId: 42,
|
||||
retCode: 0,
|
||||
fromClient: false,
|
||||
body: Buffer.concat([
|
||||
header,
|
||||
uid,
|
||||
protobuf_encode<SendMessageResponse>({ privateSequence: 87, timestamp1: timestamp }),
|
||||
]),
|
||||
};
|
||||
}
|
||||
|
||||
function response(): SendPacketResult {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(
|
||||
protobuf_encode<SsoGetC2cMsgResponse>({
|
||||
friendUid: 'u_test_peer',
|
||||
messages: [
|
||||
{
|
||||
responseHead: {
|
||||
fromUin: 10001,
|
||||
fromUid: 'u_test_self',
|
||||
toUin: 20002,
|
||||
toUid: 'u_test_peer',
|
||||
},
|
||||
contentHead: {
|
||||
msgType: 166,
|
||||
sequence: 9,
|
||||
ntMsgSeq: 87,
|
||||
timestamp,
|
||||
msgId: 123456,
|
||||
},
|
||||
body: { richText: { elems: [{ text: { str: 'hello' } }] } },
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
async function setup() {
|
||||
const bridge = new Bridge(IdentityService.memory('10001'));
|
||||
bridges.push(bridge);
|
||||
vi.spyOn(bridge.apis.contacts, 'fetchFriendList').mockResolvedValue([
|
||||
{ uin: 10001, uid: 'u_test_self', nickname: 'self', remark: '' },
|
||||
]);
|
||||
vi.spyOn(bridge.apis.contacts, 'fetchGroupList').mockResolvedValue([]);
|
||||
const sendPacket = vi.fn<PacketSender['sendPacket']>(async () => response());
|
||||
const sender = { sendPacket };
|
||||
bridge.bindPid(1234, sender);
|
||||
await bridge.whenRosterWarmupSettled();
|
||||
const received = vi.fn();
|
||||
bridge.events.on('friend_message', received);
|
||||
return { bridge, sendPacket, sender, received };
|
||||
}
|
||||
|
||||
describe('Bridge client message recovery', () => {
|
||||
it('does not retry a delayed lookup on a detached or replacement connection', async () => {
|
||||
const ctx = await setup();
|
||||
vi.useFakeTimers();
|
||||
ctx.sendPacket.mockResolvedValue({
|
||||
...response(),
|
||||
responseData: Buffer.from(
|
||||
protobuf_encode<SsoGetC2cMsgResponse>({
|
||||
result: 100000301,
|
||||
friendUid: 'u_test_peer',
|
||||
}),
|
||||
),
|
||||
});
|
||||
const work = ctx.bridge.onPacket(packet());
|
||||
const rejected = expect(work).rejects.toThrow('inactive connection');
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.sendPacket).toHaveBeenCalledOnce();
|
||||
ctx.bridge.detachPid(1234);
|
||||
const replacement = vi.fn<PacketSender['sendPacket']>();
|
||||
ctx.bridge.bindPid(1234, { sendPacket: replacement });
|
||||
await vi.runAllTimersAsync();
|
||||
await rejected;
|
||||
expect(ctx.sendPacket).toHaveBeenCalledOnce();
|
||||
expect(replacement).not.toHaveBeenCalled();
|
||||
expect(ctx.received).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('dispatches confirmed content through the normal event pipeline', async () => {
|
||||
const ctx = await setup();
|
||||
await ctx.bridge.onPacket(packet());
|
||||
expect(ctx.sendPacket).toHaveBeenCalledOnce();
|
||||
expect(ctx.received).toHaveBeenCalledOnce();
|
||||
expect(ctx.received).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: 'friend_message',
|
||||
selfUin: 10001,
|
||||
senderUin: 10001,
|
||||
peerUin: 20002,
|
||||
ntMsgSeq: 87,
|
||||
clientSeq: 9,
|
||||
elements: [{ type: 'text', text: 'hello' }],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not treat an ordinary packet with the same command as a receipt', async () => {
|
||||
const ctx = await setup();
|
||||
const ordinary = packet();
|
||||
delete ordinary.source;
|
||||
await ctx.bridge.onPacket(ordinary);
|
||||
expect(ctx.sendPacket).not.toHaveBeenCalled();
|
||||
expect(ctx.received).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shares an in-flight lookup across repeated receipts and ordinary PID observations', async () => {
|
||||
const ctx = await setup();
|
||||
const result = deferred<SendPacketResult>();
|
||||
const started = deferred<void>();
|
||||
ctx.sendPacket.mockImplementation(() => {
|
||||
started.resolve();
|
||||
return result.promise;
|
||||
});
|
||||
const first = ctx.bridge.onPacket(packet());
|
||||
await started.promise;
|
||||
ctx.bridge.bindPid(1234, ctx.sender);
|
||||
const duplicate = ctx.bridge.onPacket(packet());
|
||||
await Promise.resolve();
|
||||
result.resolve(response());
|
||||
await Promise.all([first, duplicate]);
|
||||
expect(ctx.sendPacket).toHaveBeenCalledOnce();
|
||||
expect(ctx.received).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it.each(['detach', 'replace', 'reattach', 'dispose'] as const)(
|
||||
'rejects a lookup completed after %s',
|
||||
async (action) => {
|
||||
const ctx = await setup();
|
||||
const result = deferred<SendPacketResult>();
|
||||
const started = deferred<void>();
|
||||
ctx.sendPacket.mockImplementation(() => {
|
||||
started.resolve();
|
||||
return result.promise;
|
||||
});
|
||||
const work = ctx.bridge.onPacket(packet());
|
||||
const rejected = expect(work).rejects.toThrow('inactive connection');
|
||||
await started.promise;
|
||||
let disposal: Promise<void> | undefined;
|
||||
|
||||
if (action === 'dispose') {
|
||||
disposal = ctx.bridge.dispose();
|
||||
} else if (action === 'replace') {
|
||||
ctx.bridge.bindPid(1234, { sendPacket: vi.fn() });
|
||||
} else {
|
||||
ctx.bridge.detachPid(1234);
|
||||
|
||||
if (action === 'reattach') {
|
||||
ctx.bridge.bindPid(1234, ctx.sender);
|
||||
}
|
||||
}
|
||||
|
||||
result.resolve(response());
|
||||
await rejected;
|
||||
await disposal;
|
||||
expect(ctx.received).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('queries the originating connection even when another process is active', async () => {
|
||||
const ctx = await setup();
|
||||
const other = { sendPacket: vi.fn<PacketSender['sendPacket']>() };
|
||||
ctx.bridge.bindPid(4321, other);
|
||||
await ctx.bridge.onPacket(packet());
|
||||
expect(ctx.sendPacket).toHaveBeenCalledOnce();
|
||||
expect(other.sendPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects unavailable, detached and wrong-account receipts before querying', async () => {
|
||||
const ctx = await setup();
|
||||
await expect(ctx.bridge.onPacket({ ...packet(), retCode: -1 })).rejects.toThrow(
|
||||
'unavailable',
|
||||
);
|
||||
await expect(ctx.bridge.onPacket({ ...packet(), uin: '20002' })).rejects.toThrow('account');
|
||||
ctx.bridge.detachPid(1234);
|
||||
await expect(ctx.bridge.onPacket(packet())).rejects.toThrow('inactive connection');
|
||||
expect(ctx.sendPacket).not.toHaveBeenCalled();
|
||||
expect(ctx.received).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('surfaces lookup failure and allows a later receipt to retry', async () => {
|
||||
const ctx = await setup();
|
||||
ctx.sendPacket.mockRejectedValueOnce(new Error('lookup failed'));
|
||||
await expect(ctx.bridge.onPacket(packet())).rejects.toThrow('lookup failed');
|
||||
expect(ctx.received).not.toHaveBeenCalled();
|
||||
await ctx.bridge.onPacket(packet());
|
||||
expect(ctx.sendPacket).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.received).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
81
packages/core/tests/bridge-contact-cache-lifecycle.test.ts
Normal file
81
packages/core/tests/bridge-contact-cache-lifecycle.test.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
|
||||
import { FetchRobotUinRanges } from '@snowluma/protocol/oidb-services/contacts/fetch-robot-uin-ranges';
|
||||
import { Bridge } from '../src/bridge/bridge';
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('Bridge contact cache lifecycle', () => {
|
||||
it('keeps contact lookups available to packets already draining during shutdown', async () => {
|
||||
vi.useFakeTimers();
|
||||
const bridge = new Bridge(IdentityService.memory('10001'));
|
||||
vi.spyOn(FetchRobotUinRanges, 'invoke').mockResolvedValue({ version: 1, ranges: [] });
|
||||
const load = vi
|
||||
.spyOn(FetchGroupMemberListPage, 'invoke')
|
||||
.mockResolvedValue({ members: [], token: '' });
|
||||
await bridge.apis.contacts.fetchGroupMemberList(42);
|
||||
let memberRead: Promise<unknown> | undefined;
|
||||
bridge.registerCmd('test.contact-cache', () => {
|
||||
memberRead = bridge.apis.contacts.fetchGroupMemberList(42);
|
||||
return [];
|
||||
});
|
||||
const packet = bridge.onPacket({
|
||||
pid: 1,
|
||||
uin: '10001',
|
||||
serviceCmd: 'test.contact-cache',
|
||||
seqId: 1,
|
||||
retCode: 0,
|
||||
fromClient: false,
|
||||
body: new Uint8Array(),
|
||||
});
|
||||
const closing = bridge.dispose();
|
||||
await packet;
|
||||
await expect(memberRead).resolves.toEqual([]);
|
||||
await closing;
|
||||
expect(load).toHaveBeenCalledOnce();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'releases member caches before identity closes, close failure=%s',
|
||||
async (fails) => {
|
||||
vi.useFakeTimers();
|
||||
const identity = IdentityService.memory('10001');
|
||||
const bridge = new Bridge(identity);
|
||||
vi.spyOn(FetchRobotUinRanges, 'invoke').mockResolvedValue({ version: 1, ranges: [] });
|
||||
const load = vi
|
||||
.spyOn(FetchGroupMemberListPage, 'invoke')
|
||||
.mockResolvedValue({ members: [], token: '' });
|
||||
await bridge.apis.contacts.fetchGroupMemberList(42);
|
||||
await bridge.apis.contacts.fetchGroupMemberList(42);
|
||||
expect(load).toHaveBeenCalledOnce();
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
|
||||
const originalClose = identity.close.bind(identity);
|
||||
vi.spyOn(identity, 'close').mockImplementation(async () => {
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
await originalClose();
|
||||
|
||||
if (fails) {
|
||||
throw new Error('identity close failed');
|
||||
}
|
||||
});
|
||||
const closing = bridge.dispose();
|
||||
expect(bridge.dispose()).toBe(closing);
|
||||
|
||||
if (fails) {
|
||||
await expect(closing).rejects.toThrow('identity close failed');
|
||||
} else {
|
||||
await closing;
|
||||
}
|
||||
|
||||
await expect(bridge.apis.contacts.fetchGroupMemberList(42)).rejects.toThrow('disposed');
|
||||
expect(load).toHaveBeenCalledOnce();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -115,6 +115,55 @@ describe('BridgeManager shutdown', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('reopening is not poisoned by an already-failed close', async () => {
|
||||
const failing = deferred();
|
||||
manager.onHookLogin(101, '10001', sender);
|
||||
vi.spyOn(manager.getBridge('10001')!.identity, 'close').mockReturnValue(failing.promise);
|
||||
manager.onPidDisconnected(101);
|
||||
failing.reject(new Error('close failed'));
|
||||
await nextTurn();
|
||||
|
||||
// The failed close stays in the bookkeeping (dispose still reports
|
||||
// it), but the reopening gate must absorb the rejection instead of
|
||||
// passing it down — a rejected gate would keep the identity DB of
|
||||
// every future session for this UIN closed until process restart.
|
||||
manager.onHookLogin(202, '10001', sender);
|
||||
const beforeOpen = vi.mocked(IdentityService.openForUin).mock.calls.at(-1)![2]!;
|
||||
await expect(beforeOpen).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('reopening waits for all closes to settle even when one of them fails', async () => {
|
||||
const failing = deferred();
|
||||
const slow = deferred();
|
||||
manager.onHookLogin(101, '10001', sender);
|
||||
vi.spyOn(manager.getBridge('10001')!.identity, 'close').mockReturnValue(failing.promise);
|
||||
manager.onPidDisconnected(101);
|
||||
manager.onHookLogin(202, '10001', sender);
|
||||
vi.spyOn(manager.getBridge('10001')!.identity, 'close').mockReturnValue(slow.promise);
|
||||
manager.onPidDisconnected(202);
|
||||
|
||||
failing.reject(new Error('close failed'));
|
||||
await nextTurn();
|
||||
|
||||
manager.onHookLogin(303, '10001', sender);
|
||||
const beforeOpen = vi.mocked(IdentityService.openForUin).mock.calls.at(-1)![2]!;
|
||||
let ready = false;
|
||||
const opening = beforeOpen.then(() => {
|
||||
ready = true;
|
||||
});
|
||||
|
||||
try {
|
||||
await nextTurn();
|
||||
// Still waiting for the pending close...
|
||||
expect(ready).toBe(false);
|
||||
} finally {
|
||||
slow.resolve();
|
||||
}
|
||||
|
||||
// ...and the already-failed close must not reject the gate.
|
||||
await opening;
|
||||
});
|
||||
|
||||
it('ignores late transport callbacks after shutdown starts', async () => {
|
||||
const shutdown = manager.dispose();
|
||||
manager.onHookLogin(101, '10001', sender);
|
||||
|
||||
@@ -2,7 +2,11 @@ import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { DatalineMsgBody, DatalineTextMsg } from '@snowluma/proto-defs/dataline';
|
||||
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
|
||||
import type {
|
||||
SendMessageRequest,
|
||||
SendMessageResponse,
|
||||
SendRichText,
|
||||
} from '@snowluma/proto-defs/action';
|
||||
import type { FileExtra } from '@snowluma/proto-defs/message';
|
||||
import { DATALINE_UIN_PHONE } from '@snowluma/protocol/dataline/device-contacts';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
@@ -10,6 +14,9 @@ import type { OidbOfflineFileFinalizeResp } from '@snowluma/proto-defs/oidb-acti
|
||||
|
||||
vi.mock('@snowluma/protocol/element-builder', () => ({
|
||||
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
|
||||
encodePrivateRichText: vi.fn(async () =>
|
||||
protobuf_encode<SendRichText>({ elems: [{ text: { str: 'stub media elem' } }] }),
|
||||
),
|
||||
}));
|
||||
|
||||
// Imported statically (not via `await import` inside each `it`) so the heavy
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { SendRichText } from '@snowluma/proto-defs/action';
|
||||
// Regression test for the c2c-vs-group businessType asymmetry that made
|
||||
// private-chat video / record sends bounce with `send private message
|
||||
// rejected: result=79`. The receive-side decoder
|
||||
@@ -22,15 +23,16 @@ vi.mock('@snowluma/protocol/highway/image-upload', () => ({
|
||||
uploadImageMsgInfo: vi.fn(async () => new Uint8Array([7, 8, 9])),
|
||||
}));
|
||||
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({
|
||||
uploadPttMsgInfo: vi.fn(async () => new Uint8Array([4, 5, 6])),
|
||||
uploadPtt: vi.fn(async () => ({ msgInfo: new Uint8Array([4, 5, 6]) })),
|
||||
}));
|
||||
vi.mock('@snowluma/protocol/highway/video-upload', () => ({
|
||||
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array([1, 2, 3])),
|
||||
}));
|
||||
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { MsgInfo } from '@snowluma/proto-defs/element';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import { type bytes, type pb, protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { GroupFileExtra, MsgInfo } from '@snowluma/proto-defs/element';
|
||||
import { buildSendElems, encodePrivateRichText } from '@snowluma/protocol/element-builder';
|
||||
import { uploadPtt } from '@snowluma/protocol/highway/ptt-upload';
|
||||
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
|
||||
import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload';
|
||||
import { uploadVideoMsgInfo } from '@snowluma/protocol/highway/video-upload';
|
||||
@@ -372,6 +374,27 @@ describe('element-builder / all-message validation preflight', () => {
|
||||
});
|
||||
|
||||
describe('element-builder / file element is no longer carried in elems[]', () => {
|
||||
it.each([12345, 54321])(
|
||||
'preserves temporary storage only in a matching group forward (%s)',
|
||||
async (cachedGroupId) => {
|
||||
const bridge = {
|
||||
recallUploadedFile: vi.fn(() => ({
|
||||
scope: 'group',
|
||||
groupId: cachedGroupId,
|
||||
busId: 104,
|
||||
fileName: 'doc.pdf',
|
||||
fileSize: 3,
|
||||
})),
|
||||
} as any;
|
||||
const [elem] = await buildSendElems([{ type: 'file', fileId: 'temp' }], {
|
||||
bridge,
|
||||
groupId: 12345,
|
||||
forwardFake: true,
|
||||
});
|
||||
const extra = protobuf_decode<GroupFileExtra>(elem!.transElem!.elemValue!.subarray(3));
|
||||
expect(extra.inner?.info?.busId).toBe(cachedGroupId === 12345 ? 104 : 102);
|
||||
},
|
||||
);
|
||||
// Regression for the `result=79` class: previously the element-builder
|
||||
// emitted a `transElem(elemType=24, ...)` for `{type:'file'}` segments
|
||||
// and the QQ-NT server rejected the outgoing PbSendMsg with that wire
|
||||
@@ -569,3 +592,33 @@ describe('element-builder / forward preview', () => {
|
||||
).rejects.toBeInstanceOf(MessageElementValidationError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('private voice compatibility', () => {
|
||||
const context = { bridge: fakeBridge, userUid: 'u_peer', scene: 'direct-private' } as const;
|
||||
const record = { type: 'record', url: 'voice.amr' } as const;
|
||||
const modern = Uint8Array.of(4, 5, 6);
|
||||
|
||||
it('keeps all modern clips when one legacy voice slot cannot represent the message', async () => {
|
||||
const compat = protobuf_encode<{ ptt?: pb<4, bytes> }>({ ptt: Uint8Array.of(8, 4) });
|
||||
vi.mocked(uploadPtt)
|
||||
.mockResolvedValueOnce({ msgInfo: modern, compatQMsg: compat })
|
||||
.mockResolvedValueOnce({ msgInfo: modern, compatQMsg: compat });
|
||||
const rich = await encodePrivateRichText([record, record], context);
|
||||
expect(protobuf_decode<{ ptt?: pb<4, bytes> }>(rich).ptt).toBeNull();
|
||||
expect(protobuf_decode<SendRichText>(rich).elems).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('sends modern voice when no compatibility data is available and rejects malformed data', async () => {
|
||||
vi.mocked(uploadPtt).mockResolvedValueOnce({ msgInfo: modern });
|
||||
expect(
|
||||
protobuf_decode<SendRichText>(await encodePrivateRichText([record], context)).elems,
|
||||
).toHaveLength(1);
|
||||
vi.mocked(uploadPtt).mockResolvedValueOnce({
|
||||
msgInfo: modern,
|
||||
compatQMsg: Uint8Array.of(0x12, 0),
|
||||
});
|
||||
await expect(encodePrivateRichText([record], context)).rejects.toThrow(
|
||||
'incomplete playback information',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
14
packages/core/tests/fixtures/issue-614-private-voice-upload.hex
vendored
Normal file
14
packages/core/tests/fixtures/issue-614-private-voice-upload.hex
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
08ed241064180022ef0412ec0432b9020af6010af3010a7d08fb3d122030303030303030303030303030303030303030
|
||||
303030303030303030303030301a28303030303030303030303030303030303030303030303030303030303030303030
|
||||
30303030303030222430303030303030303030303030303030303030303030303030303030303030302e616d722a0408
|
||||
032001400312637878787878787878787878787878787878787878787878787878787878787878787878787878787878
|
||||
787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878
|
||||
7878787878787878787818012081808080012881800138fa0a123e0a0612047465737412001a3208818080800110012a
|
||||
22081e121e0505050505050505050505050505050505050505050505050505050505055a040800380042ad02122baa02
|
||||
289a0125aa0322081e121e05050505050505050505050505050505050505050505050505050505050522fd0108041081
|
||||
808080011a97017878787878787878787878787878787878787878787878787878787878787878787878787878787878
|
||||
787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878
|
||||
787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878
|
||||
78787878787878787878787878782210000000000000000000000000000000002a243030303030303030303030303030
|
||||
3030303030303030303030303030303030302e616d7230fb3d3a16000000000000000000000000000000000000000000
|
||||
005801980103e80101
|
||||
@@ -208,6 +208,56 @@ describe('MessageApi history pagination', () => {
|
||||
expect(result.map((message) => message.ntMsgSeq)).toEqual([63213, 63214, 63215]);
|
||||
});
|
||||
|
||||
it('splits a 200-message private history request into bounded pages', async () => {
|
||||
mockC2cRoamFetch.mockImplementation(
|
||||
async (_sender, _identity, _self, _friend, time, count) => ({
|
||||
messages: Array.from({ length: count }, (_, index) => ({
|
||||
...gm(time - index),
|
||||
kind: 'friend_message',
|
||||
ntMsgSeq: time - index,
|
||||
})),
|
||||
cursor: { time: time - count, random: 1 },
|
||||
isComplete: false,
|
||||
}),
|
||||
);
|
||||
const result = await runHistory(
|
||||
new MessageApi(ctx).getC2cLatestHistory('u_friend', 200, 10001, 1000),
|
||||
);
|
||||
expect(result).toHaveLength(200);
|
||||
expect(mockC2cRoamFetch.mock.calls.map((call) => call[5])).toEqual([100, 100]);
|
||||
expect(result.map((message) => message.ntMsgSeq)).toEqual(
|
||||
Array.from({ length: 200 }, (_, index) => 801 + index),
|
||||
);
|
||||
});
|
||||
|
||||
it('honors completion even when the last page still includes a cursor', async () => {
|
||||
mockC2cRoamFetch.mockResolvedValue({
|
||||
messages: [{ ...gm(1), kind: 'friend_message', ntMsgSeq: 1 }],
|
||||
cursor: { time: 100, random: 2 },
|
||||
isComplete: true,
|
||||
});
|
||||
const result = await runHistory(
|
||||
new MessageApi(ctx).getC2cLatestHistory('u_friend', 20, 10001, 1000),
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(mockC2cRoamFetch).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('does not return partial history after a later request fails', async () => {
|
||||
mockC2cRoamFetch
|
||||
.mockResolvedValueOnce({
|
||||
messages: [{ ...gm(1), kind: 'friend_message', ntMsgSeq: 1 }],
|
||||
cursor: { time: 100, random: 2 },
|
||||
isComplete: false,
|
||||
})
|
||||
.mockRejectedValueOnce(new Error('SsoGetRoamMsg failed: result=123'));
|
||||
const assertion = expect(
|
||||
new MessageApi(ctx).getC2cLatestHistory('u_friend', 20, 10001, 1000),
|
||||
).rejects.toThrow('result=123');
|
||||
await vi.runAllTimersAsync();
|
||||
await assertion;
|
||||
});
|
||||
|
||||
it('rejects a stalled private roam cursor instead of returning a partial page', async () => {
|
||||
mockC2cRoamFetch.mockResolvedValue({
|
||||
cursor: { time: 1700000100, random: 0 },
|
||||
|
||||
@@ -15,8 +15,9 @@
|
||||
// 一连接,但仍全部成功。
|
||||
|
||||
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
|
||||
import type { HttpConn0x6FF501Response } from '@snowluma/proto-defs/highway';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { HttpConn0x6FF501Response, ReqDataHighwayHead } from '@snowluma/proto-defs/highway';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { unpackHighwayFrame } from '@snowluma/protocol/highway/utils';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
@@ -79,8 +80,14 @@ class FakeSocket extends EventEmitter {
|
||||
writable = true;
|
||||
posts = 0;
|
||||
headers: string[] = [];
|
||||
frames: Buffer[] = [];
|
||||
closeBeforeResponse = false;
|
||||
idleBeforeResponse = false;
|
||||
stallWrites = false;
|
||||
responseDelayMs = 0;
|
||||
connectFailure?: Error | 'timeout';
|
||||
private connectTimer?: ReturnType<typeof setTimeout>;
|
||||
private responseTimer?: ReturnType<typeof setTimeout>;
|
||||
private buf = Buffer.alloc(0);
|
||||
constructor(
|
||||
private readonly responseFrame: Buffer,
|
||||
@@ -102,6 +109,10 @@ class FakeSocket extends EventEmitter {
|
||||
}
|
||||
|
||||
write(data: unknown, cb?: (err?: Error) => void): boolean {
|
||||
if (this.stallWrites) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.destroyed || !this.writable) {
|
||||
const err = new Error('write after socket end');
|
||||
|
||||
@@ -141,14 +152,20 @@ class FakeSocket extends EventEmitter {
|
||||
}
|
||||
|
||||
this.headers.push(s.slice(0, he));
|
||||
this.frames.push(Buffer.from(this.buf.subarray(he + 4, total)));
|
||||
this.buf = this.buf.subarray(total);
|
||||
this.posts += 1;
|
||||
const thisPost = this.posts;
|
||||
setImmediate(() => {
|
||||
|
||||
const respond = () => {
|
||||
if (this.destroyed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.idleBeforeResponse) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (thisPost === this.failOnPost) {
|
||||
this.writable = false;
|
||||
this.readableEnded = true;
|
||||
@@ -157,6 +174,14 @@ class FakeSocket extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.closeBeforeResponse) {
|
||||
this.writable = false;
|
||||
this.readableEnded = true;
|
||||
this.emit('end');
|
||||
this.emit('close');
|
||||
return;
|
||||
}
|
||||
|
||||
if (thisPost === this.errorAfterPartialOnPost) {
|
||||
const full = httpWrap(this.responseFrame);
|
||||
this.emit('data', full.subarray(0, full.length - 3));
|
||||
@@ -187,12 +212,19 @@ class FakeSocket extends EventEmitter {
|
||||
this.emit('end');
|
||||
this.emit('close');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if (this.responseDelayMs > 0) {
|
||||
this.responseTimer = setTimeout(respond, this.responseDelayMs);
|
||||
} else {
|
||||
setImmediate(respond);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destroy() {
|
||||
clearTimeout(this.connectTimer);
|
||||
clearTimeout(this.responseTimer);
|
||||
this.destroyed = true;
|
||||
this.writable = false;
|
||||
}
|
||||
@@ -227,8 +259,8 @@ function highwayTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Highway');
|
||||
}
|
||||
|
||||
function makeBridge(): BridgeContext {
|
||||
return { identity: { uin: '10001' } as unknown } as unknown as BridgeContext;
|
||||
function makeBridge(uin = '10001'): BridgeContext {
|
||||
return { identity: { uin } as unknown } as unknown as BridgeContext;
|
||||
}
|
||||
|
||||
function makeSession(): HighwaySession {
|
||||
@@ -443,10 +475,11 @@ describe('fetchHighwaySession trace lifecycle', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Highway initial connection selection', () => {
|
||||
describe('Highway connection selection', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
setLogLevel(previousLogLevel);
|
||||
});
|
||||
|
||||
@@ -460,6 +493,201 @@ describe('Highway initial connection selection', () => {
|
||||
};
|
||||
}
|
||||
|
||||
it.each([1003, 1004])(
|
||||
'reaches the fourth candidate after three idle peers for command %i (#637)',
|
||||
async (commandId) => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS', '100');
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '5000');
|
||||
installFactory(() => {
|
||||
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
|
||||
socket.idleBeforeResponse =
|
||||
createConnectionMock.mock.lastCall?.[0].host !== '192.0.2.4';
|
||||
return socket;
|
||||
});
|
||||
const session = {
|
||||
...makeSession(),
|
||||
servers: Array.from({ length: 4 }, (_, i) => ({
|
||||
host: `192.0.2.${i + 1}`,
|
||||
port: 443,
|
||||
})),
|
||||
};
|
||||
const source = new RecordingChunkSource(80);
|
||||
const completed = expect(
|
||||
uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
session,
|
||||
commandId,
|
||||
source,
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
),
|
||||
).resolves.toBeUndefined();
|
||||
await Promise.all([completed, vi.runAllTimersAsync()]);
|
||||
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual(
|
||||
session.servers,
|
||||
);
|
||||
expect(source.reads).toEqual([{ offset: 0, length: 80 }]);
|
||||
expect(source.closeCount).toBe(1);
|
||||
expect((createdSockets as FakeSocket[]).every((socket) => socket.destroyed)).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it('uses recent successful host and port only for the same account and upload type', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS', '100');
|
||||
const session = {
|
||||
...makeSession(),
|
||||
servers: [
|
||||
{ host: '192.0.2.1', port: 14000 },
|
||||
{ host: '192.0.2.1', port: 80 },
|
||||
],
|
||||
};
|
||||
const bridge = makeBridge();
|
||||
|
||||
const send = async (owner: BridgeContext, commandId = 1004, candidates = session) => {
|
||||
installFactory(() => {
|
||||
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
|
||||
socket.idleBeforeResponse = createConnectionMock.mock.lastCall?.[0].port === 14000;
|
||||
return socket;
|
||||
});
|
||||
await Promise.all([
|
||||
expect(
|
||||
uploadHighwayHttp(
|
||||
owner,
|
||||
candidates,
|
||||
commandId,
|
||||
new RecordingChunkSource(80),
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
),
|
||||
).resolves.toBeUndefined(),
|
||||
vi.runAllTimersAsync(),
|
||||
]);
|
||||
return createConnectionMock.mock.calls.map(([options]) => options);
|
||||
};
|
||||
|
||||
expect(await send(bridge)).toEqual(session.servers);
|
||||
expect(await send(bridge)).toEqual([session.servers[1]]);
|
||||
expect(await send(makeBridge('10002'))).toEqual(session.servers);
|
||||
expect(await send(bridge, 1003)).toEqual(session.servers);
|
||||
const replacement = { ...session, servers: [{ host: '192.0.2.2', port: 80 }] };
|
||||
expect(await send(bridge, 1004, replacement)).toEqual(replacement.servers);
|
||||
await vi.advanceTimersByTimeAsync(5 * 60_000);
|
||||
expect(await send(bridge)).toEqual(session.servers);
|
||||
});
|
||||
|
||||
it.each(['response', 'write', 'retry'])(
|
||||
'stops a pending %s at the shared upload deadline and releases resources',
|
||||
async (phase) => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '150');
|
||||
vi.stubEnv(
|
||||
'SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS',
|
||||
phase === 'retry' ? '50' : '1000',
|
||||
);
|
||||
installFactory(() => {
|
||||
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
|
||||
socket.idleBeforeResponse = true;
|
||||
socket.stallWrites = phase === 'write';
|
||||
return socket;
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const source = new RecordingChunkSource(80);
|
||||
const start = Date.now();
|
||||
|
||||
try {
|
||||
const failed = expect(
|
||||
uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
sessionWithCandidates(),
|
||||
1004,
|
||||
source,
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
),
|
||||
).rejects.toThrow('timed out after 150ms');
|
||||
await Promise.all([failed, vi.runAllTimersAsync()]);
|
||||
expect(Date.now() - start).toBe(150);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(1);
|
||||
expect(source.closeCount).toBe(1);
|
||||
expect(
|
||||
(createdSockets as FakeSocket[]).every(
|
||||
(socket) =>
|
||||
socket.destroyed &&
|
||||
socket.listenerCount('data') === 0 &&
|
||||
socket.listenerCount('close') === 0,
|
||||
),
|
||||
).toBe(true);
|
||||
const terminal = highwayTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('highway_put_terminal '),
|
||||
);
|
||||
expect(terminal).toHaveLength(1);
|
||||
expect(terminal[0]!.message).toContain('reason=upload_timeout');
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
|
||||
if (phase === 'retry') {
|
||||
expect(
|
||||
entries.some(
|
||||
(entry) =>
|
||||
entry.message.includes('phase=read_response') &&
|
||||
entry.message.includes('received=0B'),
|
||||
),
|
||||
).toBe(true);
|
||||
}
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('does not renew the total deadline when a chunk succeeds', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '250');
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS', '200');
|
||||
installFactory(() => {
|
||||
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
|
||||
socket.responseDelayMs = 100;
|
||||
return socket;
|
||||
});
|
||||
const source = new RecordingChunkSource(2 * HIGHWAY_BLOCK_SIZE + 80);
|
||||
const start = Date.now();
|
||||
const failed = expect(
|
||||
uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
makeSession(),
|
||||
1004,
|
||||
source,
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
),
|
||||
).rejects.toThrow('acknowledgedBytes=2097152/2097232');
|
||||
await Promise.all([failed, vi.runAllTimersAsync()]);
|
||||
expect(Date.now() - start).toBe(250);
|
||||
expect(source.closeCount).toBe(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('rejects invalid timeout configuration before connecting and closes the source', async () => {
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '0');
|
||||
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'));
|
||||
const source = new RecordingChunkSource(80);
|
||||
await expect(
|
||||
uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
makeSession(),
|
||||
1004,
|
||||
source,
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
),
|
||||
).rejects.toThrow('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS');
|
||||
expect(createConnectionMock).not.toHaveBeenCalled();
|
||||
expect(source.closeCount).toBe(1);
|
||||
});
|
||||
|
||||
it.each(['timeout', 'ECONNREFUSED', 'ENETUNREACH'])(
|
||||
'switches on %s and uploads over the successful connection',
|
||||
async (failure) => {
|
||||
@@ -503,8 +731,9 @@ describe('Highway initial connection selection', () => {
|
||||
},
|
||||
);
|
||||
|
||||
it('bounds initial selection to ten seconds without repeating exhausted candidates', async () => {
|
||||
it('bounds initial selection by the configured total deadline without repeating candidates', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '10000');
|
||||
installFactory(() => {
|
||||
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
|
||||
socket.connectFailure = 'timeout';
|
||||
@@ -532,7 +761,7 @@ describe('Highway initial connection selection', () => {
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
);
|
||||
const failed = expect(upload).rejects.toThrow(/connection failed.*TCP connect timeout/);
|
||||
const failed = expect(upload).rejects.toThrow('timed out after 10000ms');
|
||||
await vi.runAllTimersAsync();
|
||||
await failed;
|
||||
expect(Date.now() - start).toBe(10000);
|
||||
@@ -549,7 +778,7 @@ describe('Highway initial connection selection', () => {
|
||||
entry.message.startsWith('highway_put_terminal '),
|
||||
);
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('reason=connect_exhausted');
|
||||
expect(terminals[0]!.message).toContain('reason=upload_timeout');
|
||||
expect(terminals[0]!.message).toContain('connections=0');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
@@ -582,24 +811,160 @@ describe('Highway initial connection selection', () => {
|
||||
expect(source.closeCount).toBe(1);
|
||||
});
|
||||
|
||||
it('stays on the selected node after data was sent without an acknowledgement', async () => {
|
||||
it.each([0, HIGHWAY_BLOCK_SIZE])(
|
||||
'retries only the unconfirmed chunk at offset %i on the next node',
|
||||
async (offset) => {
|
||||
vi.useFakeTimers();
|
||||
installFactory(() => {
|
||||
const host = createConnectionMock.mock.lastCall?.[0].host;
|
||||
const socket = new FakeSocket(
|
||||
buildEmptyHighwayResponseFrame(),
|
||||
'keepalive',
|
||||
host === '192.0.2.1' && offset > 0 ? 2 : -1,
|
||||
);
|
||||
socket.closeBeforeResponse = host === '192.0.2.1' && offset === 0;
|
||||
return socket;
|
||||
});
|
||||
const session = sessionWithCandidates();
|
||||
const original = structuredClone(session);
|
||||
const source = new RecordingChunkSource(offset + 80);
|
||||
const extend = new Uint8Array([0x12, 0x34]);
|
||||
const upload = uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
session,
|
||||
71,
|
||||
source,
|
||||
new Uint8Array(16),
|
||||
extend,
|
||||
);
|
||||
const completed = expect(upload).resolves.toBeUndefined();
|
||||
await Promise.all([completed, vi.runAllTimersAsync()]);
|
||||
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual(
|
||||
session.servers,
|
||||
);
|
||||
const [failed, recovered] = createdSockets as FakeSocket[];
|
||||
expect(recovered!.posts).toBe(1);
|
||||
const first = unpackHighwayFrame(failed!.frames.at(-1)!);
|
||||
const retry = unpackHighwayFrame(recovered!.frames[0]!);
|
||||
const firstHead = protobuf_decode<ReqDataHighwayHead>(first.head);
|
||||
const retryHead = protobuf_decode<ReqDataHighwayHead>(retry.head);
|
||||
expect(retry.body).toEqual(first.body);
|
||||
expect(retryHead).toEqual({
|
||||
...firstHead,
|
||||
msgBaseHead: { ...firstHead.msgBaseHead, retryTimes: 1 },
|
||||
});
|
||||
expect(retryHead.msgSegHead?.dataOffset ?? 0n).toBe(BigInt(offset));
|
||||
expect(retryHead.bytesReqExtendInfo).toEqual(Buffer.from(extend));
|
||||
expect(source.reads).toEqual(
|
||||
offset === 0
|
||||
? [{ offset: 0, length: 80 }]
|
||||
: [
|
||||
{ offset: 0, length: HIGHWAY_BLOCK_SIZE },
|
||||
{ offset, length: 80 },
|
||||
],
|
||||
);
|
||||
expect(source.closeCount).toBe(1);
|
||||
expect(session).toEqual(original);
|
||||
expect((createdSockets as FakeSocket[]).every((socket) => socket.destroyed)).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it('bounds retries across nodes and reports the unconfirmed chunk without advancing progress', async () => {
|
||||
vi.useFakeTimers();
|
||||
installFactory(
|
||||
(idx) =>
|
||||
new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', idx === 0 ? 1 : -1),
|
||||
);
|
||||
installFactory(() => {
|
||||
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
|
||||
socket.closeBeforeResponse = true;
|
||||
return socket;
|
||||
});
|
||||
const session = sessionWithCandidates();
|
||||
const source = new RecordingChunkSource(80);
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
|
||||
try {
|
||||
const upload = uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
session,
|
||||
71,
|
||||
source,
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
);
|
||||
const failed = expect(upload).rejects.toThrow(
|
||||
/transport failed after 3 attempts.*acknowledgedBytes=0.*unconfirmed/,
|
||||
);
|
||||
await Promise.all([failed, vi.runAllTimersAsync()]);
|
||||
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual([
|
||||
session.servers[0],
|
||||
session.servers[1],
|
||||
session.servers[0],
|
||||
]);
|
||||
expect(source.reads).toEqual([{ offset: 0, length: 80 }]);
|
||||
expect(source.closeCount).toBe(1);
|
||||
const terminals = highwayTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('highway_put_terminal '),
|
||||
);
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=transport_exhausted');
|
||||
expect(terminals[0]!.message).toContain('uploadedBytes=0');
|
||||
expect((createdSockets as FakeSocket[]).every((socket) => socket.destroyed)).toBe(true);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('continues after the actual failed node and skips candidates that cannot reconnect', async () => {
|
||||
vi.useFakeTimers();
|
||||
installFactory(() => {
|
||||
const host = createConnectionMock.mock.lastCall?.[0].host;
|
||||
const socket = new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive');
|
||||
|
||||
if (host === '192.0.2.1') {
|
||||
socket.connectFailure = new Error('ECONNREFUSED');
|
||||
} else if (host === '192.0.2.2') {
|
||||
socket.closeBeforeResponse = true;
|
||||
} else if (host === '192.0.2.3') {
|
||||
socket.connectFailure = 'timeout';
|
||||
}
|
||||
|
||||
return socket;
|
||||
});
|
||||
const session = {
|
||||
...makeSession(),
|
||||
servers: Array.from({ length: 4 }, (_, i) => ({ host: `192.0.2.${i + 1}`, port: 443 })),
|
||||
};
|
||||
const source = new RecordingChunkSource(80);
|
||||
const upload = uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
session,
|
||||
1004,
|
||||
new RecordingChunkSource(1),
|
||||
71,
|
||||
source,
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
);
|
||||
await Promise.all([expect(upload).resolves.toBeUndefined(), vi.runAllTimersAsync()]);
|
||||
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual(
|
||||
session.servers,
|
||||
);
|
||||
expect((createdSockets as FakeSocket[]).map((socket) => socket.posts)).toEqual([
|
||||
0, 1, 0, 1,
|
||||
]);
|
||||
expect(source.reads).toEqual([{ offset: 0, length: 80 }]);
|
||||
expect(source.closeCount).toBe(1);
|
||||
});
|
||||
|
||||
it('keeps the successful node when the peer closes after acknowledgement', async () => {
|
||||
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'closeafter'));
|
||||
const session = sessionWithCandidates();
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
session,
|
||||
71,
|
||||
new RecordingChunkSource(HIGHWAY_BLOCK_SIZE + 80),
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(),
|
||||
);
|
||||
const completed = expect(upload).resolves.toBeUndefined();
|
||||
await vi.runAllTimersAsync();
|
||||
await completed;
|
||||
expect(createConnectionMock.mock.calls.map(([options]) => options)).toEqual([
|
||||
session.servers[0],
|
||||
session.servers[0],
|
||||
|
||||
531
packages/core/tests/highway/highway-parallel.test.ts
Normal file
531
packages/core/tests/highway/highway-parallel.test.ts
Normal file
@@ -0,0 +1,531 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
|
||||
import type { ReqDataHighwayHead, RespDataHighwayHead } from '@snowluma/proto-defs/highway';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
import { packHighwayFrame, unpackHighwayFrame, computeMd5 } from '@snowluma/protocol/highway/utils';
|
||||
import {
|
||||
uploadHighwayHttp,
|
||||
type ChunkSource,
|
||||
type HighwaySession,
|
||||
} from '@snowluma/protocol/highway';
|
||||
|
||||
const { connect } = vi.hoisted(() => ({ connect: vi.fn() }));
|
||||
vi.mock('net', () => ({ default: { createConnection: connect } }));
|
||||
const BLOCK = 1024 * 1024;
|
||||
const bridge = { identity: { uin: '10001' } } as unknown as BridgeContext;
|
||||
const session: HighwaySession = {
|
||||
sigSession: new Uint8Array([1]),
|
||||
sessionKey: new Uint8Array(),
|
||||
servers: [
|
||||
{ host: '192.0.2.1', port: 80 },
|
||||
{ host: '192.0.2.2', port: 80 },
|
||||
],
|
||||
};
|
||||
const turn = () => new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
interface Request {
|
||||
socket: TestSocket;
|
||||
head: ReqDataHighwayHead;
|
||||
bytes: Uint8Array;
|
||||
offset: number;
|
||||
respond(override?: RespDataHighwayHead): void;
|
||||
frame(bytes: Uint8Array): void;
|
||||
disconnect(): void;
|
||||
}
|
||||
let requests: Request[];
|
||||
let sockets: TestSocket[];
|
||||
let active: Set<Request>;
|
||||
let peak: number;
|
||||
let onRequest: (request: Request) => void;
|
||||
|
||||
class TestSocket extends EventEmitter {
|
||||
destroyed = false;
|
||||
readableEnded = false;
|
||||
writable = true;
|
||||
private buffer = Buffer.alloc(0);
|
||||
setTimeout() {
|
||||
return this;
|
||||
}
|
||||
write(data: Uint8Array, callback: (error?: Error) => void): boolean {
|
||||
if (this.destroyed) {
|
||||
callback(new Error('socket closed'));
|
||||
return false;
|
||||
}
|
||||
|
||||
this.buffer = Buffer.concat([this.buffer, data]);
|
||||
const end = this.buffer.indexOf('\r\n\r\n');
|
||||
|
||||
if (end >= 0) {
|
||||
const length = Number(
|
||||
this.buffer
|
||||
.subarray(0, end)
|
||||
.toString()
|
||||
.match(/Content-Length: (\d+)/i)![1],
|
||||
);
|
||||
|
||||
if (this.buffer.length >= end + 4 + length) {
|
||||
const { head, body } = unpackHighwayFrame(
|
||||
this.buffer.subarray(end + 4, end + 4 + length),
|
||||
);
|
||||
const decoded = protobuf_decode<ReqDataHighwayHead>(head);
|
||||
this.buffer = this.buffer.subarray(end + 4 + length);
|
||||
const request: Request = {
|
||||
socket: this,
|
||||
head: decoded,
|
||||
bytes: body,
|
||||
offset: Number(decoded.msgSegHead?.dataOffset ?? 0n),
|
||||
frame: (frame) => {
|
||||
if (this.destroyed) {
|
||||
throw new Error('reply on destroyed socket');
|
||||
}
|
||||
|
||||
active.delete(request);
|
||||
this.emit(
|
||||
'data',
|
||||
Buffer.concat([
|
||||
Buffer.from(
|
||||
`HTTP/1.1 200 OK\r\nContent-Length: ${frame.length}\r\n\r\n`,
|
||||
),
|
||||
frame,
|
||||
]),
|
||||
);
|
||||
},
|
||||
respond: (override = {}) =>
|
||||
request.frame(
|
||||
packHighwayFrame(
|
||||
protobuf_encode<RespDataHighwayHead>({
|
||||
msgBaseHead: { seq: decoded.msgBaseHead?.seq },
|
||||
msgSegHead: {
|
||||
filesize: decoded.msgSegHead?.filesize,
|
||||
dataOffset: decoded.msgSegHead?.dataOffset,
|
||||
dataLength: decoded.msgSegHead?.dataLength,
|
||||
},
|
||||
...override,
|
||||
}),
|
||||
new Uint8Array(),
|
||||
),
|
||||
),
|
||||
disconnect: () => this.emit('error', new Error('ECONNRESET')),
|
||||
};
|
||||
expect([...active].some((item) => item.socket === this)).toBe(false);
|
||||
requests.push(request);
|
||||
active.add(request);
|
||||
peak = Math.max(peak, active.size);
|
||||
// Deliberately respond before the write callback. Real fast peers
|
||||
// can reply while socket.write is still completing.
|
||||
onRequest(request);
|
||||
}
|
||||
}
|
||||
|
||||
callback();
|
||||
return true;
|
||||
}
|
||||
destroy() {
|
||||
if (!this.destroyed) {
|
||||
this.destroyed = true;
|
||||
this.writable = false;
|
||||
|
||||
for (const request of active) {
|
||||
if (request.socket === this) {
|
||||
active.delete(request);
|
||||
}
|
||||
}
|
||||
|
||||
queueMicrotask(() => this.emit('close'));
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
class Source implements ChunkSource {
|
||||
reads: number[] = [];
|
||||
closes = 0;
|
||||
constructor(readonly size: number) {}
|
||||
async read(offset: number, length: number) {
|
||||
this.reads.push(offset);
|
||||
return new Uint8Array(length).fill(offset / BLOCK + 1);
|
||||
}
|
||||
async close() {
|
||||
this.closes += 1;
|
||||
}
|
||||
}
|
||||
|
||||
function upload(source: ChunkSource, concurrency: number) {
|
||||
return uploadHighwayHttp(bridge, session, 1005, source, new Uint8Array(16), new Uint8Array(), {
|
||||
concurrency,
|
||||
});
|
||||
}
|
||||
|
||||
const level = getLogLevel();
|
||||
beforeEach(() => {
|
||||
requests = [];
|
||||
sockets = [];
|
||||
active = new Set();
|
||||
peak = 0;
|
||||
|
||||
onRequest = () => {};
|
||||
|
||||
connect.mockReset().mockImplementation((_options, listener) => {
|
||||
const socket = new TestSocket();
|
||||
sockets.push(socket);
|
||||
setImmediate(listener);
|
||||
return socket;
|
||||
});
|
||||
});
|
||||
afterEach(() => {
|
||||
setLogLevel(level);
|
||||
vi.unstubAllEnvs();
|
||||
vi.useRealTimers();
|
||||
|
||||
for (const socket of sockets) {
|
||||
socket.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
describe('bounded parallel highway uploads', () => {
|
||||
it('does not let trickled response bytes extend the whole-file deadline', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '100');
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_IDLE_TIMEOUT_MS', '30');
|
||||
|
||||
onRequest = ({ socket }) => {
|
||||
const timer = setInterval(() => socket.emit('data', Buffer.from('x')), 10);
|
||||
socket.once('close', () => clearInterval(timer));
|
||||
};
|
||||
|
||||
const source = new Source(80);
|
||||
const start = Date.now();
|
||||
const failed = expect(upload(source, 1)).rejects.toThrow('timed out after 100ms');
|
||||
await Promise.all([failed, vi.runAllTimersAsync()]);
|
||||
expect(Date.now() - start).toBe(100);
|
||||
expect(source.closes).toBe(1);
|
||||
expect(active.size).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('drains a pending source read after the deadline without sending its bytes', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '50');
|
||||
const source = new Source(80);
|
||||
let reading = false;
|
||||
const read = source.read.bind(source);
|
||||
|
||||
source.read = async (offset, length) => {
|
||||
reading = true;
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 100));
|
||||
reading = false;
|
||||
return read(offset, length);
|
||||
};
|
||||
|
||||
const close = vi.spyOn(source, 'close').mockImplementation(async () => {
|
||||
expect(reading).toBe(false);
|
||||
});
|
||||
const failed = expect(upload(source, 1)).rejects.toThrow('timed out after 50ms');
|
||||
await Promise.all([failed, vi.runAllTimersAsync()]);
|
||||
expect(connect).not.toHaveBeenCalled();
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('aborts all parallel requests at one whole-file deadline', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubEnv('SNOWLUMA_HIGHWAY_UPLOAD_TIMEOUT_MS', '1000');
|
||||
const source = new Source(6 * BLOCK);
|
||||
const start = Date.now();
|
||||
const failed = expect(upload(source, 3)).rejects.toThrow('timed out after 1000ms');
|
||||
await Promise.all([failed, vi.runAllTimersAsync()]);
|
||||
expect(Date.now() - start).toBe(1000);
|
||||
expect(requests).toHaveLength(3);
|
||||
expect(sockets.every((socket) => socket.destroyed)).toBe(true);
|
||||
expect(active.size).toBe(0);
|
||||
expect(source.closes).toBe(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
it.each([2, 3, 4])(
|
||||
'uses %i connections, accepts out-of-order acknowledgements and sends the tail last',
|
||||
async (concurrency) => {
|
||||
const source = new Source(6 * BLOCK + 17);
|
||||
const confirmed = new Set<number>();
|
||||
|
||||
const checkAndAck = (request: Request) => {
|
||||
if (request.offset === 6 * BLOCK) {
|
||||
expect(confirmed.size).toBe(6);
|
||||
}
|
||||
|
||||
expect(request.bytes.every((byte) => byte === request.offset / BLOCK + 1)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(Buffer.from(request.head.msgSegHead!.md5!)).toEqual(
|
||||
Buffer.from(computeMd5(request.bytes)),
|
||||
);
|
||||
confirmed.add(request.offset);
|
||||
request.respond();
|
||||
};
|
||||
|
||||
const result = upload(source, concurrency);
|
||||
await vi.waitFor(() => expect(requests).toHaveLength(concurrency));
|
||||
expect(source.closes).toBe(0);
|
||||
onRequest = checkAndAck;
|
||||
|
||||
for (const request of [...active].reverse()) {
|
||||
checkAndAck(request);
|
||||
}
|
||||
|
||||
await result;
|
||||
expect(peak).toBe(concurrency);
|
||||
expect(sockets).toHaveLength(concurrency);
|
||||
expect(requests).toHaveLength(7);
|
||||
expect(new Set(requests.map((request) => request.head.msgBaseHead?.seq)).size).toBe(7);
|
||||
expect(source.closes).toBe(1);
|
||||
expect(sockets.every((socket) => socket.destroyed)).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it('logs confirmed bytes separately from the contiguous prefix after out-of-order replies', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const source = new Source(3 * BLOCK + 1);
|
||||
|
||||
try {
|
||||
const result = upload(source, 3);
|
||||
await vi.waitFor(() => expect(requests).toHaveLength(3));
|
||||
requests[2].respond();
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
entries.some((entry) =>
|
||||
entry.message.includes('acknowledgedBytes=1048576 contiguousBytes=0'),
|
||||
),
|
||||
).toBe(true),
|
||||
);
|
||||
expect(requests).toHaveLength(3);
|
||||
onRequest = (request) => request.respond();
|
||||
requests[1].respond();
|
||||
requests[0].respond();
|
||||
await result;
|
||||
const terminal = entries.filter((entry) =>
|
||||
entry.message.startsWith('highway_put_terminal '),
|
||||
);
|
||||
expect(terminal).toHaveLength(1);
|
||||
expect(terminal[0]?.message).toContain(`uploadedBytes=${source.size}`);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('surfaces repeated backpressure after the retry budget is exhausted', async () => {
|
||||
const source = new Source(4 * BLOCK);
|
||||
|
||||
onRequest = (request) => {
|
||||
if (request.offset === 0) {
|
||||
request.respond({ errorCode: 102902 });
|
||||
} else {
|
||||
request.respond();
|
||||
}
|
||||
};
|
||||
|
||||
await expect(upload(source, 3)).rejects.toThrow(/error_code=102902/);
|
||||
expect(requests.filter((request) => request.offset === 0)).toHaveLength(8);
|
||||
expect(requests.some((request) => request.offset === 3 * BLOCK)).toBe(false);
|
||||
expect(source.closes).toBe(1);
|
||||
});
|
||||
|
||||
it('limits lookahead behind a slow chunk and recovers an idle connection failure', async () => {
|
||||
const source = new Source(14 * BLOCK + 1);
|
||||
|
||||
onRequest = (request) => {
|
||||
if (request.offset !== 0) {
|
||||
request.respond();
|
||||
}
|
||||
};
|
||||
|
||||
const result = upload(source, 4);
|
||||
await vi.waitFor(() => expect(requests).toHaveLength(10));
|
||||
await turn();
|
||||
expect(Math.max(...requests.map((request) => request.offset))).toBe(9 * BLOCK);
|
||||
const idle = sockets.find(
|
||||
(socket) => ![...active].some((request) => request.socket === socket),
|
||||
)!;
|
||||
idle.emit('error', new Error('idle connection reset'));
|
||||
onRequest = (request) => request.respond();
|
||||
requests[0].respond();
|
||||
await result;
|
||||
expect(requests).toHaveLength(15);
|
||||
expect(source.closes).toBe(1);
|
||||
});
|
||||
|
||||
it('retries only the unconfirmed range after a transport failure', async () => {
|
||||
const source = new Source(6 * BLOCK);
|
||||
let failed = false;
|
||||
|
||||
onRequest = (request) => {
|
||||
if (request.offset === BLOCK && !failed) {
|
||||
failed = true;
|
||||
request.disconnect();
|
||||
} else {
|
||||
request.respond();
|
||||
}
|
||||
};
|
||||
|
||||
await upload(source, 3);
|
||||
const retried = requests.filter((request) => request.offset === BLOCK);
|
||||
expect(retried).toHaveLength(2);
|
||||
expect(retried[1].bytes).toEqual(retried[0].bytes);
|
||||
expect(retried[1].head.msgBaseHead?.retryTimes).toBe(1);
|
||||
expect(retried[1].head.msgBaseHead?.seq).not.toBe(retried[0].head.msgBaseHead?.seq);
|
||||
expect(source.reads).toHaveLength(6);
|
||||
expect(requests.filter((request) => request.offset !== BLOCK)).toHaveLength(5);
|
||||
expect(source.closes).toBe(1);
|
||||
});
|
||||
|
||||
it.each([102902, 302902])(
|
||||
'drains in-flight requests and reduces concurrency on %i',
|
||||
async (code) => {
|
||||
const source = new Source(7 * BLOCK);
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
|
||||
try {
|
||||
const result = upload(source, 4);
|
||||
await vi.waitFor(() => expect(requests).toHaveLength(4));
|
||||
requests[0].respond({ errorCode: code });
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
entries.some((entry) =>
|
||||
entry.message.includes('reducing concurrency from 4 to 1'),
|
||||
),
|
||||
).toBe(true),
|
||||
);
|
||||
await turn();
|
||||
expect(requests).toHaveLength(4);
|
||||
let afterDrainPeak = 0;
|
||||
|
||||
onRequest = (request) => {
|
||||
afterDrainPeak = Math.max(afterDrainPeak, active.size);
|
||||
request.respond();
|
||||
};
|
||||
|
||||
for (const request of [...active]) {
|
||||
request.respond();
|
||||
}
|
||||
|
||||
await result;
|
||||
expect(afterDrainPeak).toBe(1);
|
||||
expect(requests.filter((request) => request.offset === 0)).toHaveLength(2);
|
||||
expect(requests).toHaveLength(8);
|
||||
expect(source.closes).toBe(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ msgBaseHead: { seq: 999 } },
|
||||
{ msgSegHead: { dataOffset: 99n } },
|
||||
{ msgSegHead: { dataLength: 99 } },
|
||||
{ msgSegHead: { filesize: 99n } },
|
||||
])('rejects mismatched acknowledgements without retrying (case %#)', async (response) => {
|
||||
const source = new Source(4 * BLOCK);
|
||||
onRequest = (request) => request.respond(response);
|
||||
await expect(upload(source, 3)).rejects.toThrow(/acknowledgement mismatch/);
|
||||
expect(requests.every((request) => (request.head.msgBaseHead?.retryTimes ?? 0) === 0)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(requests.some((request) => request.offset === 3 * BLOCK)).toBe(false);
|
||||
expect(source.closes).toBe(1);
|
||||
expect(sockets.every((socket) => socket.destroyed)).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects segment-level errors even when the top-level code is zero', async () => {
|
||||
const source = new Source(4 * BLOCK);
|
||||
onRequest = (request) => request.respond({ msgSegHead: { retCode: 921 } });
|
||||
await expect(upload(source, 3)).rejects.toThrow(/segRetCode=921/);
|
||||
expect(source.closes).toBe(1);
|
||||
});
|
||||
|
||||
it('stops peers on rejection and waits for pending source reads before closing', async () => {
|
||||
let release!: () => void;
|
||||
let reading = false;
|
||||
const source = new Source(5 * BLOCK);
|
||||
const read = source.read.bind(source);
|
||||
|
||||
source.read = async (offset, length) => {
|
||||
if (offset === BLOCK) {
|
||||
reading = true;
|
||||
await new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
reading = false;
|
||||
}
|
||||
|
||||
return read(offset, length);
|
||||
};
|
||||
|
||||
const close = vi.spyOn(source, 'close').mockImplementation(async () => {
|
||||
expect(reading).toBe(false);
|
||||
});
|
||||
const result = upload(source, 3);
|
||||
const rejected = expect(result).rejects.toThrow(/error_code=921/);
|
||||
await vi.waitFor(() => expect(requests).toHaveLength(2));
|
||||
requests.find((request) => request.offset === 0)!.respond({ errorCode: 921 });
|
||||
await turn();
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
release();
|
||||
await rejected;
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(requests).toHaveLength(2);
|
||||
expect(sockets.every((socket) => socket.destroyed)).toBe(true);
|
||||
});
|
||||
|
||||
it('stops after bounded transport retries without sending the final chunk', async () => {
|
||||
const source = new Source(5 * BLOCK);
|
||||
|
||||
onRequest = (request) => {
|
||||
if (request.offset === 0) {
|
||||
request.disconnect();
|
||||
} else {
|
||||
request.respond();
|
||||
}
|
||||
};
|
||||
|
||||
await expect(upload(source, 3)).rejects.toThrow(/transport failed after 3 attempts/);
|
||||
expect(requests.filter((request) => request.offset === 0)).toHaveLength(3);
|
||||
expect(requests.some((request) => request.offset === 4 * BLOCK)).toBe(false);
|
||||
expect(source.closes).toBe(1);
|
||||
});
|
||||
|
||||
it.each([1, BLOCK + 1, 2 * BLOCK])('keeps a %i-byte upload on one connection', async (size) => {
|
||||
onRequest = (request) => request.respond();
|
||||
await upload(new Source(size), 4);
|
||||
expect(peak).toBe(1);
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('keeps legacy success responses without echo fields compatible', async () => {
|
||||
onRequest = (request) => request.respond({ msgBaseHead: undefined, msgSegHead: undefined });
|
||||
await upload(new Source(4 * BLOCK), 3);
|
||||
expect(requests).toHaveLength(4);
|
||||
});
|
||||
|
||||
it.each([0, 5, -1, 1.5, NaN])(
|
||||
'rejects invalid concurrency %s and closes the source',
|
||||
async (concurrency) => {
|
||||
const source = new Source(4 * BLOCK);
|
||||
await expect(upload(source, concurrency)).rejects.toThrow(/integer from 1 to 4/);
|
||||
expect(source.closes).toBe(1);
|
||||
expect(requests).toHaveLength(0);
|
||||
},
|
||||
);
|
||||
|
||||
it('rejects short reads instead of acknowledging bytes that were not uploaded', async () => {
|
||||
const source = new Source(4 * BLOCK);
|
||||
source.read = async () => new Uint8Array(1);
|
||||
await expect(upload(source, 3)).rejects.toThrow(/expected 1048576/);
|
||||
expect(requests).toHaveLength(0);
|
||||
expect(source.closes).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,9 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
vi.mock('@snowluma/protocol/highway/pipeline', () => ({
|
||||
runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })),
|
||||
runNtv2Upload: vi.fn(async () => ({
|
||||
msgInfo: { msgInfoBody: [{ index: { fileUuid: 'uploaded-image' } }], extBizInfo: {} },
|
||||
})),
|
||||
finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0xca, 0xfe])),
|
||||
hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)),
|
||||
}));
|
||||
|
||||
@@ -132,6 +132,36 @@ describe('pipeline — runNtv2Upload', () => {
|
||||
setLogLevel(previousLogLevel);
|
||||
});
|
||||
|
||||
it('passes concurrency only for the sub-file that explicitly opts in', async () => {
|
||||
const bridge = makeBridge({
|
||||
responseData: encodeOidbResponse({
|
||||
upload: {
|
||||
uKey: 'main-key',
|
||||
subFileInfos: [{ uKey: 'cover-key' }],
|
||||
msgInfo: { msgInfoBody: [{}, {}], extBizInfo: {} },
|
||||
},
|
||||
}),
|
||||
});
|
||||
const media = {
|
||||
bytes: new Uint8Array([1]),
|
||||
md5: new Uint8Array(16),
|
||||
sha1: new Uint8Array(20),
|
||||
};
|
||||
await runNtv2Upload(
|
||||
baseParams({
|
||||
bridge,
|
||||
uploads: [
|
||||
{ ...media, source: 'top', cmdId: 1005, concurrency: 4 },
|
||||
{ ...media, source: 0, cmdId: 1006 },
|
||||
],
|
||||
}),
|
||||
);
|
||||
const calls = vi.mocked(highway.uploadHighwayHttp).mock.calls;
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(calls[0]?.[6]).toEqual({ concurrency: 4 });
|
||||
expect(calls[1]?.[6]).toBeUndefined();
|
||||
});
|
||||
|
||||
it('records fast-upload selection and one completed media terminal', async () => {
|
||||
const bridge = makeBridge({
|
||||
responseData: encodeOidbResponse({
|
||||
|
||||
@@ -39,11 +39,12 @@ describe('ptt-upload', () => {
|
||||
vi.mocked(pipeline.runNtv2Upload).mockResolvedValueOnce({
|
||||
msgInfo: { msgInfoBody: [{ index: node }] },
|
||||
} as any);
|
||||
const element = { ...FINGERPRINT };
|
||||
const element = { ...FINGERPRINT, isNtv2: false };
|
||||
await uploadPttMsgInfo({} as any, true, 12345, element);
|
||||
expect(element).toMatchObject({
|
||||
fileId: 'uploaded-resource',
|
||||
mediaNode: node,
|
||||
isNtv2: true,
|
||||
md5Hex: 'aa',
|
||||
sha1Hex: 'bb',
|
||||
});
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
getVideoUploadConcurrency,
|
||||
setVideoUploadConcurrency,
|
||||
} from '@snowluma/protocol/highway/upload-settings';
|
||||
// video-upload tests cover the fingerprint (fast-upload) path. The
|
||||
// regular load path exercises ffmpeg + the OS temp dir + a streaming
|
||||
// SHA1 implementation; that machinery has its own seams worth testing
|
||||
@@ -9,7 +13,7 @@
|
||||
// fastOnlyError difference (main has it; thumb doesn't — FALLBACK_THUMB
|
||||
// always provides bytes), and the video-specific OIDB fields.
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { promises as fsp } from 'fs';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
@@ -44,11 +48,27 @@ const FINGERPRINT = {
|
||||
} as any;
|
||||
|
||||
describe('video-upload', () => {
|
||||
afterEach(() => setVideoUploadConcurrency(1));
|
||||
beforeEach(() => {
|
||||
vi.mocked(pipeline.runNtv2Upload).mockClear();
|
||||
vi.mocked(pipeline.finalizeMediaMsgInfo).mockClear();
|
||||
});
|
||||
|
||||
it('snapshots the global concurrency for video bodies without parallelizing covers', async () => {
|
||||
expect(getVideoUploadConcurrency()).toBe(1);
|
||||
setVideoUploadConcurrency(4);
|
||||
const first = uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
|
||||
setVideoUploadConcurrency(2);
|
||||
await first;
|
||||
const firstUpload = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
|
||||
expect(firstUpload.uploads[0]!.concurrency).toBe(4);
|
||||
expect(firstUpload.uploads[1]!.concurrency).toBeUndefined();
|
||||
await uploadVideoMsgInfo({} as any, false, 'recipient-uid', FINGERPRINT);
|
||||
const secondUpload = vi.mocked(pipeline.runNtv2Upload).mock.calls[1]![0];
|
||||
expect(secondUpload.uploads[0]!.concurrency).toBe(2);
|
||||
expect(secondUpload.uploads[1]!.concurrency).toBeUndefined();
|
||||
});
|
||||
|
||||
it('retains successful upload metadata for self-sent history', async () => {
|
||||
const node = { fileUuid: 'uploaded-resource', storeId: 1, info: { fileSize: 1234 } };
|
||||
vi.mocked(pipeline.runNtv2Upload).mockResolvedValueOnce({
|
||||
|
||||
@@ -141,6 +141,73 @@ describe('IdentityService', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('retains legacy member identities and refreshes only damaged cards across restarts', async () => {
|
||||
const dbPath = tempDbPath('legacy-card');
|
||||
const member = makeMember(33333, 'u_member', 'placeholder');
|
||||
const other = makeMember(44444, 'u_other', 'ordinary');
|
||||
const seed = new IdentityService(SELF_UIN, dbPath);
|
||||
seed.rememberGroups([makeGroup()]);
|
||||
seed.rememberGroupMembers(GROUP_ID, [member, other]);
|
||||
await seed.close();
|
||||
// Persisted bytes from #646 after the old text normalization stripped the envelope prefix.
|
||||
const damaged = Buffer.concat([
|
||||
Buffer.from('1209', 'hex'),
|
||||
Buffer.from('三字名'),
|
||||
Buffer.from('0a090a0724c3bfc48011221000', 'hex'),
|
||||
]);
|
||||
const sql = new DatabaseSync(dbPath);
|
||||
|
||||
try {
|
||||
sql.prepare('UPDATE group_members SET card = CAST(? AS TEXT) WHERE uin = ?').run(
|
||||
damaged,
|
||||
member.uin,
|
||||
);
|
||||
} finally {
|
||||
sql.close();
|
||||
}
|
||||
|
||||
const stale = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
try {
|
||||
await stale.initialization;
|
||||
const cached = stale.findGroupMember(GROUP_ID, member.uin)!;
|
||||
expect(cached).toMatchObject({ card: undefined, uid: member.uid, isRobot: false });
|
||||
expect(stale.findGroupMember(GROUP_ID, other.uin)?.card).toBe('ordinary');
|
||||
stale.updateGroupMember(GROUP_ID, { ...cached, role: 'admin' });
|
||||
} finally {
|
||||
await stale.close();
|
||||
}
|
||||
|
||||
const refreshed = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
try {
|
||||
await refreshed.initialization;
|
||||
expect(refreshed.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
|
||||
card: undefined,
|
||||
role: 'admin',
|
||||
});
|
||||
refreshed.rememberGroupMembers(GROUP_ID, [
|
||||
{ ...member, role: 'admin', card: ' 三字名 ' },
|
||||
other,
|
||||
]);
|
||||
} finally {
|
||||
await refreshed.close();
|
||||
}
|
||||
|
||||
const restored = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
try {
|
||||
await restored.initialization;
|
||||
expect(restored.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
|
||||
card: ' 三字名 ',
|
||||
role: 'admin',
|
||||
});
|
||||
expect(restored.findGroupMember(GROUP_ID, other.uin)?.card).toBe('ordinary');
|
||||
} finally {
|
||||
await restored.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('persists group member robot classification across restarts', async () => {
|
||||
const dbPath = tempDbPath('persist-robot');
|
||||
|
||||
@@ -160,11 +227,13 @@ describe('IdentityService', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('migrates legacy member caches without inventing a robot classification', async () => {
|
||||
const dbPath = tempDbPath('migrate-robot');
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
const legacy = new DatabaseSync(dbPath);
|
||||
legacy.exec(`
|
||||
it.each([false, true])(
|
||||
'migrates legacy member cards and retries after failure=%s',
|
||||
async (failMigration) => {
|
||||
const dbPath = tempDbPath('migrate-robot');
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
const legacy = new DatabaseSync(dbPath);
|
||||
legacy.exec(`
|
||||
CREATE TABLE users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
uid TEXT UNIQUE,
|
||||
@@ -197,6 +266,7 @@ describe('IdentityService', () => {
|
||||
join_time INTEGER NOT NULL DEFAULT 0,
|
||||
last_sent_time INTEGER NOT NULL DEFAULT 0,
|
||||
shut_up_time INTEGER NOT NULL DEFAULT 0,
|
||||
${failMigration ? 'is_robot INTEGER,' : ''}
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
updated_at INTEGER NOT NULL,
|
||||
UNIQUE(group_id, uid),
|
||||
@@ -207,19 +277,96 @@ describe('IdentityService', () => {
|
||||
INSERT INTO group_members (group_id, uid, uin, nickname, updated_at)
|
||||
VALUES (${GROUP_ID}, 'u_legacy', 33333, 'legacy-member', 1);
|
||||
`);
|
||||
legacy.close();
|
||||
legacy.close();
|
||||
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
await identity.initialization;
|
||||
expect(identity.findGroupMember(GROUP_ID, 33333)?.isRobot).toBeUndefined();
|
||||
await identity.close();
|
||||
if (failMigration) {
|
||||
const originalExec = SqliteDatabase.prototype.exec;
|
||||
const fault = vi
|
||||
.spyOn(SqliteDatabase.prototype, 'exec')
|
||||
.mockImplementation(function (this: SqliteDatabase, sql) {
|
||||
if (sql.includes('ADD COLUMN card_known')) {
|
||||
return Promise.reject(new Error('injected card migration failure'));
|
||||
}
|
||||
|
||||
const migrated = new DatabaseSync(dbPath);
|
||||
const columns = migrated.prepare('PRAGMA table_info(group_members)').all() as Array<{
|
||||
name: string;
|
||||
}>;
|
||||
expect(columns.map((column) => column.name)).toContain('is_robot');
|
||||
migrated.close();
|
||||
return originalExec.call(this, sql);
|
||||
});
|
||||
const failed = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
try {
|
||||
await expect(failed.initialization).rejects.toThrow(
|
||||
'injected card migration failure',
|
||||
);
|
||||
await expect(failed.close()).rejects.toThrow('injected card migration failure');
|
||||
} finally {
|
||||
fault.mockRestore();
|
||||
await failed.close();
|
||||
}
|
||||
}
|
||||
|
||||
const identity = new IdentityService(SELF_UIN, dbPath);
|
||||
await identity.initialization;
|
||||
expect(identity.findGroupMember(GROUP_ID, 33333)?.isRobot).toBeUndefined();
|
||||
expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('');
|
||||
await identity.close();
|
||||
|
||||
const migrated = new DatabaseSync(dbPath);
|
||||
const columns = migrated.prepare('PRAGMA table_info(group_members)').all() as Array<{
|
||||
name: string;
|
||||
}>;
|
||||
expect(columns.map((column) => column.name)).toContain('is_robot');
|
||||
expect(columns.map((column) => column.name)).toContain('card_known');
|
||||
migrated.close();
|
||||
|
||||
const reopened = new IdentityService(SELF_UIN, dbPath);
|
||||
await reopened.initialization;
|
||||
expect(reopened.findGroupMember(GROUP_ID, 33333)?.card).toBe('');
|
||||
await reopened.close();
|
||||
},
|
||||
);
|
||||
|
||||
it('preserves valid cards when an unreadable roster arrives during initialization', async () => {
|
||||
const dbPath = tempDbPath('pending-card-roster');
|
||||
const member = makeMember(33333, 'u_member', 'valid card');
|
||||
const seed = new IdentityService(SELF_UIN, dbPath);
|
||||
seed.rememberGroups([makeGroup()]);
|
||||
seed.rememberGroupMembers(GROUP_ID, [member]);
|
||||
await seed.close();
|
||||
let release!: () => void;
|
||||
const loading = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const identity = new IdentityService(SELF_UIN, dbPath, loading);
|
||||
const unreadable = { ...member, card: undefined, role: 'admin' };
|
||||
identity.rememberGroupMembers(GROUP_ID, [unreadable]);
|
||||
release();
|
||||
|
||||
try {
|
||||
await identity.initialization;
|
||||
expect(identity.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
|
||||
card: 'valid card',
|
||||
role: 'admin',
|
||||
});
|
||||
identity.updateGroupMember(GROUP_ID, { ...unreadable, level: 9 });
|
||||
expect(identity.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
|
||||
card: 'valid card',
|
||||
level: 9,
|
||||
});
|
||||
} finally {
|
||||
await identity.close();
|
||||
}
|
||||
|
||||
const reopened = new IdentityService(SELF_UIN, dbPath);
|
||||
|
||||
try {
|
||||
await reopened.initialization;
|
||||
expect(reopened.findGroupMember(GROUP_ID, member.uin)).toMatchObject({
|
||||
card: 'valid card',
|
||||
role: 'admin',
|
||||
level: 9,
|
||||
});
|
||||
} finally {
|
||||
await reopened.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps updateGroupMember changes after reopening the persistent cache', async () => {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import { parseMsgPush, MSG_PUSH_CMD } from '@snowluma/protocol/msg-push';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { GroupInviteTracker } from '@snowluma/protocol/group-invite-tracker';
|
||||
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
|
||||
@@ -529,6 +530,7 @@ describe('parseMsgPush Event0x210 subType=364 (friend remark synchronization)',
|
||||
fetchGroupList: vi.fn(async () => {}),
|
||||
fetchGroupMemberList: vi.fn(async () => {}),
|
||||
resolveGroupJoinRequest: vi.fn(async () => null),
|
||||
groupInvites: new GroupInviteTracker(),
|
||||
});
|
||||
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
|
||||
|
||||
@@ -1027,6 +1029,7 @@ describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache
|
||||
fetchGroupList: vi.fn(async () => {}),
|
||||
fetchGroupMemberList: vi.fn(async () => {}),
|
||||
resolveGroupJoinRequest: vi.fn(async () => null),
|
||||
groupInvites: new GroupInviteTracker(),
|
||||
});
|
||||
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
|
||||
await pipeline.process(packet);
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
appendEvents,
|
||||
ingestTemp,
|
||||
lineSeverity,
|
||||
publicLine,
|
||||
trimMirror,
|
||||
} from '../src/native-stage-sync';
|
||||
|
||||
const VERSION = '1.14.22';
|
||||
const EVENT = 'a'.repeat(64);
|
||||
const infoLine = `2026-10-09T00:00:00Z 42 1 0 ${EVENT}`;
|
||||
const failLine = `2026-10-09T00:00:01Z 42 1 1 ${EVENT} ${'b'.repeat(16)}=7`;
|
||||
|
||||
describe('native stage sync', () => {
|
||||
it('keeps a version marker and copies the record without extra wording', () => {
|
||||
const mirror = appendEvents('', VERSION, [infoLine, failLine]);
|
||||
expect(mirror.startsWith(`v${VERSION}\n`)).toBe(true);
|
||||
expect(mirror).toContain(infoLine);
|
||||
expect(mirror).toContain(failLine);
|
||||
const shown = [publicLine(VERSION, infoLine), publicLine(VERSION, failLine)].join('\n');
|
||||
expect(shown).toBe(`${VERSION} ${infoLine}\n${VERSION} ${failLine}`);
|
||||
});
|
||||
|
||||
it('opens a new version section without dropping the previous marker', () => {
|
||||
const first = appendEvents('', '1.14.22', [infoLine]);
|
||||
const second = appendEvents(first, '1.14.23', [failLine]);
|
||||
expect(second).toContain('v1.14.22\n');
|
||||
expect(second).toContain('v1.14.23\n');
|
||||
expect(second.indexOf('v1.14.22')).toBeLessThan(second.indexOf(infoLine));
|
||||
expect(second.indexOf('v1.14.23')).toBeLessThan(second.indexOf(failLine));
|
||||
});
|
||||
|
||||
it('drops the oldest record first and keeps the version marker', () => {
|
||||
const long = `2026-10-09T00:00:00Z 1 1 0 ${'c'.repeat(64)} ${'d'.repeat(40)}`;
|
||||
let mirror = appendEvents('', VERSION, [long, long, long], 80);
|
||||
mirror = trimMirror(mirror, 80);
|
||||
expect(mirror).toContain(`v${VERSION}`);
|
||||
expect(mirror.split('\n').filter((line) => line.startsWith('2026')).length).toBeLessThan(3);
|
||||
});
|
||||
|
||||
it('treats severity 1 as a failure and ignores a missing file', () => {
|
||||
expect(lineSeverity(failLine)).toBe('error');
|
||||
expect(lineSeverity(infoLine)).toBe('info');
|
||||
const ingested = ingestTemp({
|
||||
tempText: `${infoLine}\n${failLine}\npartial`,
|
||||
offset: 0,
|
||||
mirror: '',
|
||||
version: VERSION,
|
||||
});
|
||||
expect(ingested.lines).toEqual([infoLine, failLine]);
|
||||
expect(ingested.mirror).toContain(`v${VERSION}\n`);
|
||||
expect(ingested.offset).toBe(`${infoLine}\n${failLine}\n`.length);
|
||||
const missing = ingestTemp({
|
||||
tempText: '',
|
||||
offset: 4,
|
||||
mirror: 'keep',
|
||||
version: VERSION,
|
||||
missing: true,
|
||||
});
|
||||
expect(missing.mirror).toBe('keep');
|
||||
expect(missing.lines).toEqual([]);
|
||||
expect(missing.errorCode).toBeUndefined();
|
||||
});
|
||||
});
|
||||
91
packages/core/tests/private-voice-wire.test.ts
Normal file
91
packages/core/tests/private-voice-wire.test.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { SendMessageResponse } from '@snowluma/proto-defs/action';
|
||||
import type { Elem } from '@snowluma/proto-defs/element';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import {
|
||||
type bytes,
|
||||
type pb,
|
||||
type pb_repeated,
|
||||
protobuf_decode,
|
||||
protobuf_encode,
|
||||
} from '@snowluma/proton';
|
||||
import { expect, it } from 'vitest';
|
||||
import { Bridge } from '../src/bridge/bridge';
|
||||
|
||||
interface VoiceParts {
|
||||
elems?: pb_repeated<2, bytes>;
|
||||
ptt?: pb<4, bytes>;
|
||||
}
|
||||
|
||||
interface UploadReply {
|
||||
upload?: pb<2, { compat?: pb<8, bytes> }>;
|
||||
}
|
||||
|
||||
interface OutgoingMessage {
|
||||
body?: pb<3, { richText?: pb<1, VoiceParts> }>;
|
||||
}
|
||||
|
||||
it('preserves the private voice returned for older clients alongside the modern voice', async () => {
|
||||
// The upload reply from #614, with identifiers redacted and transport credentials removed.
|
||||
const upload = Buffer.from(
|
||||
readFileSync(
|
||||
new URL('./fixtures/issue-614-private-voice-upload.hex', import.meta.url),
|
||||
'utf8',
|
||||
).replace(/\s/g, ''),
|
||||
'hex',
|
||||
);
|
||||
const captured = protobuf_decode<OidbBase<UploadReply>>(Uint8Array.from(upload)).body!.upload!
|
||||
.compat!;
|
||||
const expected = protobuf_decode<VoiceParts>(captured);
|
||||
expect(captured).toHaveLength(301);
|
||||
expect(expected.ptt).toHaveLength(253);
|
||||
let sent: VoiceParts | undefined;
|
||||
|
||||
class VoiceBridge extends Bridge {
|
||||
override async resolveUserUid(): Promise<string> {
|
||||
return 'u_peer';
|
||||
}
|
||||
|
||||
override async sendRawPacket(cmd: string, body: Uint8Array): Promise<SendPacketResult> {
|
||||
let response: Uint8Array;
|
||||
|
||||
if (cmd === 'OidbSvcTrpcTcp.0x126d_100') {
|
||||
response = upload;
|
||||
} else if (cmd === 'MessageSvc.PbSendMsg') {
|
||||
sent = protobuf_decode<OutgoingMessage>(body).body!.richText!;
|
||||
response = protobuf_encode<SendMessageResponse>({ privateSequence: 88 });
|
||||
} else {
|
||||
throw new Error(`Unexpected packet ${cmd}`);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(response),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const bridge = new VoiceBridge(IdentityService.memory('10000'));
|
||||
await bridge.apis.message.sendPrivate(10001, [
|
||||
{
|
||||
type: 'record',
|
||||
noByteFallback: true,
|
||||
fileSize: 7931,
|
||||
duration: 3,
|
||||
md5Hex: '0'.repeat(32),
|
||||
sha1Hex: '0'.repeat(40),
|
||||
fileName: 'voice.amr',
|
||||
},
|
||||
]);
|
||||
expect(protobuf_decode<Elem>(sent!.elems![0]!).commonElem).toMatchObject({
|
||||
serviceType: 48,
|
||||
businessType: 12,
|
||||
});
|
||||
expect(sent!.ptt).toEqual(expected.ptt);
|
||||
expect(sent!.elems!.slice(1)).toEqual(expected.elems);
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
@@ -9,17 +10,48 @@ const { SUPPORTED_NODE_RANGE, isSupportedNodeVersion } =
|
||||
};
|
||||
|
||||
describe('runtime Node.js preflight', () => {
|
||||
it('accepts the documented minimum and newer versions', () => {
|
||||
expect(SUPPORTED_NODE_RANGE).toBe('>=24');
|
||||
expect(isSupportedNodeVersion('24.0.0')).toBe(true);
|
||||
expect(isSupportedNodeVersion('24.21.0')).toBe(true);
|
||||
expect(isSupportedNodeVersion('26.0.0')).toBe(true);
|
||||
it.each(['24.22.1', '24.22.2', '24.23.0', '24.22.1+vendor.1', '26.12.1', '26.13.0', '27.0.0'])(
|
||||
'accepts patched stable Node.js %s',
|
||||
(version) => {
|
||||
expect(isSupportedNodeVersion(version)).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
'22.23.4',
|
||||
'23.99.99',
|
||||
'24.0.0',
|
||||
'24.21.0',
|
||||
'24.22.0',
|
||||
'25.99.99',
|
||||
'26.0.0',
|
||||
'26.11.99',
|
||||
'26.12.0',
|
||||
'24.22.1-rc.1',
|
||||
'26.12.1-rc.1',
|
||||
'not-a-version',
|
||||
])('rejects unpatched, unsupported or malformed Node.js %s', (version) => {
|
||||
expect(isSupportedNodeVersion(version)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects older and malformed versions', () => {
|
||||
expect(isSupportedNodeVersion('22.99.99')).toBe(false);
|
||||
expect(isSupportedNodeVersion('23.99.99')).toBe(false);
|
||||
expect(isSupportedNodeVersion('21.99.99')).toBe(false);
|
||||
expect(isSupportedNodeVersion('not-a-version')).toBe(false);
|
||||
it('keeps workspace requirements and the bundled runtime baseline aligned', () => {
|
||||
expect(SUPPORTED_NODE_RANGE).toBe('^24.22.1 || >=26.12.1');
|
||||
const root = new URL('../../../', import.meta.url);
|
||||
const packages = readdirSync(new URL('packages/', root), { withFileTypes: true });
|
||||
const manifests = [
|
||||
new URL('package.json', root),
|
||||
...packages
|
||||
.filter((entry) => entry.isDirectory())
|
||||
.map((entry) => new URL(`packages/${entry.name}/package.json`, root)),
|
||||
];
|
||||
|
||||
for (const manifest of manifests) {
|
||||
const pkg = JSON.parse(readFileSync(manifest, 'utf8'));
|
||||
expect(pkg.engines.node, manifest.pathname).toBe(SUPPORTED_NODE_RANGE);
|
||||
}
|
||||
|
||||
const baseline = readFileSync(new URL('.node-version', root), 'utf8').trim();
|
||||
expect(baseline).toBe('24.22.1');
|
||||
expect(isSupportedNodeVersion(baseline)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,10 +5,14 @@ import path from 'node:path';
|
||||
import { zipSync } from 'fflate';
|
||||
import { c as createTar } from 'tar';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { archivePath, assetName, downloadUpdate } from '../src/update/download';
|
||||
import { archivePath, assetName, downloadUpdate as download } from '../src/update/download';
|
||||
import { readManifest } from '../src/update/files';
|
||||
import { releaseFixture } from './helpers/update-fixture';
|
||||
|
||||
const direct = { mode: 'direct', mirror: '', mirrors: [] } as const;
|
||||
const downloadUpdate = (directory: string, version: string, target: string) =>
|
||||
download(directory, version, target, { ...direct, mirrors: [] });
|
||||
|
||||
let root: string;
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-download-test-'));
|
||||
@@ -43,6 +47,105 @@ function mockRelease(bytes: Uint8Array, target: string, digest?: string) {
|
||||
}
|
||||
|
||||
describe('release downloads', () => {
|
||||
it.each(['403', 'html', 'corrupt', 'interrupted'])(
|
||||
'cleans and retries a %s response through a mirror using HTML release checksums',
|
||||
async (failure) => {
|
||||
const manifest = await releaseFixture(path.join(root, 'source'), '2.0.0', 'win32-x64');
|
||||
const bytes = zipSync({
|
||||
'release.json': new TextEncoder().encode(JSON.stringify(manifest)),
|
||||
'app.mjs': new TextEncoder().encode('verified payload'),
|
||||
});
|
||||
const name = assetName('2.0.0', 'win32-x64');
|
||||
const digest = createHash('sha256').update(bytes).digest('hex');
|
||||
const fetchMock = vi.fn<typeof fetch>(async (input) => {
|
||||
const url = String(input);
|
||||
|
||||
if (url.includes('api.github.com')) {
|
||||
return new Response('rate limited', { status: 403 });
|
||||
}
|
||||
|
||||
if (url.includes('/expanded_assets/')) {
|
||||
return new Response(
|
||||
`<li><a href="/SnowLuma/SnowLuma/releases/download/v2.0.0/${name}">asset</a><clipboard-copy value="sha256:${digest}"></clipboard-copy></li>`,
|
||||
);
|
||||
}
|
||||
|
||||
if (url.startsWith('https://working.example/')) {
|
||||
// Mirrors may stream a verified archive without Content-Length.
|
||||
return new Response(new Uint8Array(bytes));
|
||||
}
|
||||
|
||||
if (failure === '403') {
|
||||
return new Response('blocked', { status: 403 });
|
||||
}
|
||||
|
||||
if (failure === 'html') {
|
||||
return new Response('<html>challenge</html>', {
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
});
|
||||
}
|
||||
|
||||
if (failure === 'interrupted') {
|
||||
let sent = false;
|
||||
return new Response(
|
||||
new ReadableStream({
|
||||
pull(controller) {
|
||||
if (sent) {
|
||||
controller.error(new Error('connection reset'));
|
||||
} else {
|
||||
controller.enqueue(new Uint8Array([1, 2, 3]));
|
||||
sent = true;
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return new Response('corrupt archive');
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await download(root, '2.0.0', 'win32-x64', {
|
||||
mode: 'auto',
|
||||
mirror: '',
|
||||
mirrors: ['https://working.example'],
|
||||
});
|
||||
expect(await readFile(path.join(root, 'archive'))).toEqual(Buffer.from(bytes));
|
||||
expect(await readFile(path.join(root, 'payload/app.mjs'), 'utf8')).toBe(
|
||||
'verified payload',
|
||||
);
|
||||
expect(
|
||||
fetchMock.mock.calls
|
||||
.filter(([url]) => String(url).includes('/download/'))
|
||||
.map(([url]) => String(url)),
|
||||
).toEqual([
|
||||
`https://github.com/SnowLuma/SnowLuma/releases/download/v2.0.0/${name}`,
|
||||
`https://working.example/https://github.com/SnowLuma/SnowLuma/releases/download/v2.0.0/${name}`,
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it('does not try other download sources in pinned mode', async () => {
|
||||
const bytes = new Uint8Array([1, 2, 3]);
|
||||
const fetchMock = mockRelease(bytes, 'win32-x64');
|
||||
const original = fetchMock.getMockImplementation()!;
|
||||
fetchMock.mockImplementation(async (input) =>
|
||||
String(input).includes('api.github.com')
|
||||
? original(input)
|
||||
: new Response('blocked', { status: 403 }),
|
||||
);
|
||||
await expect(
|
||||
download(root, '2.0.0', 'win32-x64', {
|
||||
mode: 'mirror',
|
||||
mirror: 'https://pinned.example',
|
||||
mirrors: ['https://other.example'],
|
||||
}),
|
||||
).rejects.toThrow('HTTP 403');
|
||||
expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
|
||||
'https://api.github.com/repos/SnowLuma/SnowLuma/releases/tags/v2.0.0',
|
||||
`https://pinned.example/https://github.com/SnowLuma/SnowLuma/releases/download/v2.0.0/${assetName('2.0.0', 'win32-x64')}`,
|
||||
]);
|
||||
expect(await readdir(root)).toEqual([]);
|
||||
});
|
||||
it.each(['win32-x64', 'linux-x64', 'linux-arm64'])(
|
||||
'downloads and validates the %s lite package',
|
||||
async (target) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { cp, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
|
||||
import { builtinModules } from 'node:module';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
@@ -14,7 +14,8 @@ let root: string;
|
||||
let staging: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
compiled = await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-build-'));
|
||||
// Module resolution uses canonical paths, including when the temp directory is a symlink.
|
||||
compiled = await realpath(await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-build-')));
|
||||
const loaded = await loadConfigFromFile(
|
||||
{ command: 'build', mode: 'production' },
|
||||
fileURLToPath(new URL('../vite.config.ts', import.meta.url)),
|
||||
@@ -114,7 +115,7 @@ afterAll(async () => {
|
||||
await rm(compiled, { recursive: true, force: true });
|
||||
});
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-test-'));
|
||||
root = await realpath(await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-test-')));
|
||||
staging = await updateDirectory(root);
|
||||
await releaseFixture(root, '1.0.0');
|
||||
await cp(path.join(compiled, '1.0.0/index.mjs'), path.join(root, 'index.mjs'));
|
||||
@@ -158,7 +159,7 @@ describe('packaged startup', () => {
|
||||
expect(JSON.parse(result.output)).toEqual({
|
||||
version: '1.0.0',
|
||||
node: process.execPath,
|
||||
cwd: os.tmpdir(),
|
||||
cwd: await realpath(os.tmpdir()),
|
||||
args: ['value with spaces'],
|
||||
oldAlive: false,
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user