Skip to content

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 ​

WhatFormat on the wire (base64, standard alphabet, padded)libsignal
identityKey33 bytes, 0x05 + Curve25519IdentityKeyPair.identityKey.serialize()
signedPreKey.publicKey, preKeys[].publicKey33 bytes, 0x05 + Curve25519PublicKey.serialize()
kyberPreKeys[].publicKey, kyberLastResortPreKey.publicKey1569 bytes, 0x08 + Kyber1024KEMPublicKey.serialize()
signature (signed prekey, Kyber prekeys)64 bytes, XEdDSA by the identity private key over the serialized public key abovePrivateKey.generateSignature(message:)
registrationIdinteger 1 to 16380random per device install
key idsinteger 0 to 16777215per 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 accepts kyberLastResortPreKey as 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, or keys:low { ecRemaining, kyberRemaining } arrives (sent once at 19 left and again at 0), POST /messaging/keys/devices/me/prekeys with up to 100 more per kind, staying under the cap of 500 stored keys per kind (MESSAGING_PREKEY_LIMIT above 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 late prekey messages 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 a Delivery's senderUserId and senderDeviceId. 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 ​

  1. 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/devices per member, including me. My own device id is the isCurrent row of GET /me/devices.
  2. For a device without a session: POST /messaging/keys/users/:userId/bundles { deviceIds? } (up to 50 ids; leave deviceIds out 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 with isLastResort: true when none are left). Check both signatures in each bundle, then processPreKeyBundle.
  3. Direct chat: encrypt the padded plaintext (section 3) per device with signalEncrypt. Envelope { deviceId, type: "prekey" | "whisper", ciphertext }, from CiphertextMessage.messageType .preKey or .whisper.
  4. Group chat: encrypt once with groupEncrypt under this device's distribution id for the conversation. Send sharedCiphertext = base64(serialize()) and senderKeyDistributionId, plus one { deviceId, type: "sender_key" } envelope per device, with no ciphertext. Before the first send, and on sender_key_missing, distribute the key (section 5). Sender-key envelopes are refused in direct chats.
  5. message:send (or POST /messaging/messages) with { conversationId, clientMessageId, kind, envelopes, sharedCiphertext?, senderKeyDistributionId?, replyToMessageId?, forwardOfMessageId?, attachmentIds?, hasLink, mentionedUserIds, mentionsEveryone, momentId? }. Retry with the same clientMessageId (1 to 64 of A-Za-z0-9._:-).
    • Limits: one envelope's ciphertext (and sharedCiphertext) is at most 262,144 base64 characters, at most 5,000 envelopes, 30 attachmentIds.
    • The answer is a SendResult in data (and the socket ack), not a problem: 201 { status: "sent", message }, or 409 with one of:
      • { status: "device_mismatch", missingDeviceIds, extraDeviceIds, duplicatedDeviceIds }: drop sessions for extraDeviceIds, fetch bundles for missingDeviceIds, send one envelope per device, encrypt again and resend.
      • { status: "sender_key_missing", deviceIds }: distribute this device's sender key to deviceIds (section 5), then resend.
  6. Save the plaintext locally under the returned message.id. The server keeps no copy.

3. Plaintext ​

plaintext = utf8(JSON content) || 0x80 || 0x00 * n

Pad 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
}
FieldRule
vContent version. Always 1 for this spec. A reader that meets a higher major version shows "Update Plemuz to read this message".
kindSame value as SendMessage.kind: text, image, video, audio, voice_note, file, song_share, moment_reply, contact, location.
textMessage body, or the caption of media. Up to 16,000 characters.
quoteCopy 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.
songFor song_share. Readers open recordingId in the app, or url elsewhere.
attachmentsFor media kinds. The ids also go in SendMessage.attachmentIds.
sentAtSender'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 same kind. The server's revision and editedAt say 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" with text. SendMessage.momentId names the moment.
  • Polls: not in v1. Option labels (labelCiphertext) get their own spec later.

4. Encrypted attachments ​

  1. 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).
  2. 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). mediaKind is one of image, video, audio, voice_note, file, sticker, thumbnail. The real content type travels encrypted; leave contentType as octet-stream (its default).
  3. PUT uploadUrl with body blob and header Content-Type: application/octet-stream (the URL is signed for that type). Send no Authorization header.
  4. POST /messaging/attachments/:id/complete. The server checks the stored size equals byteSize (MESSAGING_ATTACHMENT_INVALID otherwise). It never checks the hash: readers do.
  5. Send the message with attachmentIds: [id] and the attachment entry (section 3), which carries the key and sha256.
  6. Reader: GET /messaging/attachments/:id/download returns { id, url, byteSize, ciphertextSha256, expiresAt } (the URL lasts an hour). Fetch it, check SHA-256(blob) == sha256 from the content (and the server's ciphertextSha256), split the nonce and tag, decrypt, and check size. 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). Encrypt skdm.serialize() (raw bytes, no JSON, no padding) pairwise to each target device as in section 2, step 3. Then POST /messaging/sender-keys { conversationId, distributionId, envelopes: [{ deviceId, type: "prekey" | "whisper", ciphertext }] } (or socket senderkey: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 } or GET /messaging/devices/me/sender-keys. Decrypt pairwise from "<senderUserId>.<senderDeviceId>", call processSenderKeyDistributionMessage, then POST /messaging/devices/me/sender-keys/ack { ids }.
  • Read a group message: for a Delivery with envelopeType: "sender_key", groupDecrypt(base64decode(ciphertext), from: senderAddress). The server puts sharedCiphertext in ciphertext for these.

6. Receiving and acknowledging ​

  1. Sources: socket message:new and message:edited (one Delivery each), envelope:sync { cursor?, limit? }, or GET /messaging/devices/me/envelopes after connect and on launch. A Delivery carries messageId, revision, senderUserId, senderDeviceId, kind, envelopeType, ciphertext, senderKeyDistributionId, replyToMessageId, attachmentIds, mentionedUserIds, editedAt, createdAt, and system for server lines (call_log, system), which have no envelope.
  2. Decrypt by envelopeType:
    • prekey: PreKeySignalMessage with signalDecryptPreKey
    • whisper: SignalMessage with signalDecrypt
    • sender_key: groupDecrypt
  3. 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 socket message: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".
  4. After a prekey decrypt, refill prekeys if the count is low.

7. Versioning ​

  • v covers the JSON content. Additive fields keep v: 1. A breaking change bumps v, 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.

Plemuz API v2