Compare commits

3 Commits

Author SHA1 Message Date
unfunny
9957f2a7a9 Add step-by-step diagnostics to message handler and echo command at startup 2026-09-13 17:14:58 -04:00
unfunny
cbc23c0325 Rewrite keys/upload OTK-collision 400 into synthetic 200
Rust crypto uses an in-memory store (no IndexedDB in Node), so after a
restart it re-uploads one-time keys it already published. Synapse rejects
the duplicate with a 400; the SDK never marks the request as sent, so it
retries forever and the bot can never decrypt. Intercept that specific
400 and return a fake success with empty one_time_key_counts, which makes
the machine mint fresh OTK ids that upload cleanly.
2026-09-13 17:08:11 -04:00
unfunny
bfe7cb2790 Add E2EE support via Rust/Olm WASM crypto (initRustCrypto, stable device ID) 2026-09-13 16:56:53 -04:00
2 changed files with 48 additions and 7 deletions

View File

@@ -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

View File

@@ -1,18 +1,47 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import { MatrixClient } from 'matrix-js-sdk'; import { MatrixClient } from 'matrix-js-sdk';
import { MemoryStore } from 'matrix-js-sdk/lib/store/memory.js';
import fs from 'fs'; import fs from 'fs';
dotenv.config(); 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,
store: new MemoryStore(), 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';
@@ -56,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');
@@ -87,11 +123,12 @@ function loadQuotes() {
const type = event.getType(); const type = event.getType();
const eventRoomId = event.getRoomId(); 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(`🔒 [${eventRoomId}] 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;
} }