End-to-end encryption for chat: each browser holds a crypto device, and the server keeps its public keys and passes Olm ciphertext between devices. Encrypted chat rooms carry Megolm ciphertext over it, their room keys are backed up to a recovery key the user keeps, and devices are verified by emoji or QR code with cross-signing. Encrypted calls (W8) send their per-sender call keys over the same device layer. The design is plans/archive/Comms-Framework.md §4.5, milestone C7.
- Browser:
webroot/screen/webroot/js/WebrootCrypto.js(moqui.crypto), over matrix-sdk-crypto'sOlmMachine(the vendored@matrix-org/matrix-sdk-crypto-wasm18.9.0,/libs/matrix-sdk-crypto/). - Services:
org.moqui.chat.ChatKeyServicesandChatKeys.js(framework), withChatDevice,ChatDeviceKeyandChatToDeviceinframework/entity/ChatKeyEntities.xml, with the cross-signing and backup entities; the/ChatKeystransitions (webrootChatKeys.xml). - Encrypted rooms:
org.moqui.chat.ChatServices(ChatRoom.encrypted,ChatEvent.encrypted: the C7 block ofChatEntities.xml); in the browsermoqui.chat(js/WebrootChat.js:sealMessage,openEvents,openEvent) and BasicComms Chat (Chat.qvue). - Screens: BasicComms Settings, My devices (
Settings/Devices,Devices.qvue,DevicesTui.xml): devices, verification and the key backup; Chat's New room (Encrypted) and room settings.
A device is one browser's crypto store for one user, as in Matrix: devices belong to users, not to chat actors.
-
Made on first use.
ensureDevice()asks the server for a device (create#ChatDevice: a 10-letter deviceId) the first time this browser needs one for the user. Chat asks for it when it opens (in idle time once its rooms show; not in a desktop app window, nor in a browser without WebAssembly or IndexedDB), so new chats can be encrypted by default (below). A device made so is marked (automatic,ChatDevice.madeAutomatically). -
At most 50 in use. A user holds at most 50 devices seen in the last
chat@device-active-days(tooManyDevices); long-unused ones do not hold a new one back.find#ChatDevicesanswers each device'sactive(seen in that time) andautomatic. -
Unused automatic devices go. The daily job
clean_ChatToDevice_daily(clean#ChatToDevice) revokes each device Chat made by itself that its user never verified (no cross-signing signature over it) and that was not seen forchat@device-auto-expire-days(30), as a revoke by its user does, each in its own transaction (revoke#AutomaticDevice) and logged; one that fails is logged and the rest go on. A private window's device, made each time it opens Chat, goes this way.- The store is IndexedDB, named
moqui-crypto-<userId>-<deviceId>. - The deviceId is kept in localStorage under the userId, so the next page opens the same store.
- The store is IndexedDB, named
-
Nothing loads until needed. The 7.8 MB WebAssembly module loads only when a caller asks for the device (Chat, an encrypted room or call, My devices' actions); pages that never do load none of it.
-
Keys. The machine uploads its signed identity keys and one-time keys (
upload#Keys). A device's identity keys cannot change once set. -
Revoking. Settings, My devices removes a device (
revoke#ChatDevice):- it gets no new keys or messages;
- its keys and the messages waiting for it are deleted;
- it drops out of key queries.
A browser whose device was revoked deletes its store and makes a new device the next time it needs one. Revoking does not sign the browser out.
A device with keys needs a sign-in in the last five minutes (Recent sign-in;
reauthRequired), since the server cannot tell which browser asks. Not for a device without keys (a browser dropping a device whose first keys were refused). -
Logout and account switch. Logout and leaving the page close the store. A store belongs to one user and device, and a page of another user never opens it. The server refuses a device that is not the session user's ("not found"), so a tab left open across an account switch gets nothing; that tab only closes the store (it deletes it only when the session is still the store's user).
-
One tab holds the store; the others ask it. A tab holds a Web Lock on the store while it is open: two
OlmMachines on one store would spoil its Olm sessions.- That tab is the leader. The user's other tabs of the browser are followers: they send their calls (encrypt,
decrypt, send to devices, backup, verification) to the leader over a
BroadcastChannelnamedmoqui-crypto:<userId>:<deviceId>:<tag>, and hear its to-device events, new room keys and verifications.state.rolesays which a tab is. The tag is the first 128 bits of SHA-256 of the device's store key, so a tab finds the channel only after fetching that key as the device's signed-in user: a page of another account in the same browser profile (which can read the deviceId from localStorage) cannot ask the leader to decrypt or share keys. The leader answers only calls of the API's own functions, with an array of arguments. Without Web Crypto there is no relay: each tab waits for the store. - Each follower waits for the lock. When the leader's tab closes (or closes its store), one of them takes the store
and leads; calls still waiting are asked of it. A call not answered in 30 seconds is refused (
busy). - Encrypted files are encrypted and decrypted in any tab: that needs the module, not the store.
- That tab is the leader. The user's other tabs of the browser are followers: they send their calls (encrypt,
decrypt, send to devices, backup, verification) to the leader over a
-
At rest. The store is encrypted with its store key, a passphrase the server derives for the device and does not store: HMAC-SHA-256 under the platform secret
chat@store-key-secretofuserId|deviceId|revision(derive#ChatStoreKey). It is given only to the device's own signed-in user (/ChatKeys/storeKey); a revoke bumps the revision (ChatDevice.storeRevision). A copy of the browser profile alone does not open the store; with a signed-in session it does. No table or export holds the key, so an administrator with entity data access in Tools does not get it.- What it does not protect against: anyone who can sign in as the user (or holds a stolen session) together with the
browser profile; whoever holds the server's
chat@store-key-secret; and script running in a page of this origin while the user is signed in. It is a lock against a copied or stolen profile, not against the server.
- What it does not protect against: anyone who can sign in as the user (or holds a stolen session) together with the
browser profile; whoever holds the server's
-
A store that does not open. It is tried again (three times); a passing IndexedDB failure never deletes it. Only a definite one (a wrong key, a store of another device, data that does not decode) stops it, and the store is kept: the user is told (
state.problem,storeUnreadable) and Settings, My devices offers "Start over" (after the user confirms who they are): the store is deleted, the device revoked and a new one made, whose older messages come from the key backup. Keys that cannot be read are never deleted silently. -
A refused key upload. The machine's upload is not retried as it is: a device whose keys the server refuses (
keysChanged,keyExists,badKeys,tooLarge) is revoked and made again once; a second refusal stops this page's uploads (state.statuserror).tooManyKeysstops uploads until keys are claimed.
In the desktop client (Desktop-Client), the shell owns the account's
device, named for the app and the computer ("MR Moqui desktop on ", moquiDesktop.deviceName in place of the
browser and OS of the user agent). The host keeps its store key (/ChatKeys/storeKey) in the OS key store, so cached
ciphertext decrypts offline, and drops it on a revocation and with the account. App windows make and open no device:
ensureDevice and each call that needs it refuse with reasonCode elsewhere (moqui.crypto.elsewhere()), and an
encrypted room there opens in the shell's Chat. The shell's device is new, not moved from a browser's store; its older
room keys come from the key backup.
A user's key queries, claims and to-device sends reach their own devices and the devices of users who share a room (both members now) or a live call (not ended, neither denied nor removed) with them. Others are left out as if they had no devices.
- One-time keys. A claim locks the device's row and takes its oldest unclaimed one-time key, so two claims at once never get the same key. With none left, the device's fallback key answers. One user gets at most 10 of a device's one-time keys a minute; past that the fallback key answers, so a user in reach cannot drain them.
- To-device messages. Each is queued per device at the device's next stream position, and kept until the device
acknowledges it. A sync from a position deletes everything at or before it.
- A queued message wakes the recipient's tabs with
{kind: 'toDevice'}onchatUser:<userId>. The push carries nothing of the message. - A retried send whose transaction ID is still queued is not queued again, also when retries come at once: the sender's device row is locked with the targets' rows, in one order, before the transaction is looked up.
- A queued message wakes the recipient's tabs with
- Device lists. A sync answers the users in reach whose devices changed since the last one, so the machine queries them again.
The server keeps public keys, Olm ciphertext and routing only. Plaintext and private keys never leave the browser.
Encrypted calls (W8) use this reach as it is: their browsers send each other their SFrame keys as the to-device event
io.moqui.call.key, to the devices the call's roster names (WebRTC, Encrypted calls).
Revoking a device also takes its legs out of the encrypted calls it is in, so the others rotate their keys without it.
Call guests have no device: an encrypted call takes no guest, so the reach rules are unchanged.
The services take and answer Matrix's payloads, so the Matrix client API (C6a) can serve the same services at
/_matrix/client/v3/….
/ChatKeys/… |
Service | Matrix |
|---|---|---|
device, devices, rename, revoke, whoami |
create#, find#, update#, revoke#ChatDevice, get#ChatKeyIdentity |
login's device, devices, account/whoami |
upload |
upload#Keys |
keys/upload |
query |
query#Keys |
keys/query |
claim |
claim#Keys |
keys/claim |
send |
send#ToDevice |
sendToDevice/{eventType}/{txnId} |
sync |
sync#ToDevice |
/sync: to_device, device_lists (changed, left), device_one_time_keys_count, device_unused_fallback_key_types |
storeKey |
get#ChatDeviceStoreKey |
none: the store passphrase |
signingUpload |
upload#CrossSigningKeys |
keys/device_signing/upload |
signaturesUpload |
upload#KeySignatures |
keys/signatures/upload |
backupVersionCreate, backupVersion, backupVersionUpdate, backupVersionDelete |
create#, get#, update#, delete#KeyBackupVersion |
room_keys/version (POST, GET, PUT, DELETE) |
backupKeysPut, backupKeys, backupKeysDelete |
store#, get#, delete#BackupKeys |
room_keys/keys[/{roomId}[/{sessionId}]] (PUT, GET, DELETE) |
backupVersions |
find#KeyBackupVersions |
none: the versions not deleted, with their public keys |
settings, settingsStore |
get#, store#ChatKeySettings |
none: room keys to verified devices only |
The key counts (one_time_key_counts, device_one_time_keys_count) always hold signed_curve25519, 0 when none is
left: the machine updates its count only from an algorithm the answer names, so a device whose keys were all claimed
would otherwise never upload more. A sync's since past the last position queued counts as that position.
- Request shape. Each is a POST with a JSON body (
devices,whoami,backupVersionandbackupKeysalso take a GET) and the session's CSRF token. Matrix's path parts are body fields:version,roomId,sessionId. - Device. The device is named by
deviceIdin the body, where Matrix takes it from the access token. - Errors. A refusal answers
{errors, reasonCode}and the refusal's own fields:notFound,revoked,keysChanged,keyExists,badKeys,noMasterKey,tooManyKeys,tooManyDevices,tooLarge,tooMany,badRequest,algorithmChanged,wrongVersion(withcurrent_version),reauthRequired(no sign-in in the last five minutes); in the browser alsobusy(another tab has the store) andstoreUnreadable.
Store key. storeKey ({deviceId}) answers {storeKey}, the passphrase the browser
passes to OlmMachine.initialize as store_passphrase, so the IndexedDB store is encrypted: 43 characters of URL-safe
base64, derived (not stored) and the same at each ask. Only the device's own user gets it, so a copied browser profile
without a signed-in session cannot open the store. A revoked device gets none. It is not logged or in another answer.
Recent sign-in. These need a sign-in in the last five minutes, else reauthRequired (Recent
sign-in): a cross-signing reset that replaces the master key, backupVersionCreate (a new
backup, also the first, and "New recovery key"), backupVersionDelete, backupKeysDelete, a backupVersionUpdate that
changes the backup's public_key (new signatures alone need none), and revoke of a device with keys (see Devices).
The page asks the user for the password and second factor, or a fresh SSO sign-in, and tries again (moqui.reauth).
Cross-signing.
signingUploadtakes{master_key, self_signing_key, user_signing_key, reset}, each key a MatrixCrossSigningKeyof the session's user with one ed25519 key, and answers{changed}. The session stands for Matrix's user-interactive auth:- the first upload is allowed, and the same keys again change nothing;
- a different master key is refused (
keysChanged) unlessresetis true, the user's explicit "reset my identity". A reset deletes the old keys and every signature by or over them; - without
master_keythe user must have one (noMasterKey). A self-signing or user-signing key must carry a signature by the master key.
signaturesUploadtakes{signed}, wheresignedis Matrix's request body: Matrix user ID to key ID (a device ID or a cross-signing public key) to the signed object. It answers{failures}, Matrix user ID to key ID to{errcode, error}for each key refused. Only signatures by the caller's own keys are stored, where that key may sign:- the caller's devices by their self-signing key;
- their master key by their devices;
- their self-signing and user-signing keys by their master key;
- the master key of another user in reach by their user-signing key.
- The server checks who may sign what, not the signatures themselves; the clients verify them.
query#Keysanswersmaster_keysandself_signing_keysof the users in reach, anduser_signing_keysof the caller only. The stored signatures are merged into each signed object'ssignatures: a user's own to everyone in reach, another's only to the signer.- A change of a user's cross-signing keys or signatures is a device-list change, which syncs name in
device_lists.changed.
Device lists left. A sync's device_lists.left names the users the caller was in reach of through a room and no
longer is (no shared room, no live call), because a membership ended since deviceListSince. The client stops
tracking them.
Key backup (m.megolm_backup.v1.curve25519-aes-sha2; the server stores session_data as the browser made it).
- Disappearing messages (plans/Comms-Messaging.md §18.3 phase 16). When the expiry deletes an encrypted room's
messages, a backed-up session (room ID
!<chatRoomId>:<chat@server-name>) that no event of the room still uses (ChatEvent.megolmSessionId) goes from every user's backup, but only once it can be in use no more: its newest use past the room's rotation period (the timer, a week at most) and 10 minutes. Till then it waits (ChatExpirySession, itsdueDate), and the expiry worker deletes it then, unless a newer message of the room uses it again. In a room with a timer the sending browser rotates its session at the timer (a week at most) or every 100 messages; a timer change is a system event, on which every member's page that shows the room starts a new session, and a browser with the room closed starts one at its next send, as its encryption settings changed. So no session outlives the messages it opens. The device's own store keeps its inbound copy: the SDK has no delete for one, and it opens nothing once the ciphertext is gone. - Versions. Versions are
"1","2", … per user and never reused.backupVersionCreatetakes{algorithm, auth_data}and answers{version}; the new version is the current one.backupVersiontakes{version}, or nothing for the current (the latest not deleted). It answers{algorithm, auth_data, count, etag, version}, ornotFound.backupVersionUpdatetakes{version, algorithm, auth_data}; the algorithm cannot change (algorithmChanged).backupVersionDeletetakes{version}: the version is marked deleted and its sessions go.
- Keys.
backupKeysPuttakes{version, rooms},roomsas Matrix's body (room ID to{sessions}, session ID to{first_message_index, forwarded_count, is_verified, session_data}), and answers{count, etag}. Only the current version takes keys: another iswrongVersionwithcurrent_version(Matrix'sM_WRONG_ROOM_KEYS_VERSION).- A session already there is replaced only by a better one: a verified one, then a lower
first_message_index, then a lowerforwarded_count. backupKeystakes{version, roomId, sessionId, offset}and answers{rooms, has_more}in that shape, empty when nothing matches; at most 10,000 sessions fromoffset.backupKeysDeletetakes{version, roomId, sessionId}and answers{count, etag}.
- Etag and room IDs.
etagis a string that changes with the version's keys. Room IDs are the Matrix room IDs the browser names (!<chatRoomId>:<chat@server-name>), opaque to the server, at most 255 characters. - Bounds.
session_dataup to 16 KB each, 1,000 sessions in one put, 100,000 held by a user (tooMany).
User IDs. A Matrix user ID is @<localpart>:<chat@server-name>.
- The localpart is the userId with Matrix's mapping of other character sets: an upper-case letter is
_and the letter,_is__, and any other byte is=xx. - Set
chat@server-name(defaultlocalhost) before the first device. A change makes every device new, and C6a needs it to be the domain.
A direct or private room may be made encrypted (create#Room with encrypted; New room, Encrypted), and that cannot be
turned off. A public or record room is never encrypted (encryptedRoom), and an encrypted room stays members only. An
encrypted direct room is a room of its own beside the plain direct room of the same people.
Encrypted by default (Comms-Messaging §6.5). Chat's
createDirect and createRoom go through ChatScreenServices.create#ChatRoom. With no encrypted given:
- a direct room answers the encrypted direct room of exactly these people when there is one, else the plain one when
there is one (it keeps opening, though everyone now has a device), else a new room, encrypted when the user and every
member have a crypto device in use (
check#DevicesReady); - a private room is encrypted on the same rule; a public room never.
A device in use is not revoked, has uploaded its identity keys and was seen (a key upload or a sync) in the last
chat@device-active-days (90). One Chat made by itself (automatic) counts only once it was seen on a later day than it
was made, or its user verified it (a cross-signing signature over it), so one private window does not make its user one
with a device. create#Room's own default stays plain, so XMPP's direct chats, a call to a person and
agents are unchanged. createDirect with encrypted true is Start an encrypted chat: a plain direct room's menu and
start offer it when its people all have a device, it makes or opens the encrypted direct room of the same people, and
that room's start links back to the plain one. moqui.chat.directRoomFor opens the encrypted direct room first.
The page asks get#EncryptionDefault (Chat's encryptionDefault) for the label of a dm link's unsaved chat, New room's
Encrypted (until the user sets it) and Start an encrypted chat. It answers one bit for up to 50 people, nothing of their
devices; a person an app's chat-target provider (or an external caller's reach) refuses, or one unknown or disabled,
counts as having none, and the same device query runs for them, so the answer's time tells no more than its bit. Past
600 people an hour a user it answers false (rateLimited): each person asked about claims a slot of the hour with the
cache's putIfAbsent, which is atomic, so asks at once cannot pass the limit together. The cache
(moqui.chat.encryption.default.asked) is distributed: one count for the cluster when a distributed cache factory is
configured, a count per node with the default local one. The server only picks the default: the room made has its label,
and an encrypted room never becomes plain.
Two makes of the same people's direct room at once (two Start clicks, two people starting the chat with each other) wait
for each other: create#ChatRoom locks the people's UserAccount rows in one order first, so the second finds the room
the first made. A twin made all the same (by a server that does not take that lock) is left alone: the oldest is answered,
and directRoomFor picks the oldest too. The Start buttons and Start an encrypted chat take one click at a time.
What the server keeps. A message, edit or reaction is the Megolm ciphertext the sending browser made (the
m.room.encrypted content, in contentJson.encrypted, ChatEvent.encrypted Y). In the clear, as in Matrix:
- the relation targets:
replyToEventSeq,threadRootEventSeq,editsEventSeq,relatesToEventSeq(what an edit, reply, reaction or redaction points at); - the mentioned users (
mentionUserIdListon send and edit): they are counted and notified, without text.
Bodies, reaction keys, file names and types are in the ciphertext. No bodyText, snippet or notification summary is
written; the room list and the terminal show "Encrypted message". A file is uploaded encrypted and kept as an opaque blob
named encrypted, application/octet-stream; its name, type, key and hash travel in the message (io.moqui.files, each
with Matrix's EncryptedFile info). find#RoomFiles lists them without names or types, each with its message's ciphertext
(encryptedContent), and refuses a filter: the browser decrypts each file's details from its message and sorts the files
into the details' Media, Files and Voice tabs itself. A voice note is such a file (audio/...), played from its
decrypted blob. The server keeps no links of the room (ChatEventLink): the Links tab lists the links of the messages
the browser has decrypted. find#RoomReactions and find#ChatActivity give the ciphertext of each message and reaction,
with no snippet, and find#RoomReactions takes no reaction key.
Refused in an encrypted room (reasonCode encryptedRoom, each spec'd with the parameters that pass in a plain room):
- a plaintext body, edit or reaction key (and ciphertext in a plain room:
notEncrypted); - server search of the room, link previews, agent members (
add#Memberandset#MemberRolewithCmrAgent), assist cards and agent delivery; - polls; forwards into or out of the room; records on a message;
- Create from and File on record (framework transitions, and Mantle's
findOrCreate#ChatCommunicationEvent), Chatter's chat source (Mantleget#RecordTimelineleaves it out), BOSS Home's snippets ("Encrypted message"); - bridges (
store#RoomBridge); XMPP serves no encrypted room (C3a); call-link chat (W8); - the terminal's send ("open it in a browser").
Keys and rotation. Before a message, the sending browser shares the room's Megolm key with every device of each
member that has none (Olm to-device, encryptRoom). The machine starts a new session when a member or a device it shared
with is gone (it compares with the members the page gives), and the room page starts one at once when a member leaves or
is removed (rotateRoom). A device revoked by its user drops out of key queries, so the next message's session leaves it
out. device_lists.left tells a browser to stop tracking users it shares no room with. Rotation cannot take back what a
device already holds. A member who joins later reads earlier messages only if a member's device shares those keys, or
from their own key backup.
Decrypting. The room page decrypts each page of the timeline and each pushed event before it is shown
(moqui.chat.openEvents, openEvent). The browser decrypts an event as $<chatRoomId>.<eventSeq>:<server> in
!<chatRoomId>:<server>, as the server numbers it. An edit shows its own ciphertext (encryptedEventSeq); reactions come
as encryptedReactions, which the page decrypts and counts, and an encrypted reaction is taken back by its own
reactionEventSeq. Decrypted HTML goes through DOMPurify. A message whose key this device lacks says so, and is decrypted
again when keys arrive (onRoomKeys).
No plaintext leaves the browser. The outbox (localStorage) keeps the ciphertext; the text shown while a message waits is kept in the page only. Drafts of an encrypted room are kept in the page, not in storage.
Key backup. Settings, My devices, Set up key backup:
- sets up cross-signing when the user has none (an identity made on another device is left as it is);
- makes a recovery key (
BackupDecryptionKey, shown once in Matrix's encoding: base58 of 0x8B 0x01, the key and a parity byte, in groups of four); - makes a backup version (
m.megolm_backup.v1.curve25519-aes-sha2); from then on the machine backs up each room key, encrypted to the recovery key, toroom_keys/keys.
A new device reads older messages only after Restore with the recovery key (or when another of the user's devices shares
the keys). A wrong key is refused (wrongRecoveryKey) and nothing is reset. Restore reads the version the recovery key
opens (backupVersions lists each with its public key): the current one, or an older one that "New recovery key" left with
its keys. Only the current version takes this device's keys from then on.
Only verified devices. A user may turn on "Send my room keys only to verified devices" (Settings, My devices; the
preference CHAT_VERIFIED_DEVICES_ONLY), and a moderator of an encrypted room the room's own setting (room settings;
ChatRoom.verifiedDevicesOnly, set#RoomVerifiedDevicesOnly). With either on, the sending browser shares the room's keys
only with verified or cross-signed devices (matrix-sdk-crypto's onlyTrustedDevices); a device nobody verified cannot read
what follows. A change of the setting, and the first message of a page under it, starts a new session. The browsers apply
it; the server only keeps it. The sender is told who cannot read a message (COM-UI-013): the browser notes the devices
the share left out (leftOut), and the message shows "Not readable by ...: their devices are not verified" with Verify
(the person, below; My devices for the user's own), kept in this browser per account so a reload or another tab still
shows it. The machine sends each left-out device an m.room_key.withheld with the code m.unverified, so that device's
page says the sender has not verified it and how to verify each other (decryptRoom's withheld), not the key backup's
text. An encrypted call warns when its roster has a device of a participant this browser has not
verified (moqui.callKeys.state.unverified; the call's keys still go to the roster's devices).
Verifying another person (COM-UI-013). Chat's Members has Verify by each person of an encrypted room who is not
verified, and the room's banner and the "Not readable by" line open it for the first such person: their devices as this
store knows them (roomTrust), each with Verify (verifyDevice(theirUserId, deviceId), the same to-device SAS or QR flow
as one's own), and the verifications with them in the shared m-chat-verification card (WebrootChat.js; My devices uses
it too). A request another person makes shows in the room open in this browser (named, or "someone outside this room";
closing it cancels the request; its end shows a moment) and on My devices (named through get#PeerNames: only people
this user's devices reach). The machine drops a request from someone whose devices it does not track yet (a browser that
never opened a room with them): it then tracks them, so the asker's Try again reaches it. A completed comparison
verifies their device locally; with cross-signing on both sides it verifies their identity (the user-signing key signs
their master key), so every device they signed is verified. A person is shown verified (a check in Members and by their
messages) when their identity is, or every device of theirs is.
A verified person changed (§6.1 rule 3). Without only verified devices, encryptRoom first checks the members: a
verified person is one whose identity is verified, or one with a device verified here by emoji. A device of theirs that is
not verified (by emoji here, or signed by them with their identity verified) and not let through for this room with the
same key is a newDevice; a person verified before whose identity changed, not let through with this master key, is a
changedIdentity. It refuses with reasonCode verifiedUserProblem and the problems (problemsOf is the rule on
plain data); once the check passes it shares with all devices, so the check is the one gate, and a device verified by
emoji passes (Verify, then send). Chat then asks, per person: Verify, or Send anyway (acceptProblems(chatRoomId, problems)): what is let through is kept in this browser per account and room, by the device's ed25519 key or the
identity's master key, and never as the SDK's trust: the device gets the room's keys from that message on and stays not
verified, so "only verified devices" (the SDK's onlyTrustedDevices) still leaves it out. A failed share is said plainly,
never with the SDK's words. The same question comes before an edit or a reaction. The machine's devices and identity
callbacks are relayed to every tab (onTrust), so an open room reads its trust again. A message's sender has the check
only when it came from a verified device of theirs (verifiedSender); a verified person's message from a device that is
not has a warning mark.
Verification. My devices shows each device's verification as this browser's store holds it (trust is the clients'):
Verify asks another device; the two compare emoji (SAS), or one shows a QR code that the other reads with its camera
(where the browser has BarcodeDetector). The steps travel as to-device events. The device that did not start the
emoji comparison accepts it by itself (the SDK leaves Sas.accept to the app): the user took the request, and comparing
the emoji is the confirmation. While a verification is open the page syncs every 5 seconds, so a lost push does not
stall it and one that timed out ends; My devices says when it waits for the other device, how long is left, and why
one ended, with Try again. A verified device of one's own is signed
with the self-signing key (keys/signatures/upload), so the user's other devices trust it too. The server keeps no
verified flag of its own: it would establish no trust.
A new browser, phone or desktop app makes its device when Chat opens; what was sent before was encrypted for the user's
other devices only. Messages sent after it was made reach it, since the members' browsers hear of it at their next sync
(device_lists.changed). moqui.crypto.setupStatus() says where it stands: {deviceId, backup (the server's current backup version, or null), restored (this device holds that backup's key), verified (signed by the user's verified identity, or verified here with another of their devices), otherDevices (the user's other devices in use, each with its name, when it was added and when last seen)}. moqui.chat.setupNeeded is the rule: it is set up once it can read what
was sent before it, that is when it holds the current backup's key, or, with no key backup on the server to receive,
once it was verified with another device of the user's (which forwards the room keys it holds). Verified while a backup
exists is not yet set up: the card says "Verified. Getting your keys from the other device…" (setupWaiting), and after
two minutes "Your other device did not send the keys", with Try again (moqui.crypto.requestSecrets() asks again) and Use
your recovery key. Only a user with a key backup or another device needs it (a first device needs none; its encrypted
rooms offer Set up key backup once).
Until it is set up, an encrypted room shows "Set up this device to read messages sent before it was added", with Set
up, in its banner's place, and each message it cannot read says "Sent before this device was set up", with Set up (the
m.unverified text stays). Set up opens m-chat-device-setup (Chat; My devices has it at its top):
- Recovery key: Restore (
restoreBackup); a wrong key is said plainly and nothing is reset. - Another device: the user's other devices in use (seen in
chat@device-active-days), by name and when last seen, each with Verify (emoji or QR, in the card). The other device shows the request in Chat as well as on My devices, naming the new device and when it was added. Once it is done, this device asks its verified devices for the secrets it lacks (requestMissingSecretsIfNeeded): the cross-signing keys, which the SDK imports, and the backup key (m.megolm_backup.v1), which the SDK sends only to a verified device of the same user. A backup key is used only when it opens the server's current backup (its public key); then the backup is imported as with the recovery key, and this device backs up to it. One received while no page handled it is used when the store next opens. With no backup, the verified device forwards the room keys it holds when asked, while it is open. - Not now closes it, kept per account and device in this browser.
A full-screen dialog on a phone, 480 px on a desktop.
In moqui.crypto (the store's tab runs each call; another tab's call is relayed to it):
| Function | What |
|---|---|
ensureDevice() |
Loads the module and the store, makes the device on first use, uploads its keys. Resolves to {userId, deviceId, matrixUserId} |
sendToDevices(targets, eventType, content) |
Olm-encrypts content as an event of eventType for each device of targets and sends it. targets is a list of userIds (every device of each) or {userId, deviceIds}. It never goes to this device. Resolves to {sent, devices, skipped}: sent is how many the server queued; devices and skipped are lists of {userId, deviceId} |
onToDevice(fn) |
fn({type, content, senderUserId, senderMatrixId, senderDeviceId, senderCurve25519Key, verified}) for each to-device event that decrypted. Returns the unsubscribe |
devicesOf(userId) |
The devices of a user as this store knows them: [{deviceId, displayName, ed25519Key, verified}] |
sync(), close(), forget() |
A sync now; close the store; revoke this device and delete its store (a refused revoke deletes nothing) |
startOver() |
After state.problem: delete the unreadable store and revoke its device; the next ensureDevice makes another |
settingsChanged() |
The verified-devices-only settings are read again before the next room message |
thisDeviceId() |
This browser's deviceId for the signed-in user, without loading anything |
sealLocal(text), openLocal(sealed) |
What this device keeps in the browser's storage, sealed ({v, iv, data}: AES-GCM under a key derived with HKDF from the device's store key, moqui-chat-held-draft, the user and device as its info), and opened again: an encrypted room's scheduled message held by the device that scheduled it until its time (Comms, Send later). Neither the stored text nor the server alone opens it; the key lives in the page only, and a store key that changed (a revoke) opens nothing |
state |
{status, deviceId, matrixUserId, error, role, verifications, problem}; status is idle, loading, ready or error; role is leader or follower; problem is {reasonCode: storeUnreadable, deviceId} when the store cannot be read |
encryptRoom(chatRoomId, memberUserIds, eventType, content) |
Shares the room key with the members' devices that lack it, and resolves to the Megolm ciphertext of the event |
decryptRoom(chatRoomId, {eventSeq, sentDate, senderUserId, encrypted}) |
{type, content, verified}, or {error, withheld} when this device has no key for it (withheld: the code its sender gave, m.unverified under only verified devices, else null) |
leftOut(chatRoomId) |
The devices the last message this browser encrypted for the room was not shared with: [{userId, deviceId, displayName}], empty unless only verified devices is on |
roomTrust(chatRoomId, memberUserIds) |
{verifiedOnly, users: [{userId, identity: {known, verified, changed}, devices: [{deviceId, displayName, verified}]}]}, this device left out: the room's label (a check when all are verified, else Verify), each person's check, and who the next message leaves out |
acceptProblems(chatRoomId, problems) |
Send anyway after verifiedUserProblem: each new device (by its key) and changed identity (by its master key) let through for the room, kept in this browser per account; the SDK's trust is not changed |
problemsOf(people, allowed) |
The rule of the check before a send, on plain data |
onTrust(fn) |
fn([userId]) when users' devices or identities change, in every tab. Returns the unsubscribe |
rotateRoom(chatRoomId) |
A new session for the room's next message |
onRoomKeys(fn) |
fn([{roomId, sessionId}]) when room keys arrive (from a member, or a restore). Returns the unsubscribe |
encryptFile(blob), decryptFile(data, info) |
{blob, info} for upload; the decrypted bytes (the hash is checked) |
setupStatus() |
{deviceId, backup, restored, verified, otherDevices: [{deviceId, displayName, createdDate, lastSeenDate}]}: whether this device reads what was sent before it (A new device) |
requestSecrets() |
The secrets this device lacks asked of the user's verified devices again (Try again) |
enableBackup(), backupStatus(), restoreBackup(recoveryKey) |
{version, recoveryKey}; {version, enabled, total, backedUp}; {version, imported, total, failed, current} (the version the key opens, an older one too) |
crossSigningStatus(), setupCrossSigning(reset) |
{hasMaster, hasSelfSigning, hasUserSigning, identity, verified} |
verifyDevice(userId, deviceId), verification(flowId, action, arg), dismissVerification(flowId) |
Start a verification (its flowId); a step: accept, sas, confirm, mismatch, cancel, showQr, scanned (the code's bytes), qrConfirm. state.verifications lists them with their emoji or QR image |
In moqui.chat: e2eeLabel(room, trust) (the room's label, Comms-Messaging §6.2:
{state, lock, verified, icon, banner, hint, verify, text}), trustOf(roomTrust's answer, me) ({allVerified, unverified, leftOut, people}), verifyTarget, problemsText, leftOutText, noteLeftOut and leftOutOf(roomId) (who could not
read my messages, kept in localStorage per account), undecryptableText(withheld, senderName), sealMessage(roomId, memberIds, html, files) (the send parameters {encryptedJson, mentionUserIds}),
sealReaction, sealFile, openFile(url, file, roomId) (a blob URL), releaseFiles(roomId, ids),
openEvents(roomId, list, attachmentUrl), openEvent(roomId, event, attachmentUrl),
myReaction(roomId, messageSeq, key, me), setupNeeded(setupStatus), setupWaiting(setupStatus),
directRoomFor(rooms, userIds, me, plain) (the encrypted one first, the oldest of each kind) and makeDeviceSoon()
(Chat's device in idle time, ensureDevice({automatic: true})). A decrypted file's blob URL is revoked when its room closes (the last view of it
goes: closeRoom), or for the attachments named; opened again, it is fetched and decrypted again.
| Property | Default | What |
|---|---|---|
chat@server-name |
localhost |
The server name in device user IDs |
chat@device-active-days |
90 |
A device seen in this many days counts for the encryption default (Encrypted by default) and toward the 50 a user may hold |
chat@device-auto-expire-days |
30 |
A device Chat made by itself, never verified, is revoked by the daily job after this many days unseen |
chat@to-device-retention-days |
30 |
How long a to-device message waits for a device that does not acknowledge it (the job clean_ChatToDevice_daily, which also deletes one-time keys claimed over a day ago) |
chat@store-key-secret |
generated | The secret the store keys are derived under. A new value makes every browser's store unreadable (each starts over and reads older messages from the key backup) |
Content Security Policy. WebAssembly needs 'wasm-unsafe-eval' in a policy that sets script-src. The default
policy sets none.
-
Server:
./moq test framework --spec ChatKeys. It covers:- user IDs that map back, and identity keys that cannot change;
- another user refused with the very same parameters;
- reach by room and by live call;
- concurrent claims (8 threads, 32 claims of 20 keys), at most 10 a minute for one claimer and the fallback key past it, another claimer not held;
- the queue's cursor, acknowledgement and repeated transactions, six retries of one send at once queuing one copy, and a wake push with no content;
- device-list changes, a revoked device, a member who left the room, and a sender the server sets;
- a revoke refused without a recent sign-in with the same parameters, allowed after
reauthenticate#User; a device without keys revoked without one; an account with a second factor confirming with the password and then the code.
-
Server, trust and backup:
./moq test framework --spec ChatKeyBackup. It covers:- a store key answered only to its own user, the same at each ask, absent from the device list and its row, another after a revoke;
- a reset, a new backup, a new backup public key and deleting backed-up keys refused without a recent sign-in (also after another user's login in the session), with the same parameters; the versions listed with their public keys;
- cross-signing keys uploaded once, the same again a no-op, a different master key refused unless reset;
- signatures stored only by keys that may sign, refused out of reach and by another signer, and merged into key queries; a reset deleting every signature by or over the old keys;
- backup versions, a put to another version refused with
current_version, the better-session rule, keys by room and by session, deletes, counts and etags; device_lists.leftwhen the only shared room ends.
-
Server, the encryption default:
./moq test framework --spec ChatEncryptionDefault: the bit true only when the asker and everyone have a device in use, false for none, a revoked or keyless device, one not seen in 90 days and an unknown user; nothing else answered; more than 50 people and past 600 an hour refused; an automatic device counted once seen on a later day or verified; the job revoking an unused automatic device and keeping a verified one and one the user made; the 50 devices counting only those in use.BasicCommsEncrypted's last feature: a direct, group direct and private room encrypted when all have devices and plain otherwise, the encrypted direct room answered after a device went, a plain direct room kept and Start an encrypted chat beside it, an explicit choice kept, a public room never,create#Room's own default plain, the oldest of two encrypted direct rooms of the same people answered, and the bit false for a person an external user's reach leaves out. -
Server, encrypted rooms:
./moq test basic-comms --spec BasicCommsEncrypted(8 features). Every refusal above with the parameters that pass in a plain room; no plaintext inbodyText, the snippet, search, the ChatMention notification or the stored content; the timeline's ciphertext of an edit and its reactions; the terminal. -
Browser, encrypted rooms:
./moq test-client basic-comms --serve --spec EncryptedChatFlow(three users, three pages; about 19 seconds with the server):- an encrypted message and an encrypted image both ways, the image shown from a decrypted blob; nothing posted, and nothing in localStorage, holds the plaintext;
- a member who leaves cannot decrypt the next message, which is in a new session;
- a second tab (a window of the same browser) reads through the leader, and takes the store when the leader closes it;
- a new device of the same user reads nothing older until it restores the backup with the recovery key; a wrong key is refused; after "New recovery key", the old recovery key still restores its older version on another new device;
- only verified devices: with the sender's setting, or the room's (set by its owner, refused to a non-member), an unverified device cannot read the next message;
- a store re-made under another key is refused
storeUnreadableand kept, again on the next try; "Start over" makes a new device and drops the old one.
-
Browser, the chat store:
./moq test-client webroot --offline --spec WebrootChat: a closed room's decrypted files revoked, another room's kept, and a file decrypted again when opened again. -
Browser, encrypted calls:
EncryptedCallFlowalso checks the warning of unverified devices on the roster. -
Browser, a new device:
CryptoFlow's first feature: after two devices of a user verify by emoji, the new one (the first has a key backup) needs setting up before, then receives the backup key from the first and holds it, with no recovery key.ShellSync(offline, the bundled shell): the set-up bar and card (Restore, Verify; verified with the backup key not here yet, the card waits, then says the keys did not come, and Try again asks again), a dm link's unsaved chat with its label, Start an encrypted chat and the link back, My devices in the shell. -
Browser:
./moq test-client basic-comms --serve --spec CryptoFlow. Two Chromium pages of two users who share a room:- each makes a device;
- one Olm-encrypts a to-device event, and the other decrypts it with the sender's device;
- no body the sender posted holds the plaintext;
- after the receiver revokes its device, a send reaches nothing.
About 5 seconds.
Not checked live: Element or another Matrix client against these endpoints (C6a serves them), and Firefox and
Safari (the client specs run Chromium), and the dialogs of moqui.reauth (a spec page has always just signed in). The
client spec CryptoFlow verifies two devices of one user by emoji; QR verification has no spec, since reading a code
needs a camera and BarcodeDetector (Chrome on Android, macOS and ChromeOS; not headless).