Client Protocol
This page describes what a client sends to the database port (34567 by default) and what it receives, in enough detail to write a client in any language. It is protocol 2, spoken by servers and by @diana-db/odm since 4.6.5. Everything here was checked with a client written from this page alone.
- Transport: TCP, or TLS over TCP when the server has
ssl_cert_fileandssl_key_file. The lines are the same in both cases. - Messages are lines of text ended by
\n(a\rbefore it is ignored, and so are empty lines). The encoding is UTF-8. - The first four lines are a plain-text handshake that proves the password without sending it. Every later line is one JSON message, encrypted with a key that exists for this connection only.
Handshake
C: hello:2:admin:ALmWJMqoIA2vgqqj3CMo56+YrE6JrW63
S: challenge:2:LJV6mPL4/KlwgpkhcKohSA==:32768:8:1:1n6Tudh2swA+AG9LHr8PL/Shlpp1sT4C
C: proof:0IAydpOfbxswE8kr+DYZx6yWV5nZ5Qh0UvxN/c3pV/w=
S: ok:2:IDwtRezJuJKlq1h8vseNPvwT6DFnBhn/a5m1Li9i5Gs=
| Line | Fields |
|---|---|
hello:2:<user>:<client nonce> | The user name (letters, digits and _) and 24 random bytes in base64: exactly 32 characters, no padding. Append :subscriber to receive change notifications on this connection, and after it, optionally, :<source>,<source> to receive those of some databases or collections only |
challenge:2:<salt>:<N>:<r>:<p>:<server nonce> | The user's salt in base64, the scrypt parameters (now 32768, 8, 1; use the ones received) and the server's 24 random bytes in base64 |
proof:<client proof> | 32 bytes in base64 (44 characters), computed as below |
ok:2:<server signature> | 32 bytes in base64. Compare it with your own computation: a server that does not know the password can't produce it |
The computation. HMAC is HMAC-SHA-256 with the key first; text is UTF-8; the salt and the nonces are used as base64 text in authMessage and as bytes elsewhere.
salted = scrypt(SHA-256(password), salt bytes, 32 bytes out, N, r, p)
clientKey = HMAC(salted, "Client Key")
storedKey = SHA-256(clientKey)
serverKey = HMAC(salted, "Server Key")
authMessage = "<user>,<client nonce>,<server nonce>,<salt>"
client proof = clientKey XOR HMAC(storedKey, authMessage)
server signature= HMAC(serverKey, authMessage)
session key = HKDF-SHA-256(key = clientKey,
salt = client nonce bytes followed by server nonce bytes,
info = "diana-db session 2", 32 bytes out)
- A wrong password and an unknown user look the same: the server sends a challenge and closes the connection after the proof, without a message.
- The server closes the connection when the first line is not a valid
hello, when anything arrives before the challenge was sent, and when the answer to the challenge is not aproofline. - Until it has authenticated, a connection has
handshake_timeoutseconds (10 unless set) and may send lines of up to 1024 characters; after that the server closes it. The number of connections in this state is limited too (max_pending_connections,max_pending_connections_per_ip): one more is closed at once, without an answer. See the settings. Servers before 4.7.15 have none of these limits. - scrypt with these parameters needs about 32 MB and some tens of milliseconds on the client. A client that opens several connections can keep
saltedper password and salt. The server stores the two keys and never runs scrypt for a handshake.
Encrypted lines
After ok, every line in both directions is:
base64( iv (12 random bytes) || tag (16 bytes) || ciphertext )
ciphertext, tag = AES-256-GCM(key = session key, iv, plaintext = the JSON message as UTF-8)
- Use a new random
ivfor every line. No additional authenticated data is used. - A line the server can't decrypt, or whose plaintext is not a JSON object, closes the connection.
- A request line may be up to 64 MiB of base64, and its JSON at most 256 levels deep. Answers can be larger than that: read lines of any length, or set your own limit (the ODM stops at 256 MiB).
Requests
{
"action": "find",
"database": "shop",
"collection": "books",
"filterQueries": [{ "pages": { "$gt": 500 } }],
"sortQuery": { "pages": -1 },
"limit": 10,
"clientRequestId": "128d0016-5d3c-4982-a1cb-5a683c855517"
}
| Field | Meaning |
|---|---|
action | What to do; see Actions |
clientRequestId | Any string of your choice, unique among the requests you are waiting for. The answer repeats it |
database, collection | Where. Names hold letters, digits, _ and -, up to 128 characters |
filterQueries | An array of queries; a document matches when it matches any of them. [{}] matches every document. The query language is the one of Find. Reading without it reads everything; update and remove are refused without it |
transformQueries | An array of pipeline stages, see Find and Views |
setData | The document to insert (an array of documents for insertMany), or the values and update operators for update |
sortQuery, skip, limit | For find: { field: 1 | -1 }, a number to skip, and a limit of 1 or more |
transactionId | Runs insert, insertMany, find, count, update or remove inside a transaction |
requestGroupId | Optional; repeated in the answer, not used by the server |
- Several requests may be written before any answer has arrived. Match answers by
clientRequestId, not by order. - TIME values travel as ISO 8601 strings or as milliseconds since the epoch, and come back as ISO 8601 strings in UTC.
- The server adds
_idto every inserted document. A client does not send one.
Answers and errors
{
"action": "response",
"clientRequestId": "128d0016-5d3c-4982-a1cb-5a683c855517",
"socket": "dc0a1882-52b8-44fb-b5b7-4fa6bd59a25e",
"executionTime": 1,
"data": [
{ "_id": "02fc00000001-0152-1a21330f59a-00011a36d", "title": "Ulysses", "pages": 730 },
{ "_id": "02fc00000001-0152-1a21330f597-0000d17e0", "title": "Dune", "pages": 612 }
]
}
| Field | Meaning |
|---|---|
action | response for an answer, publish for a notification |
clientRequestId | The one of the request |
data | The result; its shape depends on the action |
error | Present only when the request failed: a text such as 006 Request Error: collection with name 'missing' doesn't exist. data is then [] |
found, modified, removed | Counts, for update and remove |
executionTime | Milliseconds the server spent on the request |
socket | The server's id of this connection |
A failed request does not close the connection. Most error texts start with a three-digit code:
| Code | Kind |
|---|---|
006 Request Error | Something does not exist, or the request lacks a field its action needs; the text names the field |
007 Access Error | The user may not do this in this database, or the action is unknown or not available to clients |
008 Memory Error | The memory guard refuses requests; nothing was changed |
100 Database Error, 101 Schema Error | A value, a document or a schema was refused |
102 Query Error, 103 Transform Error | A query or a pipeline is not valid |
102 Transaction Error | The transaction does not exist or has ended |
111 Lock Error | A document is locked by a transaction |
An error that starts with The change was applied but could not be written to disk is the only one after which the change was made (in memory): do not send the request again. See Errors for how the ODM groups these.
Actions
database is needed by every action except getVersion, getHealth, getDatabaseNames and subscribe; collection by every action of the second and third table. "Access" is the level the user needs in the database, as granted with diana-db grant-access.
Server and database
| Action | Other fields | Access | data of the answer |
|---|---|---|---|
getVersion | – | – | { "version": "4.12.0" } |
getHealth | – | – | Load numbers and memoryGuard, as getHealth() of the ODM |
getDatabaseNames | – | – | Names of the existing databases the user can read: ["shop"] |
createDatabase | – | 3 (manage) | { "database": "shop", "action": "created" } |
removeDatabase | – | 3 (manage) | { "database": "shop", "action": "removed" } |
getCollectionNames | – | 1 (read) | ["books"] |
startTransaction | autoRollbackAfterMS (optional) | 2 (write) | { "transactionId": "…" } |
commitTransaction | transactionId | 2 (write) | { "transactionId": "…", "status": "committed" } |
rollbackTransaction | transactionId | 2 (write) | { "transactionId": "…", "status": "rolled-back" } |
getMigrations | – | 2 (write) | Names of the migrations recorded as up: ["001-first"] |
migrateUp, migrateDown | migration (a name) | 2 (write) | { "migration": { "name": "001-first", "status": "up" } }. The server only records the name; the client runs the migration |
subscribe | sources: an array of names | – | { "sources": ["shop.books"] }. On a subscriber connection only, see Subscriptions. Since 4.8.17 |
Collections and views
| Action | Other fields | Access | data of the answer |
|---|---|---|---|
createCollection | schema, partition (optional) | 2 (write) | { "collection": "books", "action": "created" } |
updateCollection | schema, partition (optional) | 3 (manage) | { "collection": "books", "action": "updated" } |
removeCollection | – | 3 (manage) | { "collection": "books", "action": "removed" } |
getCollectionSchema | – | 1 (read) | { "schema": { … }, "locked": false } |
lockCollectionSchema, unlockCollectionSchema, getCollectionSchemaLock | – | 3 (manage) | { "collection": "books", "locked": true } |
addView | view, transformQueries | 2 (write); read before 4.7.16 | { "view": "titles", "action": "created" } |
removeView | view | 2 (write) | { "view": "titles", "action": "removed" } |
getCollectionViews | – | 3 (manage) | { "titles": { "transformQueries": [ … ] } } |
A schema is the JSON of a document schema with the type names as strings: { "title": { "type": "STRING" }, "pages": { "type": "NUMBER" } }. addCollection is an older name of createCollection.
Documents
| Action | Other fields | Access | Answer |
|---|---|---|---|
insert | setData: a document | 2 (write) | data: the document with its _id |
insertMany | setData: an array of documents | 2 (write) | data: the documents with their _id. All or none are inserted |
find | optional filterQueries, transformQueries, sortQuery, skip, limit | 1 (read) | data: an array of documents, or of pipeline results |
count | optional filterQueries, transformQueries | 1 (read) | data: a number |
update | filterQueries (required), setData | 2 (write) | found and modified; data is [] |
remove | filterQueries (required; [{}] removes every document) | 2 (write) | found and removed; data is [] |
distinct | distinctKey: a field name | 1 (read) | data: the different values |
max, min | distinctKey | 1 (read) | data: an array with the documents that hold the largest or smallest value |
findByView | view; optional filterQueries | 1 (read) | data: the rows of the view |
countByView | view; optional filterQueries | 1 (read) | data: a number |
Users and access rights are not managed over this protocol: use the diana-db command on the server. Before 4.7.17 a request without a field its action needs was answered with an internal error text, and remove without filterQueries removed every document.
A request is carried out as it is written, or refused with a 006 Request Error:
- A key named
__proto__,constructororprototype, anywhere in the request, is refused. Before 4.8.18 the key was dropped, so the filter{ "constructor": 1 }became{}and matched every document. action,database,collection,view,distinctKeyandtransactionIdare strings, and every query infilterQueriesis an object.updateandremovechange every document that matches: they refuselimit,skip,sortQueryandtransformQueries. Before 4.8.28 these were ignored.viewis taken byaddView,removeView,findByViewandcountByViewonly. Before 4.8.28 other actions ignored it and worked on the collection.- A
schemahas at least one property.updateCollectioncan add and remove properties, and change the options of a property it keeps, but not its type, array items, reference or precision. - Since 4.11.1 a
sortQueryorders by a property that thetransformQueriesproduced (the total of a$group, for one). Before, such a sort left the documents as they were, without an error.
Collections with partitions
Since 4.12.0 a collection can be split by the time of the insert. createCollection and updateCollection take "partition": { "unit": "year" | "month" | "day", "keep": 12 }; keep is optional.
{ "action": "createCollection", "database": "shop", "collection": "transactions",
"schema": { "amount": { "type": "NUMBER", "precision": 2 } },
"partition": { "unit": "month", "keep": 24 } }
- Inserts. A document inserted into
transactionsgoes totransactions-2026,transactions-2026-09ortransactions-2026-09-12, by the server's time at the insert, in UTC. The partition is created with the collection's schema when its first document arrives. - Reads and changes.
find,count,update,remove,distinct,minandmaxsent totransactionscover the collection and every partition. Sorting,skip,limitandtransformQueriesapply to all of them as one collection. Every partition is read: routing is by the time of the insert, so a filter cannot rule one out. - A partition is a collection. It is listed by
getCollectionNamesand can be read and changed by its own name, which is the way to read one period only. A collection created with the name of a partition (to import older documents, for one) is treated as one. keep. A partition is removedkeepunits after its period ended, so no document is removed before it is that old. This is checked when a new partition is created, when the collection is updated, when the server starts and once a minute. Withoutkeeppartitions are never removed.- Changing the unit. New documents go to partitions of the new unit; the earlier partitions stay and are still read. When
keepis not sent with the new unit it is converted, rounded so that nothing is removed earlier: 400 days become 2 years, 2 years become 24 months."keep": nullkeeps every partition. - Schema.
updateCollectionchanges the schema of every partition, then the collection's own.removeCollectionremoves the partitions too."partition": nullends it: documents are inserted into the collection again and the partitions stay as collections of their own. - A collection that has documents can get partitions. The documents it holds stay in it and are read together with the partitions.
getCollectionSchemaof such a collection also returns"partition": { "unit": "month", "keep": 24 }and"partitions": ["transactions-2026-08", "transactions-2026-09"].
Limits.
- Not available in a cluster: the request is refused there.
- A unique property is unique within a partition, not across them.
- Views,
$lookupandREFERENCEproperties work with one collection: use the name of a partition.addViewon the collection itself is refused. - An
updateor a schema change that fails in one partition leaves the partitions before it changed. Use a transaction for an update that must be all or nothing. - A collection cannot get partitions while another collection already has the name of one (
transactions-2024). @diana-db/odm4.7.10 does not sendpartitionyet: create such a collection over the protocol. Models then work with it by its name.
Subscriptions
A connection opened with hello:2:<user>:<nonce>:subscriber receives a line for every change in the databases its user can read.
{
"action": "publish",
"requestId": "306a7bac-f09c-462e-86ad-7b14baaa31c3",
"socket": "8f27634d-a024-41c4-8f17-c28a8dbaf8d5",
"data": {
"database": "shop",
"collection": "books",
"action": "update",
"affectedIds": ["02fc00000001-0152-1a21330f597-0000d17e0"],
"data": { "pages": 620 }
}
}
Since 4.8.17 a subscriber can name what it listens to. A source is a database (shop: every collection of it) or one collection (shop.books). There are two ways, and they can be combined:
# in the hello line: sources after ":subscriber:", separated by commas
hello:2:reports:ALmWJMqoIA2vgqqj3CMo56+YrE6JrW63:subscriber:userDb.user,userDb.session
{ "action": "subscribe", "sources": ["userDb.user", "userDb.session"], "clientRequestId": "…" }
- The
subscriberequest replaces the sources of the connection it is sent on and answers with the ones now in force. An empty array, or nosources, means every change again. Up to 1000 sources; the hello line is limited to 1024 characters, so a long list goes into the request. - A source gives no access: changes of a database the user can't read are never sent, and naming one is not an error, so nothing is learnt about what exists.
- A server before 4.8.17 closes the connection on a hello line with sources, and answers
subscribewith an access error. A client that must work with both sends the request, ignores that error and filters what it receives; this is what the ODM does. datais the update described in Subscribe;requestIdidentifies the notification.- Notifications are not stored: what happens while the connection is down is not sent later.
- Only subscriber connections are notified. They can send other requests too, but the ODM keeps one connection for notifications and a pool for requests.
Example client
A complete client in Node.js with no dependencies: it connects, proves the password, checks the server, asks for the version and prints the answer.
import net from 'node:net';
import crypto from 'node:crypto';
const user = process.env.DB_USER;
const password = process.env.DB_PASSWORD;
const socket = net.connect({ host: '127.0.0.1', port: Number(process.env.DB_PORT || 34567) });
socket.setEncoding('utf8');
const hash = (data) => crypto.createHash('sha256').update(data).digest();
const hmac = (key, data) => crypto.createHmac('sha256', key).update(data).digest();
const clientNonce = crypto.randomBytes(24).toString('base64');
let key; // the session key
let signature; // what the server has to answer to prove it knows the password
function encrypt(text) {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const body = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
return Buffer.concat([iv, cipher.getAuthTag(), body]).toString('base64');
}
function decrypt(line) {
const raw = Buffer.from(line, 'base64');
const decipher = crypto.createDecipheriv('aes-256-gcm', key, raw.subarray(0, 12));
decipher.setAuthTag(raw.subarray(12, 28));
return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString('utf8');
}
function onLine(line) {
if (line.startsWith('challenge:2:')) {
const [, , salt, n, r, p, serverNonce] = line.split(':');
const options = { N: Number(n), r: Number(r), p: Number(p), maxmem: 256 * Number(n) * Number(r) };
const salted = crypto.scryptSync(hash(password), Buffer.from(salt, 'base64'), 32, options);
const clientKey = hmac(salted, 'Client Key');
const authMessage = `${user},${clientNonce},${serverNonce},${salt}`;
const clientSignature = hmac(hash(clientKey), authMessage);
const proof = Buffer.from(clientKey.map((byte, i) => byte ^ clientSignature[i]));
signature = hmac(hmac(salted, 'Server Key'), authMessage).toString('base64');
const nonces = Buffer.concat([Buffer.from(clientNonce, 'base64'), Buffer.from(serverNonce, 'base64')]);
key = Buffer.from(crypto.hkdfSync('sha256', clientKey, nonces, 'diana-db session 2', 32));
socket.write(`proof:${proof.toString('base64')}\n`);
} else if (line.startsWith('ok:2:')) {
if (line !== `ok:2:${signature}`) {
throw new Error('this is not the server that knows the password');
}
const request = { action: 'getVersion', clientRequestId: crypto.randomUUID() };
socket.write(`${encrypt(JSON.stringify(request))}\n`);
} else {
console.log(JSON.parse(decrypt(line)));
socket.end();
}
}
let rest = '';
socket.on('data', (chunk) => {
const lines = (rest + chunk).split('\n');
rest = lines.pop();
lines.filter(Boolean).forEach(onLine);
});
socket.on('connect', () => socket.write(`hello:2:${user}:${clientNonce}\n`));
Security properties
What the protocol gives by itself, without TLS, and what it does not. Use TLS with certificate verification whenever the network between client and server is not fully trusted: it covers every gap listed here.
| Property | Protocol 2 alone | With TLS and a verified certificate |
|---|---|---|
| The password is not sent | Yes | Yes |
| Client and server prove to each other that they know the password | Yes | Yes |
| Requests and answers are encrypted and can't be changed unnoticed | Yes, with a key per connection | Yes |
| The user name stays private | No: it is in the first line | Yes |
| A recorded handshake is useless for guessing the password | No: each guess can be tested offline, at the cost of one scrypt run. Use long random passwords | Yes: the handshake can't be recorded |
| Recorded traffic stays secret if the password leaks later (forward secrecy) | No: the session key follows from the password and the handshake | Yes |
| A line can't be sent twice | No: there are no sequence numbers. Someone who can inject into the TCP stream can repeat a captured line on the same connection, or send a line back to its sender, since both directions use one key. A line of another connection is useless: its key is different | Yes |
- Each line uses a random 96-bit nonce. Keep a connection below about four billion lines per direction and reconnect before that; a reconnect gives a new key.
- The server only knows the client through its password. To accept certain machines only, use client certificates (
ssl_ca_filewithssl_request_cert). - TLS without checking the certificate encrypts, but does not tell the client who it is talking to. Since 4.6.10 the ODM checks the certificate unless
tls.rejectUnauthorizedis set tofalse. - A later protocol version is planned to add sequence numbers, a key per direction and counter nonces.
Protocol 1
Servers before 4.6.5 speak protocol 1, and newer servers still accept it while legacy_auth is on (it is, unless set to 0; turn it off once no client older than 4.6.5 is left). A new client should not implement it: every line is encrypted with a key derived from the password alone (SHA-256(password)), so the same key protects every connection of the user for as long as the password lives.
- With
legacy_authon, a connection that sentuser:<name>counts as started: the handshake timeout and the 1024 character limit do not apply to it, because the protocol has no step that proves the password before the first request. - First line:
user:<name>. For a subscriber:user:<name>:subscriber:<token>, where the token is the encrypted textuser:<name>:subscriber:<YYYY-MM-DD>with the current date. - Every following line has the format above, with
SHA-256(password)as the key. There is no challenge: a wrong password shows when the server fails to decrypt the first request and closes the connection. - A server before 4.6.5 closes the connection when it receives
hello:2:…. That is how the ODM recognises one; see Security.