Appearance
Chat content (v1)
This is the canonical client contract for what goes inside the end-to-end encrypted envelopes of messaging (see Chat and the messaging reference), and how encrypted attachments use /messaging/attachments. The server never reads any of it. iOS, Android and web follow it so they can read each other's messages. Paths are under /v1.
The transport is Signal's libsignal. The iOS app uses LibSignalClient v0.108.7: X3DH/PQXDH with Kyber1024 prekeys, the Double Ratchet, and sender keys for groups. Other clients use the libsignal binding for their platform (Java/Kotlin, Node/TypeScript). Use the same tag or a later one that still produces the key types below.
1. Keys and addresses
| What | Format on the wire (base64, standard alphabet, padded) | libsignal |
|---|---|---|
identityKey | 33 bytes, 0x05 + Curve25519 | IdentityKeyPair.identityKey.serialize() |
signedPreKey.publicKey, preKeys[].publicKey | 33 bytes, 0x05 + Curve25519 | PublicKey.serialize() |
kyberPreKeys[].publicKey, kyberLastResortPreKey.publicKey | 1569 bytes, 0x08 + Kyber1024 | KEMPublicKey.serialize() |
signature (signed prekey, Kyber prekeys) | 64 bytes, XEdDSA by the identity private key over the serialized public key above | PrivateKey.generateSignature(message:) |
registrationId | integer 1 to 16380 | random per device install |
| key ids | integer 0 to 16777215 | per kind, counting up |
- Device keys (
PUT /messaging/keys/devices/me): one identity key per device install, one signed prekey, one Kyber last-resort prekey, plus up to 100 one-time EC prekeys and 100 one-time Kyber prekeys per upload. The server acceptskyberLastResortPreKeyas optional for older clients; every client following this spec sends it. The server checks key lengths and type bytes, never signatures: clients check signatures on every bundle. - Refill: when
GET /messaging/keys/devices/me/prekeys/count({ ec, kyber }) reports fewer than 20 of a kind, orkeys:low { ecRemaining, kyberRemaining }arrives (sent once at 19 left and again at 0),POST /messaging/keys/devices/me/prekeyswith up to 100 more per kind, staying under the cap of 500 stored keys per kind (MESSAGING_PREKEY_LIMITabove it). - Rotation: a new signed prekey and Kyber last-resort key every 30 days (
PUT /messaging/keys/devices/me/signed-prekey { signedPreKey, kyberLastResortPreKey }). Keep the old private records for 30 more days so lateprekeymessages still decrypt. - Protocol address (local to each client, never sent):
name = "<userId>.<deviceId>"(both are v2 UUIDs, lowercase),deviceId = 1. Every client must derive the sender's address the same way from aDelivery'ssenderUserIdandsenderDeviceId. Sender keys are stored under this address. - Trust: trust on first use. A changed identity (
keys:changed) archives that device's session; the next send fetches a new bundle. Show "security code changed".
2. Sending
- Find the recipient devices. These are every keyed device of every active member, plus my other devices, never the sending device:
GET /messaging/keys/users/:userId/devicesper member, including me. My own device id is theisCurrentrow ofGET /me/devices. - For a device without a session:
POST /messaging/keys/users/:userId/bundles { deviceIds? }(up to 50 ids; leavedeviceIdsout for all the person's devices). Each bundle claims one one-time EC prekey (preKey, null when none are left) and one Kyber prekey (kyberPreKey, the last-resort key withisLastResort: truewhen none are left). Check both signatures in each bundle, thenprocessPreKeyBundle. - Direct chat: encrypt the padded plaintext (section 3) per device with
signalEncrypt. Envelope{ deviceId, type: "prekey" | "whisper", ciphertext }, fromCiphertextMessage.messageType.preKeyor.whisper. - Group chat: encrypt once with
groupEncryptunder this device's distribution id for the conversation. SendsharedCiphertext = base64(serialize())andsenderKeyDistributionId, plus one{ deviceId, type: "sender_key" }envelope per device, with no ciphertext. Before the first send, and onsender_key_missing, distribute the key (section 5). Sender-key envelopes are refused in direct chats. message:send(orPOST /messaging/messages) with{ conversationId, clientMessageId, kind, envelopes, sharedCiphertext?, senderKeyDistributionId?, replyToMessageId?, forwardOfMessageId?, attachmentIds?, hasLink, mentionedUserIds, mentionsEveryone, momentId? }. Retry with the sameclientMessageId(1 to 64 ofA-Za-z0-9._:-).- Limits: one envelope's
ciphertext(andsharedCiphertext) is at most 262,144 base64 characters, at most 5,000 envelopes, 30attachmentIds. - The answer is a
SendResultindata(and the socket ack), not a problem:201 { status: "sent", message }, or409with one of:{ status: "device_mismatch", missingDeviceIds, extraDeviceIds, duplicatedDeviceIds }: drop sessions forextraDeviceIds, fetch bundles formissingDeviceIds, send one envelope per device, encrypt again and resend.{ status: "sender_key_missing", deviceIds }: distribute this device's sender key todeviceIds(section 5), then resend.
- Limits: one envelope's
- Save the plaintext locally under the returned
message.id. The server keeps no copy.
3. Plaintext
plaintext = utf8(JSON content) || 0x80 || 0x00 * nPad so the total length is a multiple of 160 bytes, which hides the exact length. A reader strips trailing 0x00 bytes, then the single 0x80, then parses JSON. Unknown fields are ignored. Writers omit fields they do not use.
json
{
"v": 1,
"kind": "text",
"text": "Send it over",
"quote": { "messageId": "uuid", "authorUserId": "uuid", "text": "So good. She played the new one live first" },
"song": {
"recordingId": "uuid",
"title": "Lagos Nights",
"artist": "Tems Adeyemi",
"artworkUrl": "https://… (optional, may expire)",
"url": "https://spread.plemuz.com/song/<recordingId>"
},
"attachments": [
{
"id": "uuid (from POST /messaging/attachments)",
"kind": "image | video | audio | voice_note | file | sticker",
"contentType": "image/jpeg",
"fileName": "photo.jpg",
"size": 123456,
"key": "base64(32 bytes)",
"sha256": "hex of the encrypted blob (equals the server's ciphertextSha256)",
"width": 1080, "height": 1350,
"durationMs": 14000,
"thumbnail": "base64 JPEG ≤ 2 KB (optional)"
}
],
"sentAt": 1764320000000
}| Field | Rule |
|---|---|
v | Content version. Always 1 for this spec. A reader that meets a higher major version shows "Update Plemuz to read this message". |
kind | Same value as SendMessage.kind: text, image, video, audio, voice_note, file, song_share, moment_reply, contact, location. |
text | Message body, or the caption of media. Up to 16,000 characters. |
quote | Copy of the replied-to line, so a reply reads well on devices that never had the original. replyToMessageId on the request carries the id for the server. |
song | For song_share. Readers open recordingId in the app, or url elsewhere. |
attachments | For media kinds. The ids also go in SendMessage.attachmentIds. |
sentAt | Sender's clock, in milliseconds. For display only; the server's createdAt orders messages. |
- Edits (
message:edit/PATCH /messaging/messages/:id): the new envelopes carry a complete replacement content object with the samekind. The server'srevisionandeditedAtsay it is an edit. Readers replace the stored plaintext. - Deletes, reactions, pins, receipts, typing: plaintext metadata handled by the server. Never put these in envelopes.
- Moment replies:
kind: "moment_reply"withtext.SendMessage.momentIdnames the moment. - Polls: not in v1. Option labels (
labelCiphertext) get their own spec later.
4. Encrypted attachments
- Encrypt the file with AES-256-GCM. Use a fresh random 32-byte key and a random 12-byte nonce.
blob = nonce (12) || ciphertext || tag (16). POST /messaging/attachments { conversationId, mediaKind, contentType: "application/octet-stream", byteSize: blob.length, ciphertextSha256: hex(SHA-256(blob)) }returns{ id, uploadUrl, uploadExpiresAt }(the URL lasts 15 minutes).mediaKindis one ofimage,video,audio,voice_note,file,sticker,thumbnail. The real content type travels encrypted; leavecontentTypeas octet-stream (its default).PUT uploadUrlwith bodybloband headerContent-Type: application/octet-stream(the URL is signed for that type). Send no Authorization header.POST /messaging/attachments/:id/complete. The server checks the stored size equalsbyteSize(MESSAGING_ATTACHMENT_INVALIDotherwise). It never checks the hash: readers do.- Send the message with
attachmentIds: [id]and the attachment entry (section 3), which carries thekeyandsha256. - Reader:
GET /messaging/attachments/:id/downloadreturns{ id, url, byteSize, ciphertextSha256, expiresAt }(the URL lasts an hour). Fetch it, checkSHA-256(blob) == sha256from the content (and the server'sciphertextSha256), split the nonce and tag, decrypt, and checksize. Discard on any mismatch.
5. Sender keys (groups)
- Each device keeps one distribution id (a random UUID) per group. It makes a new one after
senderkey:rotate, after a member leaves, and when the device's own session state is lost. - Distribute:
SenderKeyDistributionMessage(from: myAddress, distributionId, store). Encryptskdm.serialize()(raw bytes, no JSON, no padding) pairwise to each target device as in section 2, step 3. ThenPOST /messaging/sender-keys { conversationId, distributionId, envelopes: [{ deviceId, type: "prekey" | "whisper", ciphertext }] }(or socketsenderkey:distribute). The answer is{ missingDeviceIds }: devices still without the key, which need a session first. - Receive:
senderkey:received { id, conversationId, distributionId, senderUserId, senderDeviceId, type, ciphertext }orGET /messaging/devices/me/sender-keys. Decrypt pairwise from"<senderUserId>.<senderDeviceId>", callprocessSenderKeyDistributionMessage, thenPOST /messaging/devices/me/sender-keys/ack { ids }. - Read a group message: for a
DeliverywithenvelopeType: "sender_key",groupDecrypt(base64decode(ciphertext), from: senderAddress). The server putssharedCiphertextinciphertextfor these.
6. Receiving and acknowledging
- Sources: socket
message:newandmessage:edited(oneDeliveryeach),envelope:sync { cursor?, limit? }, orGET /messaging/devices/me/envelopesafter connect and on launch. ADeliverycarriesmessageId,revision,senderUserId,senderDeviceId,kind,envelopeType,ciphertext,senderKeyDistributionId,replyToMessageId,attachmentIds,mentionedUserIds,editedAt,createdAt, andsystemfor server lines (call_log,system), which have no envelope. - Decrypt by
envelopeType:prekey:PreKeySignalMessagewithsignalDecryptPreKeywhisper:SignalMessagewithsignalDecryptsender_key:groupDecrypt
- Remove the padding, parse the content and save it locally (encrypted at rest) under
messageId. Only after that save,POST /messaging/devices/me/envelopes/ack { messageIds }(up to 500; answers{ updated }) or socketmessage:delivered { messageIds }. The ack deletes this device's ciphertext on the server and is the "delivered" receipt the sender sees, so never acknowledge what was not saved.- A duplicate whose plaintext is already saved may be acknowledged.
- A message that fails to decrypt stays unacknowledged. Undelivered envelopes are dropped after
MESSAGING_ENVELOPE_RETENTION_DAYS(30 by default), and the UI shows "Encrypted message".
- After a
prekeydecrypt, refill prekeys if the count is low.
7. Versioning
vcovers the JSON content. Additive fields keepv: 1. A breaking change bumpsv, and writers keep sending the old version until every client reads the new one.- Changes to libsignal wire formats (key type bytes, message versions) follow libsignal releases. The server checks only key lengths and type bytes (
keys/engine.ts), so bump them together.