diff --git a/index.js b/index.js index c953951..663a068 100644 --- a/index.js +++ b/index.js @@ -14,6 +14,34 @@ const client = new MatrixClient({ 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() { try { const quotesFile = './quotes.json';