Release room-scoped Matrix bot plugins and room configuration
This commit is contained in:
commit
86c7e4359c
76 files changed
+13539
No files matched your search
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* 一次性交互脚本:用你的「恢复密钥 / 安全短语」给 bot 设备做 cross-signing。
|
||||
*
|
||||
* 背景:bot 跑的 matrix-bot-sdk(底层 crypto 0.4.0)不支持设备验证,
|
||||
* 所以在 Element 里点「验证」会一直卡住。本脚本用官方 matrix-js-sdk
|
||||
* 临时登录一次,从你的 Secret Storage(4S)取出 cross-signing 私钥,
|
||||
* 直接给目标设备签名(等价于 Element 里 SAS 验证成功后的那一步),
|
||||
* 签完立刻登出这个临时设备。bot 运行时完全不动。
|
||||
*
|
||||
* 用法:node ./cross-sign.mjs 然后按提示粘贴即可。
|
||||
*/
|
||||
import { createClient, AutoDiscovery } from 'matrix-js-sdk';
|
||||
import { decodeRecoveryKey } from 'matrix-js-sdk/lib/crypto-api/recovery-key.js';
|
||||
import { pbkdf2 } from 'node:crypto';
|
||||
import { promisify } from 'node:util';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { stdin, stdout } from 'node:process';
|
||||
|
||||
const pbkdf2Async = promisify(pbkdf2);
|
||||
|
||||
function fail(msg) {
|
||||
console.error(`❌ ${msg}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
/** 普通提问;支持默认值(直接回车采用) */
|
||||
function ask(question, def) {
|
||||
const rl = createInterface({ input: stdin, output: stdout });
|
||||
const suffix = def ? ` [${def}]` : '';
|
||||
return new Promise((resolve) => {
|
||||
rl.question(`${question}${suffix}: `, (ans) => {
|
||||
rl.close();
|
||||
resolve((ans.trim() || def || '').trim());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** 隐藏输入(粘贴时不回显),用于密码 / 恢复密钥 */
|
||||
function askSecret(question) {
|
||||
return new Promise((resolve) => {
|
||||
// 先把提示语打印出来(可见),再静音后续按键回显
|
||||
stdout.write(`${question}: `);
|
||||
const rl = createInterface({ input: stdin, output: stdout });
|
||||
rl._writeToOutput = function (str) {
|
||||
// 仅放行换行,其余按键不回显
|
||||
if (str.includes('\n')) rl.output.write('\n');
|
||||
};
|
||||
rl.question('', (ans) => {
|
||||
rl.close();
|
||||
resolve(ans.trim());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
let RECOVERY_KEY = '';
|
||||
let SECURITY_PHRASE = '';
|
||||
let PASSWORD = '';
|
||||
let TARGET_DEVICE_ID = '';
|
||||
|
||||
async function main() {
|
||||
console.log('=== bot 设备 cross-signing 工具 ===\n');
|
||||
|
||||
const homeserverInput = await ask('账号域名或 API 地址');
|
||||
if (!homeserverInput) fail('必须输入账号域名或 API 地址。');
|
||||
const userId = await ask('账号 user id');
|
||||
if (!userId) fail('必须输入账号 ID。');
|
||||
PASSWORD = await askSecret('账号密码(粘贴,不回显)');
|
||||
if (!PASSWORD) fail('必须输入密码。');
|
||||
|
||||
console.log(
|
||||
'\n签名需要你的「安全密钥」或「安全短语」二选一。安全密钥优先,直接回车切到安全短语。',
|
||||
);
|
||||
RECOVERY_KEY = await askSecret('安全密钥(base58,如 EsTc...;不回显)');
|
||||
if (RECOVERY_KEY) {
|
||||
try {
|
||||
decodeRecoveryKey(RECOVERY_KEY.replace(/\s+/g, ''));
|
||||
} catch {
|
||||
fail('安全密钥格式不对(应是 EsTx... 的 base58,4 字符一组共 12 组)。');
|
||||
}
|
||||
} else {
|
||||
SECURITY_PHRASE = await askSecret('安全短语(不回显)');
|
||||
if (!SECURITY_PHRASE) fail('安全密钥和安全短语必须至少提供一个。');
|
||||
}
|
||||
|
||||
TARGET_DEVICE_ID = await ask('要签名的设备 ID');
|
||||
if (!TARGET_DEVICE_ID && await ask('签名所有未验证设备?输入 ALL 确认') !== 'ALL') {
|
||||
fail('未选择签名目标。');
|
||||
}
|
||||
|
||||
// 1) 解析真实 API 地址(支持裸域名 well-known 发现)
|
||||
const baseUrl = await resolveBaseUrl(homeserverInput);
|
||||
console.log(`\n🔗 homeserver API: ${baseUrl}`);
|
||||
|
||||
// 2) 临时登录(产生一个临时设备,结束后登出删除)
|
||||
const loginClient = createClient({ baseUrl });
|
||||
console.log('🔑 临时登录中...');
|
||||
const login = await loginClient.login('m.login.password', {
|
||||
identifier: { type: 'm.id.user', user: userId },
|
||||
password: PASSWORD,
|
||||
initial_device_display_name: 'cross-sign-temp (可删)',
|
||||
});
|
||||
const accessToken = login.access_token;
|
||||
const deviceId = login.device_id;
|
||||
const realUserId = login.user_id;
|
||||
console.log(`✅ 临时设备已登录: ${deviceId}`);
|
||||
|
||||
// 3) 构建带 crypto 的 client,提供 secret storage 取钥回调
|
||||
const client = createClient({
|
||||
baseUrl,
|
||||
accessToken,
|
||||
userId: realUserId,
|
||||
deviceId,
|
||||
cryptoCallbacks: { getSecretStorageKey },
|
||||
});
|
||||
|
||||
let signedOk = false;
|
||||
try {
|
||||
await client.initRustCrypto({ useIndexedDB: false });
|
||||
const crypto = client.getCrypto();
|
||||
if (!crypto) fail('crypto 初始化失败。');
|
||||
|
||||
console.log('🔄 启动同步(拉取设备列表 / secret storage)...');
|
||||
await client.startClient({ initialSyncLimit: 1 });
|
||||
await waitForSync(client);
|
||||
|
||||
// 4) 从 4S 导入 cross-signing 私钥(不重置已有密钥)
|
||||
console.log('📥 从 Secret Storage 导入 cross-signing 私钥...');
|
||||
await crypto.bootstrapCrossSigning({
|
||||
authUploadDeviceSigningKeys: async (makeRequest) => {
|
||||
await makeRequest({
|
||||
type: 'm.login.password',
|
||||
identifier: { type: 'm.id.user', user: realUserId },
|
||||
password: PASSWORD,
|
||||
});
|
||||
},
|
||||
});
|
||||
if (!(await crypto.isCrossSigningReady())) {
|
||||
fail(
|
||||
'cross-signing 未就绪——恢复密钥/短语可能不对,或账号未设置过 cross-signing。',
|
||||
);
|
||||
}
|
||||
console.log('✅ cross-signing 私钥就绪。');
|
||||
|
||||
// 5) 确定要签名的设备
|
||||
const targets = await resolveTargets(crypto, realUserId, deviceId);
|
||||
if (targets.length === 0) {
|
||||
console.log('ℹ️ 没有需要签名的设备(可能都已验证)。');
|
||||
}
|
||||
for (const dev of targets) {
|
||||
console.log(`✍️ 签名设备 ${dev} ...`);
|
||||
await crypto.crossSignDevice(dev);
|
||||
const st = await crypto.getDeviceVerificationStatus(realUserId, dev);
|
||||
console.log(` → crossSigningVerified=${st?.crossSigningVerified ?? '?'}`);
|
||||
}
|
||||
signedOk = true;
|
||||
} finally {
|
||||
// 6) 清理:登出临时设备(删除它),停止 client
|
||||
try {
|
||||
client.stopClient();
|
||||
} catch {}
|
||||
try {
|
||||
console.log('🧹 登出并删除临时设备...');
|
||||
await client.logout(true);
|
||||
console.log('✅ 临时设备已删除。');
|
||||
} catch (e) {
|
||||
console.warn('⚠️ 登出临时设备失败(可手动在 Element 删除):', e?.message);
|
||||
}
|
||||
}
|
||||
|
||||
if (signedOk) {
|
||||
console.log('\n🎉 完成!刷新 Element 设备列表即可看到目标设备已验证(绿盾)。');
|
||||
}
|
||||
process.exit(signedOk ? 0 : 1);
|
||||
}
|
||||
|
||||
/** secret storage 取钥回调:用恢复密钥或安全短语派生 4S 密钥 */
|
||||
async function getSecretStorageKey({ keys }) {
|
||||
const keyId = Object.keys(keys)[0];
|
||||
const info = keys[keyId];
|
||||
let privateKey;
|
||||
if (RECOVERY_KEY) {
|
||||
privateKey = decodeRecoveryKey(RECOVERY_KEY.replace(/\s+/g, ''));
|
||||
} else {
|
||||
const pp = info?.passphrase;
|
||||
if (!pp?.salt || !pp?.iterations) {
|
||||
fail('该账号的 4S 没有 passphrase 信息,请改用安全密钥。');
|
||||
}
|
||||
privateKey = new Uint8Array(
|
||||
await pbkdf2Async(SECURITY_PHRASE, pp.salt, pp.iterations, 32, 'sha512'),
|
||||
);
|
||||
}
|
||||
return [keyId, privateKey];
|
||||
}
|
||||
|
||||
/** 决定签名目标:指定了 TARGET_DEVICE_ID 就只签它;否则签名所有未交叉验证的自有设备(除临时设备) */
|
||||
async function resolveTargets(crypto, userId, tempDeviceId) {
|
||||
if (TARGET_DEVICE_ID) return [TARGET_DEVICE_ID];
|
||||
const map = await crypto.getUserDeviceInfo([userId], true);
|
||||
const devices = map.get(userId);
|
||||
const out = [];
|
||||
if (!devices) return out;
|
||||
for (const devId of devices.keys()) {
|
||||
if (devId === tempDeviceId) continue;
|
||||
const st = await crypto.getDeviceVerificationStatus(userId, devId);
|
||||
if (!st?.crossSigningVerified) out.push(devId);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** well-known 发现:裸域名 → 真实 API 地址 */
|
||||
async function resolveBaseUrl(input) {
|
||||
if (/^https?:\/\//.test(input)) return input.replace(/\/$/, '');
|
||||
const res = await AutoDiscovery.findClientConfig(input);
|
||||
const url = res?.['m.homeserver']?.base_url;
|
||||
if (!url) fail(`无法从 ${input} 发现 homeserver,请直接填完整 API 地址。`);
|
||||
return url.replace(/\/$/, '');
|
||||
}
|
||||
|
||||
/** 等待首次同步完成 */
|
||||
function waitForSync(client) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const to = setTimeout(() => reject(new Error('同步超时(60s)')), 60_000);
|
||||
client.once('sync', function handler(state) {
|
||||
if (state === 'PREPARED') {
|
||||
clearTimeout(to);
|
||||
resolve();
|
||||
} else if (state === 'ERROR') {
|
||||
clearTimeout(to);
|
||||
reject(new Error('同步出错'));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error('💥 出错:', e);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in new issue
Block a user