Compare commits
3 Commits
main
...
encryption
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9957f2a7a9 | ||
|
|
cbc23c0325 | ||
|
|
bfe7cb2790 |
@@ -5,5 +5,9 @@ MATRIX_HOME_SERVER=https://matrix.org
|
|||||||
MATRIX_ACCESS_TOKEN=your_real_access_token_here
|
MATRIX_ACCESS_TOKEN=your_real_access_token_here
|
||||||
BOT_COMMAND=!quote
|
BOT_COMMAND=!quote
|
||||||
|
|
||||||
|
# Stable device ID for the bot's E2EE identity. Keep this consistent
|
||||||
|
# across restarts so the bot reuses its encryption keys.
|
||||||
|
MATRIX_DEVICE_ID=ANCESTORBOT
|
||||||
|
|
||||||
# If you want debug logging, set DEBUG=true
|
# If you want debug logging, set DEBUG=true
|
||||||
DEBUG=false
|
DEBUG=false
|
||||||
|
|||||||
84
index.js
84
index.js
@@ -6,11 +6,42 @@ dotenv.config();
|
|||||||
|
|
||||||
console.log('🚀 Starting Ancestor Quote Bot...\n');
|
console.log('🚀 Starting Ancestor Quote Bot...\n');
|
||||||
|
|
||||||
|
const deviceId = process.env.MATRIX_DEVICE_ID || 'ANCESTORBOT';
|
||||||
|
|
||||||
const client = new MatrixClient({
|
const client = new MatrixClient({
|
||||||
accessToken: process.env.MATRIX_ACCESS_TOKEN,
|
accessToken: process.env.MATRIX_ACCESS_TOKEN,
|
||||||
baseUrl: process.env.MATRIX_HOME_SERVER,
|
baseUrl: process.env.MATRIX_HOME_SERVER,
|
||||||
|
deviceId,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// The Rust crypto backend uses an in-memory store here (no IndexedDB in Node),
|
||||||
|
// so after a restart it 'forgets' one-time keys it already uploaded. Re-uploading
|
||||||
|
// an existing OTK id makes Synapse reject the request with a 400, the SDK never
|
||||||
|
// marks it as sent, and it retries forever — which blocks decryption entirely.
|
||||||
|
// Rewrite that specific 400 into a synthetic success: the empty count makes the
|
||||||
|
// Rust machine mint fresh OTK ids on the next tick, which then upload cleanly.
|
||||||
|
function installOtkCollisionWorkaround(client) {
|
||||||
|
const http = client.http;
|
||||||
|
const authedRequest = http.authedRequest.bind(http);
|
||||||
|
http.authedRequest = async function (method, path, queryParams, body, opts) {
|
||||||
|
try {
|
||||||
|
return await authedRequest(method, path, queryParams, body, opts);
|
||||||
|
} catch (err) {
|
||||||
|
if (
|
||||||
|
method === 'POST' &&
|
||||||
|
/\/keys\/upload$/.test(path) &&
|
||||||
|
err?.httpStatus === 400 &&
|
||||||
|
/already exists/.test(err?.message || '')
|
||||||
|
) {
|
||||||
|
console.warn('⚙️ One-time-key collision on keys/upload; telling Rust crypto to mint fresh keys');
|
||||||
|
return '{"one_time_key_counts":{}}';
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
installOtkCollisionWorkaround(client);
|
||||||
|
|
||||||
function loadQuotes() {
|
function loadQuotes() {
|
||||||
try {
|
try {
|
||||||
const quotesFile = './quotes.json';
|
const quotesFile = './quotes.json';
|
||||||
@@ -54,7 +85,14 @@ function loadQuotes() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
client.credentials.userId = userId;
|
client.credentials.userId = userId;
|
||||||
console.log(`👤 Bot Identity: ${userId}`);
|
console.log(`👤 Bot Identity: ${userId} (device ${deviceId})`);
|
||||||
|
|
||||||
|
// Enable end-to-end encryption so the bot can read and reply in
|
||||||
|
// encrypted rooms. The Rust/Olm WASM backend needs no native
|
||||||
|
// compile. useIndexedDB=false keeps everything in memory (no
|
||||||
|
// IndexedDB in Node).
|
||||||
|
await client.initRustCrypto({ useIndexedDB: false });
|
||||||
|
console.log('🔐 E2EE crypto initialised (Rust/Olm WASM)');
|
||||||
|
|
||||||
await client.startClient();
|
await client.startClient();
|
||||||
console.log('✅ MatrixClient connected and authenticated\n');
|
console.log('✅ MatrixClient connected and authenticated\n');
|
||||||
@@ -67,6 +105,7 @@ function loadQuotes() {
|
|||||||
console.log('');
|
console.log('');
|
||||||
|
|
||||||
const cmd = (process.env.BOT_COMMAND || '!quote').toLowerCase();
|
const cmd = (process.env.BOT_COMMAND || '!quote').toLowerCase();
|
||||||
|
console.log(`🔊 Listening for command: "${cmd}"`);
|
||||||
|
|
||||||
// Auto-accept invites so the bot can be invited into rooms.
|
// Auto-accept invites so the bot can be invited into rooms.
|
||||||
client.on('RoomMember.membership', (event, member) => {
|
client.on('RoomMember.membership', (event, member) => {
|
||||||
@@ -82,36 +121,49 @@ function loadQuotes() {
|
|||||||
// Respond to messages in any room this bot is a member of.
|
// Respond to messages in any room this bot is a member of.
|
||||||
client.on('event', (event) => {
|
client.on('event', (event) => {
|
||||||
const type = event.getType();
|
const type = event.getType();
|
||||||
|
const eventRoomId = event.getRoomId();
|
||||||
|
|
||||||
// Encrypted rooms: the bot has no E2EE support, so command text
|
// If an event still arrives encrypted, decryption failed — the
|
||||||
// never arrives as plaintext and cannot be read or answered.
|
// room is likely set to only share keys with verified sessions.
|
||||||
if (type === 'm.room.encrypted') {
|
if (type === 'm.room.encrypted') {
|
||||||
console.log(`🔒 [${event.getRoomId()}] encrypted message received. ` +
|
console.log(`🔒 [${eventRoomId}] could not decrypt message. ` +
|
||||||
`The bot cannot read E2EE rooms; invite it to an unencrypted room instead.`);
|
`The room may be set to share keys only with verified sessions; ` +
|
||||||
|
`change room encryption settings to include this bot's device, or verify it.`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (type !== 'm.room.message') return;
|
if (type !== 'm.room.message') return;
|
||||||
|
|
||||||
const sender = event.getSender();
|
const sender = event.getSender();
|
||||||
if (sender === userId) return;
|
if (sender === userId) return; // skip replies from ourselves
|
||||||
|
|
||||||
const room = client.getRoom(event.getRoomId());
|
const room = eventRoomId ? client.getRoom(eventRoomId) : null;
|
||||||
if (!room) return;
|
if (!room) {
|
||||||
|
console.log(`ℹ️ [debug] got m.room.message for unknown room: ${eventRoomId}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const membership = room.getMyMembership();
|
const membership = room.getMyMembership();
|
||||||
if (membership !== 'join') return;
|
if (membership !== 'join') {
|
||||||
|
console.log(`ℹ️ [debug] [${room.roomId}] m.room.message while membership="${membership}" — not replying`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const content = event.getContent();
|
const content = event.getContent();
|
||||||
if (!content || typeof content.body !== 'string') return;
|
if (!content || typeof content.body !== 'string') {
|
||||||
|
console.log(`ℹ️ [debug] [${room.roomId}] m.room.message without text body`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const lower = content.body.toLowerCase().trim();
|
const lower = content.body.toLowerCase().trim();
|
||||||
if (lower === cmd || lower.startsWith(cmd + ' ')) {
|
const matches = lower === cmd || lower.startsWith(cmd + ' ');
|
||||||
const quote = quotes[Math.floor(Math.random() * quotes.length)];
|
console.log(`💬 [${room.roomId}] <${sender}> "${content.body}" (listening for "${cmd}", match=${matches})`);
|
||||||
client.sendTextMessage(room.roomId, quote)
|
if (!matches) return;
|
||||||
.then(() => console.log(`🎃 [${room.roomId}] ${quote}`))
|
|
||||||
.catch((err) => console.error('Failed to send quote:', err.message));
|
const quote = quotes[Math.floor(Math.random() * quotes.length)];
|
||||||
}
|
client.sendTextMessage(room.roomId, quote)
|
||||||
|
.then(() => console.log(`🎃 [${room.roomId}] ${quote}`))
|
||||||
|
.catch((err) => console.error('Failed to send quote:', err.message));
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('🤖 Bot is running!');
|
console.log('🤖 Bot is running!');
|
||||||
|
|||||||
Reference in New Issue
Block a user