Loading document parsing libraries...
# Server
Class
## About
`Server` is a WebSocket server that can run without a user interface, including in a console application or service. It authenticates connections, checks access whenever a user opens a document, saves document changes, sends changes to other users, shares live pointer and selection activity, and owns node locks. It does not create an `Editor` and does not need registered node types.
## Event Definitions
| Name | Parameters | Return Type | Description |
| --- | :---: | :---: | --- |
| AuthenticateUser | ipAddress As String <br> userName As String <br> nonce As String <br> challengeID As String <br> clientProof As String <br> documentID As String | GraffitiProEditor.CollaborationAccess | Requests application-defined authentication and authorization for a connection or document-open attempt. |
| ClientConnected | connectionID As String <br> ipAddress As String | (None) | Raised when a WebSocket client completes its handshake. |
| ClientDisconnected | connectionID As String | (None) | Raised when a WebSocket client disconnects. |
| RequestDocuments | user As GraffitiProEditor.Network.User <br> request As JSONItem | JSONItem | Requests application-defined JSON document-list data for an authenticated user. |
| TransportError | message As String | (None) | Raised when the WebSocket transport encounters an error. |
## Methods
| Name | Parameters | Return Type | Description |
| --- | :---: | :---: | --- |
| Close | (None) | (None) | Closes the collaboration database and releases all in-memory authentication, connection, and lock state. |
| Constructor | databaseFile As FolderItem = Nil | (None) | Creates a headless WebSocket collaboration server backed by the supplied SQLite file or an in-memory database. |
| DatabaseFile | (None) | FolderItem | Returns the SQLite database file, or Nil when the server uses in-memory storage. |
| DisconnectUser | user As GraffitiProEditor.Network.User <br> clearDocument As Boolean = False | (None) | Ends the supplied user's connection. The client is told the server ended the session, and the other users in its document see it leave. With clearDocument, the client also clears the open document and its undo history from its editor. |
| Documents | (None) | String | Returns the IDs of the documents stored by this server, in order. |
| IsListening | (None) | Boolean | Returns whether the WebSocket server is listening. |
| IsPersistent | (None) | Boolean | Returns whether document snapshots and operations are stored in a file-backed database. |
| IsSecure | (None) | Boolean | Returns whether newly accepted connections use built-in TLS. |
| Listen | port As Integer <br> path As String = "/" <br> networkInterface As NetworkInterface = Nil | (None) | Starts the built-in WebSocket server. |
| PutDocument | documentID As String <br> snapshot As String <br> documentVersion As Integer = GraffitiProEditor.CurrentDocumentVersion | (None) | Creates or replaces the stored snapshot for a document that clients may subsequently open. |
| Sessions | (None) | GraffitiProEditor.Network.User | Returns the authenticated sessions: one user per connection, for the document it has open, or with an empty DocumentID before it opens one. Setting a returned user's Access changes that session's access. |
| SetTLSCertificate | certificateFile As FolderItem <br> certificatePassword As String = "" | (None) | Enables or disables built-in TLS for connections accepted after this call. |
| StopListening | (None) | (None) | Stops the WebSocket listener and closes active connections. |
## Notes
### Authentication and Authorization
`AuthenticateUser` is raised once for connection authentication and again whenever that authenticated user attempts to open a document. Return `CollaborationAccess.None` by default or when proof verification fails. For a document request, return `Read` or `Edit` only after checking that user's permission for that document. Password lookup, password hashing, user storage, document discovery, and metadata filtering remain application responsibilities.
The protocol transmits an HMAC proof rather than the password hash. Challenges expire after thirty seconds and repeated failures are rate limited by IP address and user name. Username uniqueness and other identity policies belong in the application's `AuthenticateUser` handler; the server permits the same authenticated identity to use multiple simultaneous sessions.
### Document Listing
The server accepts `documents.list` only after the connection has been authenticated. It passes the authenticated `Network.User` and a copy of the client's application-defined JSON to `RequestDocuments`. Return any JSON object or array your application needs. Returning `Nil`, or leaving the event unimplemented, returns an empty JSON array.
The server never builds this list from its document database. The event handler must return only documents that the authenticated user may discover. A later attempt to open a listed document is independently checked through `AuthenticateUser`, so list visibility is not treated as permission to read or edit the document.
Requests and responses are limited to one MiB. Event-handler exceptions produce `document-list-failed` rather than terminating the connection. The request and response are copied at the protocol boundary so later changes by application code cannot alter data already being sent.
### Node Locks and Revisions
A client requests a node lock when selecting an editable node. The server grants at most one connection ownership of each document-and-node pair and releases locks on selection change or disconnect. Before accepting an atomic operation, the server removes from it any removal of a node locked by another connection, or of a node containing one, and keeps those nodes in place; the rest of the operation proceeds, and the update is marked `adjusted` so the sender restores the kept nodes. The server then applies the operation to a temporary JSON document and compares every node locked by another connection, rejecting any result that changes one.
The server keeps the latest live pointer, selection, and editing information for each connected user. A newly joined client receives that information and the current locks before it tries to lock its own selection. Clearing a selection sends presence information without a selected node and is reported to application code as a `Nil` node.
Every change names the revision on which it was based. When that revision is older than the current one, the server reads the changes accepted since then from its operation log. If none of them touched the same top-level nodes, none also changed document settings when this change does, and none also reordered or removed nodes when this change does, the server applies the change to the current revision. Otherwise the change receives the server's current document as a conflict response. Rebasing considers at most 64 newer revisions. The server remembers operation IDs, and checks them before the revision, so a resent message is acknowledged rather than applied twice. Complete documents are sent only when opening a document or recovering from a conflict.
### Persistence
Passing a database file to the constructor creates or opens a SQLite database and enables write-ahead logging. Passing Nil uses an in-memory SQLite database. The server stores the current document, its format version, a revision number that increases after each accepted change, and a log of accepted operations with their IDs. The log identifies repeated messages and lets the server apply a change based on an older revision when it does not overlap the changes accepted since. Node locks, pointer positions, and selections exist only during the live session and are not saved.
Calling `PutDocument` for an existing document replaces its content without adding to the operation log. Changes based on revisions up to that point are therefore never rebased across the replacement; they receive a conflict response and the new content. The server remembers replacements only while it runs, which is sufficient because clients that reconnect receive the complete current document.
### Server Documents and Conflict Responses
The server's saved document is the shared source of truth. When a client opens a document, the server sends the complete current document, its checksum, revision number, and document format version. It does not receive or merge the editor's existing content during this step. `Client` and application code handle any older or offline local content after the server copy is loaded.
Each later change includes the revision on which it was based. The server accepts the change when that revision is still current, or when the change can be applied over the newer revisions without overlapping them (see **Node Locks and Revisions**). The document format must also be supported, the resulting document must be valid, and the change must not modify or remove a node locked by another user. An existing node in the change replaces the stored node in its current position; only a new node is placed at the index the client sent. The entire change is saved together, the revision increases by one, and every user in that document receives the update.
When the starting revision is out of date and the change overlaps newer changes, or a lock prevents the change, the server saves none of it. It sends `document.conflict` with the current complete document, checksum, revision, and document format version. The client may preserve edits to a node it still owns and submit another change, but the server does not merge document versions itself.
### Sessions and Access
`Sessions` returns one `User` for each authenticated connection: for the document it has open, or with an empty `DocumentID` before it opens one. The same object is returned for a session until it ends, so the application can keep it. `Documents` returns the IDs of the documents stored by the server.
A live session has `Read` or `Edit` access. Setting `Access` on a user returned by `Sessions` changes that session and tells its client, which raises `Client.AccessChanged`. With `Read`, the server releases the user's node locks and rejects further changes, and the client's editor becomes read-only. `Edit` lets the user change the document again. The other users' editors update the collaborator's access. Assigning `None`, or assigning `Access` on any other `User`, has no effect.
`DisconnectUser` removes a user: the client receives a `session-ended` error and then disconnects, and the other users in its document see the user leave. The user keeps the document on screen. Pass `True` for `clearDocument` to revoke the document as well: the client clears it and its undo history from its editor first. To keep a user out, refuse them in `AuthenticateUser`, which returns `None` to refuse a connection or a document.
### Transport Contract
The constructor never begins listening. Call `Listen` with a port, request path, and optional network interface. The server validates upgrade requests, requires masked client frames, supports fragmented text messages, answers pings, performs close handshakes, and enforces header and message limits. Call `StopListening` to close the listener and its WebSocket clients. Call `SetTLSCertificate` before accepting connections to serve `wss` directly; the file must contain the PEM certificate chain and private key. Without a certificate the server accepts unencrypted `ws`, which should be limited to trusted networks or placed behind a TLS-terminating reverse proxy.
Xojo's `SSLSocket` documentation does not state whether a client verifies the server's certificate chain and host name, or which certificate file format Windows requires. Confirm both on every target platform before relying on `wss` across untrusted networks; until then, a TLS-terminating reverse proxy with verified certificates remains the conservative choice for internet-facing services.
## Examples
Create the server, implement `AuthenticateUser`, register documents with `PutDocument`, and call `Listen`.
### Authentication
```xojo
Private Function AuthenticateCollaborationUser(sender As GraffitiProEditor.Network.Server, ipAddress As String, userName As String, nonce As String, challengeID As String, clientProof As String, documentID As String) As GraffitiProEditor.CollaborationAccess
Var passwordHash As String = PasswordHashForUser(userName)
If Not GraffitiProEditor.CollaborationAuthentication.VerifyProof(passwordHash, nonce, challengeID, userName, clientProof, documentID) Then Return GraffitiProEditor.CollaborationAccess.None
If documentID = "" Then Return GraffitiProEditor.CollaborationAccess.Read
Return AccessForDocument(userName, documentID)
End Function
```
### Headless Server
```xojo
Var databaseFile As FolderItem = SpecialFolder.ApplicationData.Child("collaboration.sqlite")
Var server As New GraffitiProEditor.Network.Server(databaseFile)
AddHandler server.AuthenticateUser, AddressOf AuthenticateCollaborationUser
server.PutDocument(documentID, initialSnapshot)
server.SetTLSCertificate(SpecialFolder.ApplicationData.Child("collaboration.pem"))
server.Listen(443, "/editor")
```
`SetTLSCertificate` enables `wss` for connections accepted afterwards. The PEM file contains the certificate chain and private key; pass the private key's password as the second argument when it is encrypted. Omit the call to accept unencrypted `ws` connections on a trusted network.
### Listing Documents
```xojo
Private Function RequestCollaborationDocuments(sender As GraffitiProEditor.Network.Server, user As GraffitiProEditor.Network.User, request As JSONItem) As JSONItem
#Pragma Unused sender
Var result As New JSONItem("[]")
For Each document As ApplicationDocument In DocumentsVisibleToUser(user, request)
Var metadata As New JSONItem
metadata.Value("documentId") = document.ID
metadata.Value("title") = document.Title
metadata.Value("category") = document.Category
result.Add(metadata)
Next
Return result
End Function
```
Register this handler with `AddHandler server.RequestDocuments, AddressOf RequestCollaborationDocuments`. The application chooses every field and must omit documents the authenticated user should not discover.
### Managing Sessions
```xojo
For Each session As GraffitiProEditor.Network.User In server.Sessions
If session.UserName = removedUserName Then
server.DisconnectUser(session)
ElseIf session.DocumentID = archivedDocumentID Then
session.Access = GraffitiProEditor.CollaborationAccess.Read
ElseIf session.UserName = revokedUserName Then
server.DisconnectUser(session, True)
End If
Next
```