AI-native design editor. Open-source Figma alternative.
feat(collab): sync Cloud documents through a server relay (#1055)
Danila Poyarkov90e0cb6a4aa9
diff --git a/bun.lock b/bun.lockindex 017811b9c..8c17ec1aa 100644--- a/bun.lock+++ b/bun.lock@@ -32,6 +32,7 @@"@nanostores/i18n": "^1.3.3","@nanostores/vue": "^1.1.0","@open-pencil/cli": "workspace:*",+ "@open-pencil/cloud": "workspace:*","@open-pencil/core": "workspace:*","@open-pencil/design-jsx": "workspace:*","@open-pencil/dom-css": "workspace:*",@@ -215,23 +216,29 @@"@vue-email/render": "^0.0.9","better-auth": "1.7.7","es-toolkit": "^1.52.0",+ "fflate": "^0.8.3","hono": "^4.13.13","hono-rate-limiter": "^0.5.3","jose": "^6.2.8","kysely": "^0.29.6",+ "lib0": "^0.2.117","nodemailer": "^9.0.5","smol-toml": "^1.8.0","valibot": "^1.5.0","vue": "^3.5.43",+ "ws": "^8.21.3",+ "yjs": "^13.6.32",},"devDependencies": {"@electric-sql/pglite": "0.4.1","@types/bun": "^1.3.14","@types/nodemailer": "^8.0.1","@types/pg": "^8.21.0",+ "@types/ws": "^8.18.1","kysely-pglite-dialect": "1.3.1","tsdown": "^0.22.14","typescript": "~5.8.3",+ "y-protocols": "^1.0.7",},"optionalDependencies": {"pg": "^8.23.0",diff --git a/package.json b/package.jsonindex da47ae3f0..a6792375d 100644--- a/package.json+++ b/package.json@@ -140,6 +140,7 @@"@nanostores/i18n": "^1.3.3","@nanostores/vue": "^1.1.0","@open-pencil/cli": "workspace:*",+ "@open-pencil/cloud": "workspace:*","@open-pencil/core": "workspace:*","@open-pencil/design-jsx": "workspace:*","@open-pencil/dom-css": "workspace:*",diff --git a/packages/cloud/AGENTS.md b/packages/cloud/AGENTS.mdindex 3c81e986a..4a09523f2 100644--- a/packages/cloud/AGENTS.md+++ b/packages/cloud/AGENTS.md@@ -15,6 +15,12 @@ Optional, self-hostable backend; the design is in `packages/docs/development/clo- Add schema changes as a new numbered migration in `src/server/db/migrations/` registered in `src/server/db/migrate.ts`; never edit a migration that has shipped. Better Auth's tables have their own versioned migration (`016_auth_schema.ts`).- Prefer typed Kysely queries; raw SQL goes through the reviewed helpers in `src/server/db/expressions.ts`.+## Collaboration relay++- The relay hub in `src/server/collaboration/relay/` is runtime-neutral: runtimes hand it sockets through `RelaySocket` and own listening (`src/runtime/node/relay.ts`). It joins every room as the `server` peer, so it must keep answering `sync-step1` and saving the room document.+- Viewers may send only the channels in `VIEWER_ACTIONS`; every other channel from them is dropped, and presence is stamped from the ticket by `stampAwareness` (`tests/server/collaboration/relay/hub.test.ts`).+- Decoders must consume exactly the frame's bytes and copy payloads out, since socket buffers are pooled (`src/contract/relay.ts`, `tests/contract/relay.test.ts`).+## Configuration- Deployment settings live in the schema-versioned TOML parsed by `src/server/config/deployment.ts`; environment variables only resolve `{ from_env }` secret references and never override the file (`tests/runtime/node/config.test.ts`).diff --git a/packages/cloud/deploy/README.md b/packages/cloud/deploy/README.mdindex 874cdca88..7dfa17aef 100644--- a/packages/cloud/deploy/README.md+++ b/packages/cloud/deploy/README.md@@ -77,6 +77,15 @@ Each command reads the same `OPENPENCIL_CLOUD_CONFIG` and secrets as the server:| `bun --filter @open-pencil/cloud entitlements` | Inspect or set a workspace's entitlements || `bun --filter @open-pencil/cloud admin` | Approve enrollment and grant deployment admin |+### Collaboration relay++The server accepts collaboration WebSockets on `/api/collaboration/relay` on the same listener, so+a reverse proxy must forward WebSocket upgrades for that path. Collaboration tickets name the relay+at `deployment.public_url` with a `ws:` or `wss:` scheme; set `[collaboration] relay_url` when+clients reach it elsewhere. `technical_limits.maximum_collaboration_message_bytes` and+`maximum_connections_per_room` bound each room, and the `entitlements.collaboration` limits apply+per workspace.+### Transactional emailSet `email.transport = "smtp"` with an `[email.smtp]` table, or `"none"` to disable delivery; withdiff --git a/packages/cloud/deploy/openpencil-cloud.example.toml b/packages/cloud/deploy/openpencil-cloud.example.tomlindex 9c0781d1c..4fa37e10b 100644--- a/packages/cloud/deploy/openpencil-cloud.example.toml+++ b/packages/cloud/deploy/openpencil-cloud.example.toml@@ -71,6 +71,11 @@ force_path_style = truechecksum_verification = "metadata"# Credentials default to S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY.+# The collaboration relay is served on the API origin. Set this only when clients reach it+# through a different URL, such as a separate proxy.+# [collaboration]+# relay_url = "wss://relay.example.com/api/collaboration/relay"+[email]transport = "none"diff --git a/packages/cloud/package.json b/packages/cloud/package.jsonindex 32241b2c4..f459214c0 100644--- a/packages/cloud/package.json+++ b/packages/cloud/package.json@@ -64,7 +64,7 @@"migrate": "bun src/runtime/node/migrate.ts","cleanup": "bun src/runtime/node/cleanup.ts","quota:reconcile": "bun src/runtime/node/quota-reconcile.ts",- "entitlements": "bun src/runtime/node/entitlements.ts",+ "entitlements": "bun src/runtime/node/entitlements/main.ts","admin": "bun src/runtime/node/admin.ts","typecheck": "bunx tsc --noEmit -p tsconfig.json"},@@ -82,14 +82,18 @@"@vue-email/render": "^0.0.9","better-auth": "1.7.7","es-toolkit": "^1.52.0",+ "fflate": "^0.8.3","hono": "^4.13.13","hono-rate-limiter": "^0.5.3","jose": "^6.2.8","kysely": "^0.29.6",+ "lib0": "^0.2.117","nodemailer": "^9.0.5","smol-toml": "^1.8.0","valibot": "^1.5.0",- "vue": "^3.5.43"+ "vue": "^3.5.43",+ "ws": "^8.21.3",+ "yjs": "^13.6.32"},"optionalDependencies": {"pg": "^8.23.0"@@ -99,8 +103,10 @@"@types/bun": "^1.3.14","@types/nodemailer": "^8.0.1","@types/pg": "^8.21.0",+ "@types/ws": "^8.18.1","kysely-pglite-dialect": "1.3.1","tsdown": "^0.22.14",- "typescript": "~5.8.3"+ "typescript": "~5.8.3",+ "y-protocols": "^1.0.7"}}diff --git a/packages/cloud/src/client/auth.ts b/packages/cloud/src/client/auth/client.tssimilarity index 98%rename from packages/cloud/src/client/auth.tsrename to packages/cloud/src/client/auth/client.tsindex 45abf3f22..ce614aeb7 100644--- a/packages/cloud/src/client/auth.ts+++ b/packages/cloud/src/client/auth/client.ts@@ -3,8 +3,8 @@ import { passkeyClient } from '@better-auth/passkey/client'import { createAuthClient } from 'better-auth/client'import { deviceAuthorizationClient, twoFactorClient } from 'better-auth/client/plugins'-import { cloudAuthFailure, type CloudAuthResult } from './auth-failure'-import type { CloudFetch } from './discovery'+import type { CloudFetch } from '../discovery'+import { cloudAuthFailure, type CloudAuthResult } from './failure'export type CloudSocialProvider = CloudDiscovery['authentication']['socialProviders'][number]diff --git a/packages/cloud/src/client/auth-failure.ts b/packages/cloud/src/client/auth/failure.tssimilarity index 100%rename from packages/cloud/src/client/auth-failure.tsrename to packages/cloud/src/client/auth/failure.tsdiff --git a/packages/cloud/src/client/auth-navigation.ts b/packages/cloud/src/client/auth/navigation.tssimilarity index 100%rename from packages/cloud/src/client/auth-navigation.tsrename to packages/cloud/src/client/auth/navigation.tsdiff --git a/packages/cloud/src/client/index.ts b/packages/cloud/src/client/index.tsindex 74d25542a..c26531643 100644--- a/packages/cloud/src/client/index.ts+++ b/packages/cloud/src/client/index.ts@@ -1,4 +1,4 @@-export { cloudEditorReturnURL, cloudSignInURL } from './auth-navigation'+export { cloudEditorReturnURL, cloudSignInURL } from './auth/navigation'export { cloudRedirectPath, cloudShareURL } from './links'export {CloudAPIError,@@ -7,7 +7,7 @@ export {type CloudRequestOptions,type CloudUpload} from './api'-export { cloudAuthFailure, type CloudAuthFailure, type CloudAuthResult } from './auth-failure'+export { cloudAuthFailure, type CloudAuthFailure, type CloudAuthResult } from './auth/failure'export {createCloudAuthClient,resendCloudVerification,@@ -20,7 +20,7 @@ export {type CloudAuthClientOptions,type CloudSignInOptions,type CloudSocialProvider-} from './auth'+} from './auth/client'export {CloudDeviceAuthorizationError,type CloudDeviceErrorCode,diff --git a/packages/cloud/src/contract/collaboration.ts b/packages/cloud/src/contract/collaboration.tsindex 9bff04121..e0f75f4b8 100644--- a/packages/cloud/src/contract/collaboration.ts+++ b/packages/cloud/src/contract/collaboration.ts@@ -19,7 +19,7 @@ export type CollaborationPrincipal = v.InferOutput<typeof collaborationPrincipalexport const collaborationTicketSchema = v.object({token: v.string(),- provider: v.optional(v.picklist(['trystero', 'hocuspocus'])),+ provider: v.optional(v.picklist(['trystero', 'relay'])),serverURL: v.optional(v.pipe(v.string(), v.url())),documentId: v.pipe(v.string(), v.uuid()),roomId: v.string(),diff --git a/packages/cloud/src/contract/index.ts b/packages/cloud/src/contract/index.tsindex 8854c6fbf..a70037f7c 100644--- a/packages/cloud/src/contract/index.ts+++ b/packages/cloud/src/contract/index.ts@@ -6,6 +6,7 @@ export {type CollaborationPrincipal,type CollaborationTicket} from './collaboration'+export * from './relay'export { workspaceEntitlementsSchema, type WorkspaceEntitlements } from './entitlements'export {CLOUD_DISCOVERY_PATH,diff --git a/packages/cloud/src/contract/relay.ts b/packages/cloud/src/contract/relay.tsnew file mode 100644index 000000000..8cb0573e7--- /dev/null+++ b/packages/cloud/src/contract/relay.ts@@ -0,0 +1,206 @@+import { deflateSync, Inflate } from 'fflate'+import * as decoding from 'lib0/decoding'+import * as encoding from 'lib0/encoding'+import * as Y from 'yjs'++/** Where the relay accepts WebSocket upgrades, under the Cloud API origin. */+export const RELAY_PATH = '/api/collaboration/relay'++/**+ * The room messages collaboration sends. The relay reads the document ones to keep its copy,+ * persist it, and drop writes from viewers; it forwards the rest unread.+ */+export const COLLAB_ACTIONS = {+ yjsUpdate: 'yjs-update',+ syncStep1: 'sync-step1',+ syncReply: 'sync-reply',+ awareness: 'awareness',+ agentPreview: 'agent-preview'+} as const++/**+ * The most a room message may decode to, compressed or not. A peer's update past it is dropped+ * before it is decoded, so a small compressed reply cannot expand without bound.+ */+export const MAX_COLLAB_MESSAGE_BYTES = 256 * 1024 * 1024++/**+ * What a peer joining needs is the whole document, which repeats the same field names across+ * every layer, so the reply to its state vector travels compressed; Yjs's V2 encoding already+ * groups that repetition, and together they make a room's first sync about a twelfth the size.+ * Edits travel as V2 updates uncompressed: they are small, and arrive in a stream.+ */+export function encodeSyncReply(document: Y.Doc, stateVector: Uint8Array): Uint8Array {+ return deflateSync(Y.encodeStateAsUpdateV2(document, stateVector))+}++/**+ * Compressed input is inflated this much at a time, so a reply stops within a step of passing+ * the limit: deflate expands at most about 1,032 times, so a step can overshoot by about 16 MB.+ */+const INFLATE_STEP = 16 * 1024++/**+ * The V2 update a peer sent, inflated first when `compressed`, as a sync reply is; null once it+ * would decode past `limit` bytes. Throws on data that does not inflate.+ */+export function decodeRoomUpdate(+ data: Uint8Array,+ { limit, compressed = false }: { limit: number; compressed?: boolean }+): Uint8Array | null {+ if (!compressed) return data.length <= limit ? data : null+ const chunks: Uint8Array[] = []+ let size = 0+ const inflate = new Inflate((chunk) => {+ size += chunk.length+ if (size <= limit) chunks.push(chunk)+ })+ for (let offset = 0; offset < data.length; offset += INFLATE_STEP) {+ inflate.push(data.subarray(offset, offset + INFLATE_STEP), offset + INFLATE_STEP >= data.length)+ if (size > limit) return null+ }+ const inflated = new Uint8Array(size)+ let at = 0+ for (const chunk of chunks) {+ inflated.set(chunk, at)+ at += chunk.length+ }+ return inflated+}++/** The peer ID the relay itself uses: it holds the room's document and answers sync requests. */+export const RELAY_SERVER_PEER = 'server'++/**+ * Close codes in the WebSocket application range. A client reconnects with a fresh ticket after+ * `expired`, and gives up on the others.+ */+export const RELAY_CLOSE = {+ unauthorized: 4401,+ expired: 4403,+ roomFull: 4409,+ messageTooLarge: 4413,+ protocol: 4400+} as const++const CLIENT_AUTH = 0+const CLIENT_MESSAGE = 1+const SERVER_WELCOME = 0+const SERVER_JOIN = 1+const SERVER_LEAVE = 2+const SERVER_MESSAGE = 3++/** Frames a client sends: its ticket first, again to refresh it, then room messages. */+export type RelayClientFrame =+ | { type: 'auth'; token: string }+ | { type: 'message'; namespace: string; target: string | null; payload: Uint8Array }++/** Frames the relay sends: who is in the room, arrivals and departures, and forwarded messages. */+export type RelayServerFrame =+ | { type: 'welcome'; peerId: string; peers: string[] }+ | { type: 'join'; peerId: string }+ | { type: 'leave'; peerId: string }+ | { type: 'message'; namespace: string; from: string; payload: Uint8Array }++/** Encodes into a buffer of its own, which `WebSocket.send` accepts. */+function toSendable(write: (encoder: encoding.Encoder) => void): Uint8Array<ArrayBuffer> {+ return new Uint8Array(encoding.encode(write))+}++export function encodeRelayClientFrame(frame: RelayClientFrame): Uint8Array<ArrayBuffer> {+ return toSendable((encoder) => {+ if (frame.type === 'auth') {+ encoding.writeVarUint(encoder, CLIENT_AUTH)+ encoding.writeVarString(encoder, frame.token)+ return+ }+ encoding.writeVarUint(encoder, CLIENT_MESSAGE)+ encoding.writeVarString(encoder, frame.namespace)+ encoding.writeVarString(encoder, frame.target ?? '')+ encoding.writeVarUint8Array(encoder, frame.payload)+ })+}++export function encodeRelayServerFrame(frame: RelayServerFrame): Uint8Array<ArrayBuffer> {+ return toSendable((encoder) => {+ switch (frame.type) {+ case 'welcome':+ encoding.writeVarUint(encoder, SERVER_WELCOME)+ encoding.writeVarString(encoder, frame.peerId)+ encoding.writeVarUint(encoder, frame.peers.length)+ for (const peer of frame.peers) encoding.writeVarString(encoder, peer)+ return+ case 'join':+ case 'leave':+ encoding.writeVarUint(encoder, frame.type === 'join' ? SERVER_JOIN : SERVER_LEAVE)+ encoding.writeVarString(encoder, frame.peerId)+ return+ case 'message':+ encoding.writeVarUint(encoder, SERVER_MESSAGE)+ encoding.writeVarString(encoder, frame.namespace)+ encoding.writeVarString(encoder, frame.from)+ encoding.writeVarUint8Array(encoder, frame.payload)+ }+ })+}++/**+ * lib0 reads byte arrays as views of the underlying buffer, which can run past the end of the+ * frame's own view, as with pooled socket buffers. A frame is valid only when decoding consumed+ * exactly its bytes, and payloads are copied out of the shared buffer.+ */+function complete<T>(decoder: decoding.Decoder, data: Uint8Array, frame: T): T | null {+ return decoder.pos === data.byteLength ? frame : null+}++function readPayload(decoder: decoding.Decoder): Uint8Array {+ return decoding.readVarUint8Array(decoder).slice()+}++/** Returns null for a frame that is malformed or of an unknown type. */+export function decodeRelayClientFrame(data: Uint8Array): RelayClientFrame | null {+ try {+ const decoder = decoding.createDecoder(data)+ const type = decoding.readVarUint(decoder)+ if (type === CLIENT_AUTH) {+ return complete(decoder, data, { type: 'auth', token: decoding.readVarString(decoder) })+ }+ if (type !== CLIENT_MESSAGE) return null+ const namespace = decoding.readVarString(decoder)+ const target = decoding.readVarString(decoder)+ const payload = readPayload(decoder)+ return complete(decoder, data, { type: 'message', namespace, target: target || null, payload })+ } catch {+ return null+ }+}++/** Returns null for a frame that is malformed or of an unknown type. */+export function decodeRelayServerFrame(data: Uint8Array): RelayServerFrame | null {+ try {+ const decoder = decoding.createDecoder(data)+ switch (decoding.readVarUint(decoder)) {+ case SERVER_WELCOME: {+ const peerId = decoding.readVarString(decoder)+ const count = decoding.readVarUint(decoder)+ const peers: string[] = []+ for (let index = 0; index < count; index++) peers.push(decoding.readVarString(decoder))+ return complete(decoder, data, { type: 'welcome', peerId, peers })+ }+ case SERVER_JOIN:+ return complete(decoder, data, { type: 'join', peerId: decoding.readVarString(decoder) })+ case SERVER_LEAVE:+ return complete(decoder, data, { type: 'leave', peerId: decoding.readVarString(decoder) })+ case SERVER_MESSAGE: {+ const namespace = decoding.readVarString(decoder)+ const from = decoding.readVarString(decoder)+ const payload = readPayload(decoder)+ return complete(decoder, data, { type: 'message', namespace, from, payload })+ }+ default:+ return null+ }+ } catch {+ return null+ }+}diff --git a/packages/cloud/src/runtime/node/application.ts b/packages/cloud/src/runtime/node/application.tsindex 78e5a74bc..3c7d68bdc 100644--- a/packages/cloud/src/runtime/node/application.ts+++ b/packages/cloud/src/runtime/node/application.ts@@ -10,7 +10,7 @@ import {import { loadNodeCloudServerConfig } from './config'import { createNodeCloudDatabase } from './database'-import { createNodeTransactionalEmailRuntime } from './email-runtime'+import { createNodeTransactionalEmailRuntime } from './email/runtime'export type NodeCloudApplicationOptions = {environment?: CloudEnvironmentdiff --git a/packages/cloud/src/runtime/node/email-runtime.ts b/packages/cloud/src/runtime/node/email/runtime.tssimilarity index 93%rename from packages/cloud/src/runtime/node/email-runtime.tsrename to packages/cloud/src/runtime/node/email/runtime.tsindex 8f4e65a1e..11a80faae 100644--- a/packages/cloud/src/runtime/node/email-runtime.ts+++ b/packages/cloud/src/runtime/node/email/runtime.ts@@ -1,4 +1,3 @@-import { createSMTPTransactionalEmailTransport } from '#cloud/runtime/node/email'import {createInvitationOutbox,createTransactionalEmailService,@@ -9,6 +8,8 @@ import {import type { CloudDatabase } from '#cloud/server/db'import type { Kysely } from 'kysely'+import { createSMTPTransactionalEmailTransport } from './transport'+export type NodeTransactionalEmailRuntime = {email: TransactionalEmailServicetransport?: TransactionalEmailTransportdiff --git a/packages/cloud/src/runtime/node/email.ts b/packages/cloud/src/runtime/node/email/transport.tssimilarity index 100%rename from packages/cloud/src/runtime/node/email.tsrename to packages/cloud/src/runtime/node/email/transport.tsdiff --git a/packages/cloud/src/runtime/node/entitlements.ts b/packages/cloud/src/runtime/node/entitlements/main.tssimilarity index 93%rename from packages/cloud/src/runtime/node/entitlements.tsrename to packages/cloud/src/runtime/node/entitlements/main.tsindex 9bee1a40f..9fb5e4100 100644--- a/packages/cloud/src/runtime/node/entitlements.ts+++ b/packages/cloud/src/runtime/node/entitlements/main.ts@@ -3,8 +3,8 @@ import { readFile } from 'node:fs/promises'import { createWorkspaceEntitlementRepository, parseStaticEntitlementsTOML } from '#cloud/server'import { parse as parseTOML } from 'smol-toml'-import { withNodeCloudDatabase } from './command'-import { entitlementWriteRefusal } from './entitlements-command'+import { withNodeCloudDatabase } from '../command'+import { entitlementWriteRefusal } from './refusal'const operation = process.argv[2]const workspaceIndex = process.argv.indexOf('--workspace')diff --git a/packages/cloud/src/runtime/node/entitlements-command.ts b/packages/cloud/src/runtime/node/entitlements/refusal.tssimilarity index 100%rename from packages/cloud/src/runtime/node/entitlements-command.tsrename to packages/cloud/src/runtime/node/entitlements/refusal.tsdiff --git a/packages/cloud/src/runtime/node/index.ts b/packages/cloud/src/runtime/node/index.tsindex 748180f86..39031d6da 100644--- a/packages/cloud/src/runtime/node/index.ts+++ b/packages/cloud/src/runtime/node/index.ts@@ -4,7 +4,7 @@ export { loadNodeCloudServerConfig } from './config'export {createNodeTransactionalEmailRuntime,type NodeTransactionalEmailRuntime-} from './email-runtime'+} from './email/runtime'export { createNodeCloudDatabase, type NodeCloudDatabaseOptions } from './database'export {createNodemailerInvitationDelivery,@@ -15,6 +15,7 @@ export {type SMTPInvitationDeliveryOptions,type NodemailerTransactionalEmailTransportOptions,type SMTPTransactionalEmailTransportOptions-} from './email'+} from './email/transport'export { createS3ObjectStore } from '#cloud/runtime/s3/objects'+export { attachCollaborationRelay, defaultRelayURL } from './relay'export { startNodeCloudServer, type NodeCloudServerOptions } from './server'diff --git a/packages/cloud/src/runtime/node/relay.ts b/packages/cloud/src/runtime/node/relay.tsnew file mode 100644index 000000000..3410748fd--- /dev/null+++ b/packages/cloud/src/runtime/node/relay.ts@@ -0,0 +1,61 @@+import type { IncomingMessage, Server } from 'node:http'+import type { Duplex } from 'node:stream'++import { RELAY_PATH } from '#cloud/contract'+import type { CollaborationRelay } from '#cloud/server'+import { WebSocketServer, type RawData } from 'ws'++function bytes(data: RawData): Uint8Array {+ if (Array.isArray(data)) return new Uint8Array(Buffer.concat(data))+ return data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data)+}++/**+ * Accepts WebSocket upgrades on the relay path of an HTTP server and hands each socket to the+ * relay. Other upgrade requests are refused.+ */+export function attachCollaborationRelay(+ server: Pick<Server, 'on' | 'off'>,+ relay: CollaborationRelay,+ maximumMessageBytes: number+) {+ // ws enforces the limit before buffering; the relay checks again for other runtimes.+ const sockets = new WebSocketServer({ noServer: true, maxPayload: maximumMessageBytes })++ function upgrade(request: IncomingMessage, socket: Duplex, head: Buffer) {+ const path = new URL(request.url ?? '/', 'http://relay').pathname+ if (path !== RELAY_PATH) {+ socket.destroy()+ return+ }+ sockets.handleUpgrade(request, socket, head, (webSocket) => {+ webSocket.binaryType = 'nodebuffer'+ const connection = relay.connect({+ send: (data) => webSocket.send(data),+ close: (code, reason) => webSocket.close(code, reason)+ })+ webSocket.on('message', (data) => connection.receive(bytes(data)))+ webSocket.on('close', () => connection.closed())+ webSocket.on('error', () => webSocket.terminate())+ })+ }++ server.on('upgrade', upgrade)+ return {+ async close() {+ server.off('upgrade', upgrade)+ await relay.close()+ for (const client of sockets.clients) client.terminate()+ await new Promise<void>((resolve) => {+ sockets.close(() => resolve())+ })+ }+ }+}++/** The relay's public URL on the same origin as the API, unless the deployment names another. */+export function defaultRelayURL(publicURL: string): string {+ const url = new URL(RELAY_PATH, publicURL)+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'+ return url.href+}diff --git a/packages/cloud/src/runtime/node/server.ts b/packages/cloud/src/runtime/node/server.tsindex b28e461a5..af55a0511 100644--- a/packages/cloud/src/runtime/node/server.ts+++ b/packages/cloud/src/runtime/node/server.ts@@ -1,7 +1,17 @@+import { createServer } from 'node:http'+import { createS3ObjectStore } from '#cloud/runtime/s3/objects'import {+ CLOUD_FEATURE_KEYS,createCloudApp,createCloudAuthenticationRuntime,+ createCollaborationRelay,+ createCollaborationStateStore,+ createDefaultCloudPolicy,+ DatabaseEntitlementSource,+ EntitlementOpenFeatureProvider,+ StaticEntitlementSource,+ staticEntitlementValues,createDocumentCleanupService,createRateLimitCleanupService,createUploadCleanupService,@@ -9,10 +19,11 @@ import {startTransactionalEmailWorker,withIndexingPolicy} from '#cloud/server'-import { serve, type ServerType } from '@hono/node-server'+import { getRequestListener } from '@hono/node-server'import { createMigratedNodeCloudDatabase } from './bootstrap'-import { createNodeTransactionalEmailRuntime } from './email-runtime'+import { createNodeTransactionalEmailRuntime } from './email/runtime'+import { attachCollaborationRelay, defaultRelayURL } from './relay'export type NodeCloudServerOptions = {environment?: Readonly<Record<string, string | undefined>>@@ -52,7 +63,36 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})objects,invitationOutbox,transactionalEmail: email,- enrollment+ enrollment,+ relayURL: config.relayURL ?? defaultRelayURL(config.publicURL)+ })+ const policy = createDefaultCloudPolicy(+ new EntitlementOpenFeatureProvider(+ config.staticEntitlements+ ? new StaticEntitlementSource(staticEntitlementValues(config.staticEntitlements))+ : new DatabaseEntitlementSource(database)+ )+ )+ const relay = createCollaborationRelay({+ authSecret: config.authSecret,+ store: createCollaborationStateStore(database),+ maximumMessageBytes: config.technicalLimits.maximumCollaborationMessageBytes,+ maximumConnectionsPerRoom: config.technicalLimits.maximumConnectionsPerRoom,+ async maximumParticipants(documentId) {+ const document = await database+ .selectFrom('document')+ .select('workspaceId')+ .where('id', '=', documentId)+ .executeTakeFirst()+ if (!document) return 0+ const limit = await policy.number(CLOUD_FEATURE_KEYS.maximumParticipants, -1, {+ targetingKey: document.workspaceId,+ workspaceId: document.workspaceId,+ documentId,+ deploymentMode: config.deployment+ })+ return limit < 0 ? null : limit+ }})const emailWorker = emailTransport? startTransactionalEmailWorker(email, {@@ -71,11 +111,17 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})options.port ?? Number(environment.PORT ?? 8787),environment.HOST ?? '0.0.0.0')+ const relayListener = attachCollaborationRelay(+ server.http,+ relay,+ config.technicalLimits.maximumCollaborationMessageBytes+ )return {app,database,url: server.url,async stop() {+ await relayListener.close()await server.close()await cleanup?.stop()await emailWorker?.stop()@@ -89,20 +135,24 @@ async function listen(port: number,hostname: string) {- let server: ServerType | undefined- const url = await new Promise<URL>((resolve) => {- server = serve({ fetch, hostname, port }, (info) => {- resolve(new URL(`http://localhost:${info.port}`))+ const listener = getRequestListener(fetch)+ const server = createServer((request, response) => {+ void listener(request, response)+ })+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject)+ server.listen(port, hostname, () => {+ server.off('error', reject)+ resolve()})})+ const address = server.address()+ const boundPort = typeof address === 'object' && address ? address.port : portreturn {- url,+ url: new URL(`http://localhost:${boundPort}`),+ http: server,close: () =>new Promise<void>((done, fail) => {- if (!server) {- done()- return- }server.close((error) => {if (error) fail(error)else done()diff --git a/packages/cloud/src/server/app.ts b/packages/cloud/src/server/app.tsindex ff5fe7a70..6090c3478 100644--- a/packages/cloud/src/server/app.ts+++ b/packages/cloud/src/server/app.ts@@ -62,6 +62,11 @@ export type CloudServices = {enrollment?: EnrollmentServiceentitlementSource?: EntitlementSourcepolicy?: CloudPolicy+ /**+ * Where clients reach this runtime's collaboration relay. Without one, Cloud rooms fall back to+ * peer-to-peer and writes are not enforced by the server.+ */+ relayURL?: string}type CloudEnvironment = CloudAPIEnvironment@@ -213,7 +218,7 @@ export function createCloudApp(services: CloudServices) {database: services.database,sharing,authSecret: services.config.authSecret,- collaborationURL: services.config.collaborationURL,+ relayURL: services.relayURL,policy,deploymentMode: services.config.deployment})diff --git a/packages/cloud/src/server/collaboration/index.ts b/packages/cloud/src/server/collaboration/index.tsindex bacc6f40c..55cf16df9 100644--- a/packages/cloud/src/server/collaboration/index.ts+++ b/packages/cloud/src/server/collaboration/index.ts@@ -5,6 +5,23 @@ export {} from './routes'export {createCollaborationTicketService,+ signCollaborationTicket,+ type CollaborationTicketClaims,type CollaborationTicketService,type CollaborationTicketServiceOptions} from './service'+export {+ authorizeRelayTicket,+ createCollaborationRelay,+ createCollaborationStateStore,+ stampAwareness,+ type CollaborationRelay,+ type CollaborationRelayOptions,+ type CollaborationRoomIdentity,+ type CollaborationStateStore,+ type RelayAuthorization,+ type RelayConnection,+ type RelaySocket,+ type StampedAwareness,+ type VerifiedPresence+} from './relay'diff --git a/packages/cloud/src/server/collaboration/relay/authorize.ts b/packages/cloud/src/server/collaboration/relay/authorize.tsnew file mode 100644index 000000000..77b54a9b8--- /dev/null+++ b/packages/cloud/src/server/collaboration/relay/authorize.ts@@ -0,0 +1,53 @@+import {+ collaborationPrincipalSchema,+ type CollaborationPrincipal,+ type DocumentPermission+} from '#cloud/contract'+import { jwtVerify } from 'jose'+import * as v from 'valibot'++const relayClaimsSchema = v.object({+ documentId: v.pipe(v.string(), v.uuid()),+ roomId: v.string(),+ principal: collaborationPrincipalSchema,+ permission: v.picklist(['view', 'edit']),+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),+ serverEnforcedWrites: v.literal(true),+ exp: v.pipe(v.number(), v.integer())+})++export type RelayAuthorization = {+ roomId: string+ documentId: string+ roomEpoch: number+ permission: DocumentPermission+ principal: CollaborationPrincipal+ /** When the ticket stops being valid, in milliseconds since the epoch. */+ expiresAt: number+}++/** Verifies a collaboration ticket issued for the relay; throws for anything else. */+export async function authorizeRelayTicket(+ token: string,+ authSecret: string+): Promise<RelayAuthorization> {+ const verified = await jwtVerify(token, new TextEncoder().encode(authSecret), {+ algorithms: ['HS256']+ })+ const claims = v.parse(relayClaimsSchema, verified.payload)+ if (claims.roomId !== `cloud:${claims.documentId}:${claims.roomEpoch}`) {+ throw new Error('Collaboration ticket names a different room')+ }+ return {+ roomId: claims.roomId,+ documentId: claims.documentId,+ roomEpoch: claims.roomEpoch,+ permission: claims.permission,+ principal: claims.principal,+ expiresAt: claims.exp * 1000+ }+}++export function principalKey(principal: CollaborationPrincipal): string {+ return principal.kind === 'user' ? `user:${principal.userId}` : `guest:${principal.guestId}`+}diff --git a/packages/cloud/src/server/collaboration/relay/awareness.ts b/packages/cloud/src/server/collaboration/relay/awareness.tsnew file mode 100644index 000000000..1d364f07b--- /dev/null+++ b/packages/cloud/src/server/collaboration/relay/awareness.ts@@ -0,0 +1,98 @@+import type { CollaborationPrincipal, DocumentPermission } from '#cloud/contract'+import * as decoding from 'lib0/decoding'+import * as encoding from 'lib0/encoding'+import * as v from 'valibot'++const AwarenessStateJSON = v.pipe(+ v.string(),+ v.parseJson(),+ v.looseObject({ user: v.optional(v.looseObject({})) })+)++type AwarenessEntry = { clientId: number; clock: number; state: string }++function decodeEntries(update: Uint8Array): AwarenessEntry[] | null {+ try {+ const decoder = decoding.createDecoder(update)+ const count = decoding.readVarUint(decoder)+ const entries: AwarenessEntry[] = []+ for (let index = 0; index < count; index++) {+ entries.push({+ clientId: decoding.readVarUint(decoder),+ clock: decoding.readVarUint(decoder),+ state: decoding.readVarString(decoder)+ })+ }+ return decoder.pos === update.byteLength ? entries : null+ } catch {+ return null+ }+}++function encodeEntries(entries: AwarenessEntry[]): Uint8Array {+ return encoding.encode((encoder) => {+ encoding.writeVarUint(encoder, entries.length)+ for (const entry of entries) {+ encoding.writeVarUint(encoder, entry.clientId)+ encoding.writeVarUint(encoder, entry.clock)+ encoding.writeVarString(encoder, entry.state)+ }+ })+}++/** Who the relay verified a peer to be, as other peers see it in presence. */+export type VerifiedPresence = {+ principal: CollaborationPrincipal+ permission: DocumentPermission+}++function verifiedIdentity({ principal, permission }: VerifiedPresence) {+ return {+ kind: principal.kind,+ id: principal.kind === 'user' ? principal.userId : principal.guestId,+ name: principal.name,+ permission+ }+}++export type StampedAwareness = {+ /** The update to forward, or null when nothing in it may be forwarded. */+ update: Uint8Array | null+ /** Presence clients this update introduced for the peer. */+ claimed: number[]+}++/**+ * Rewrites a peer's presence update so others see who the relay verified rather than what the+ * peer claims: the display name comes from the ticket, and a `cloud` field carries the verified+ * identity and permission. Entries for presence clients another peer owns are dropped, so one+ * peer cannot speak for another; removals pass through for the peer's own clients only.+ */+export function stampAwareness(+ update: Uint8Array,+ presence: VerifiedPresence,+ ownedByOthers: (clientId: number) => boolean+): StampedAwareness {+ const entries = decodeEntries(update)+ if (!entries) return { update: null, claimed: [] }+ const identity = verifiedIdentity(presence)+ const forwarded: AwarenessEntry[] = []+ const claimed: number[] = []+ for (const entry of entries) {+ if (ownedByOthers(entry.clientId)) continue+ if (entry.state === 'null') {+ forwarded.push(entry)+ continue+ }+ const parsed = v.safeParse(AwarenessStateJSON, entry.state)+ if (!parsed.success) continue+ const state = {+ ...parsed.output,+ user: { ...parsed.output.user, name: identity.name },+ cloud: identity+ }+ claimed.push(entry.clientId)+ forwarded.push({ ...entry, state: JSON.stringify(state) })+ }+ return { update: forwarded.length > 0 ? encodeEntries(forwarded) : null, claimed }+}diff --git a/packages/cloud/src/server/collaboration/relay/hub.ts b/packages/cloud/src/server/collaboration/relay/hub.tsnew file mode 100644index 000000000..c3cea68cb--- /dev/null+++ b/packages/cloud/src/server/collaboration/relay/hub.ts@@ -0,0 +1,438 @@+import {+ COLLAB_ACTIONS,+ encodeSyncReply,+ decodeRelayClientFrame,+ decodeRoomUpdate,+ encodeRelayServerFrame,+ MAX_COLLAB_MESSAGE_BYTES,+ RELAY_CLOSE,+ RELAY_SERVER_PEER,+ type RelayServerFrame+} from '#cloud/contract'+import * as Y from 'yjs'++import { authorizeRelayTicket, principalKey, type RelayAuthorization } from './authorize'+import { stampAwareness } from './awareness'+import type { CollaborationStateStore } from './persistence'++/** One client's socket, as a runtime adapter hands it to the relay. */+export type RelaySocket = {+ send(data: Uint8Array): void+ close(code: number, reason: string): void+}++/** What the adapter reports back about that socket. */+export type RelayConnection = {+ receive(data: Uint8Array): void+ closed(): void+}++export type CollaborationRelayOptions = {+ authSecret: string+ store: CollaborationStateStore+ maximumMessageBytes: number+ maximumConnectionsPerRoom: number+ /** The participant limit policy sets for a document, or null for none. */+ maximumParticipants?: (documentId: string) => Promise<number | null>+ /** How long after a change the room's document is saved. */+ persistDelayMs?: number+ /** How long a room whose last save failed waits before saving again. */+ persistRetryMs?: number+ /** How long a socket may stay open without presenting a ticket. */+ authTimeoutMs?: number+ onError?: (message: string, error: unknown) => void+}++/** Messages a viewer may send; their document writes never leave the relay. */+const VIEWER_ACTIONS = new Set<string>([COLLAB_ACTIONS.syncStep1, COLLAB_ACTIONS.awareness])++type Peer = {+ id: string+ socket: RelaySocket+ authorization: RelayAuthorization+ presenceClients: Set<number>+ expiry?: ReturnType<typeof setTimeout>+}++type Room = {+ id: string+ identity: { documentId: string; roomEpoch: number }+ document: Y.Doc+ peers: Map<string, Peer>+ persistTimer: ReturnType<typeof setTimeout> | null+}++export type CollaborationRelay = ReturnType<typeof createCollaborationRelay>++/**+ * A runtime-neutral relay for collaboration rooms. It forwards room messages between peers and+ * joins every room as a peer itself: it holds the room's document, answers sync requests from+ * it, saves it, drops document writes from viewers, and stamps presence with verified identity.+ */+export function createCollaborationRelay(options: CollaborationRelayOptions) {+ const rooms = new Map<string, Room>()+ const opening = new Map<string, Promise<Room>>()+ /** Rooms whose last peer left and whose document is still being saved. */+ const closing = new Map<string, Promise<void>>()+ /** Set by `close()`: a failed save then drops the room instead of retrying. */+ let shuttingDown = false+ const persistDelayMs = options.persistDelayMs ?? 2_000+ const persistRetryMs = options.persistRetryMs ?? 30_000+ const authTimeoutMs = options.authTimeoutMs ?? 10_000+ const report = options.onError ?? ((message, error) => console.error(`[Cloud] ${message}`, error))++ function send(socket: RelaySocket, frame: RelayServerFrame) {+ socket.send(encodeRelayServerFrame(frame))+ }++ async function openRoom(authorization: RelayAuthorization): Promise<Room> {+ const existing = rooms.get(authorization.roomId)+ if (existing) return existing+ const pending = opening.get(authorization.roomId)+ if (pending) return pending+ const identity = { documentId: authorization.documentId, roomEpoch: authorization.roomEpoch }+ const created = (async () => {+ // A room reopened while its last save is in flight must load what that save writes, or,+ // when the save failed, take the room it kept.+ await closing.get(authorization.roomId)+ const kept = rooms.get(authorization.roomId)+ if (kept) return kept+ const document = new Y.Doc()+ const state = await options.store.load(identity)+ if (state) Y.applyUpdate(document, state)+ const room: Room = {+ id: authorization.roomId,+ identity,+ document,+ peers: new Map(),+ persistTimer: null+ }+ document.on('update', () => schedulePersist(room))+ rooms.set(room.id, room)+ return room+ })()+ opening.set(authorization.roomId, created)+ try {+ return await created+ } finally {+ opening.delete(authorization.roomId)+ }+ }++ /** Saves the room's document; false when the store refused it. */+ async function persist(room: Room): Promise<boolean> {+ if (room.persistTimer) clearTimeout(room.persistTimer)+ room.persistTimer = null+ try {+ await options.store.store(room.identity, Y.encodeStateAsUpdate(room.document))+ return true+ } catch (error) {+ report('Saving a collaboration room failed:', error)+ return false+ }+ }++ function schedulePersist(room: Room) {+ room.persistTimer ??= setTimeout(() => void persist(room), persistDelayMs)+ }++ /**+ * Applies a peer's V2 update to the room, inflated first for a sync reply. Rooms are saved as+ * V1 updates; only what peers exchange is V2.+ */+ function applyToRoom(room: Room, peer: Peer, namespace: string, payload: Uint8Array): boolean {+ try {+ const update = decodeRoomUpdate(payload, {+ limit: MAX_COLLAB_MESSAGE_BYTES,+ compressed: namespace === COLLAB_ACTIONS.syncReply+ })+ if (!update) {+ peer.socket.close(RELAY_CLOSE.messageTooLarge, 'Collaboration update is too large')+ return false+ }+ Y.applyUpdateV2(room.document, update, peer.id)+ return true+ } catch {+ peer.socket.close(RELAY_CLOSE.protocol, 'Malformed document update')+ return false+ }+ }++ function forward(+ room: Room,+ from: Peer,+ namespace: string,+ target: string | null,+ payload: Uint8Array+ ) {+ const frame = encodeRelayServerFrame({ type: 'message', namespace, from: from.id, payload })+ if (target) {+ room.peers.get(target)?.socket.send(frame)+ return+ }+ for (const peer of room.peers.values()) if (peer !== from) peer.socket.send(frame)+ }++ function handleServerMessage(room: Room, peer: Peer, namespace: string, payload: Uint8Array) {+ if (namespace === COLLAB_ACTIONS.syncStep1) {+ let reply: Uint8Array+ try {+ reply = encodeSyncReply(room.document, payload)+ } catch {+ peer.socket.close(RELAY_CLOSE.protocol, 'Malformed state vector')+ return+ }+ send(peer.socket, {+ type: 'message',+ namespace: COLLAB_ACTIONS.syncReply,+ from: RELAY_SERVER_PEER,+ payload: reply+ })+ } else if (namespace === COLLAB_ACTIONS.syncReply) {+ applyToRoom(room, peer, namespace, payload)+ }+ }++ function handleMessage(+ room: Room,+ peer: Peer,+ namespace: string,+ target: string | null,+ payload: Uint8Array+ ) {+ const readOnly = peer.authorization.permission === 'view'+ if (readOnly && !VIEWER_ACTIONS.has(namespace)) return++ let forwarded = payload+ if (namespace === COLLAB_ACTIONS.awareness) {+ const stamped = stampAwareness(payload, peer.authorization, (clientId) =>+ [...room.peers.values()].some(+ (other) => other !== peer && other.presenceClients.has(clientId)+ )+ )+ for (const clientId of stamped.claimed) peer.presenceClients.add(clientId)+ if (!stamped.update) return+ forwarded = stamped.update+ }++ if (target === RELAY_SERVER_PEER) {+ handleServerMessage(room, peer, namespace, payload)+ return+ }+ if (+ (namespace === COLLAB_ACTIONS.yjsUpdate || namespace === COLLAB_ACTIONS.syncReply) &&+ !applyToRoom(room, peer, namespace, payload)+ ) {+ return+ }+ forward(room, peer, namespace, target, forwarded)+ }++ function scheduleExpiry(peer: Peer) {+ clearTimeout(peer.expiry)+ peer.expiry = setTimeout(+ () => peer.socket.close(RELAY_CLOSE.expired, 'Collaboration ticket expired'),+ Math.max(0, peer.authorization.expiresAt - Date.now())+ )+ }++ async function admit(+ socket: RelaySocket,+ authorization: RelayAuthorization+ ): Promise<Peer | null> {+ const limit = await options.maximumParticipants?.(authorization.documentId)+ let room = await openRoom(authorization)+ // The room's last peer may have left while it opened; a closed room takes no newcomers.+ while (rooms.get(room.id) !== room) room = await openRoom(authorization)+ const capacity = Math.min(limit ?? Number.POSITIVE_INFINITY, options.maximumConnectionsPerRoom)+ if (room.peers.size >= capacity) {+ socket.close(RELAY_CLOSE.roomFull, 'Collaboration room is full')+ if (room.peers.size === 0) await leaveRoom(room)+ return null+ }+ const peer: Peer = {+ id: crypto.randomUUID(),+ socket,+ authorization,+ presenceClients: new Set()+ }+ scheduleExpiry(peer)+ send(socket, {+ type: 'welcome',+ peerId: peer.id,+ peers: [RELAY_SERVER_PEER, ...room.peers.keys()]+ })+ for (const other of room.peers.values()) send(other.socket, { type: 'join', peerId: peer.id })+ room.peers.set(peer.id, peer)+ // Ask for what the newcomer has that the room lacks, such as edits made offline.+ if (authorization.permission === 'edit') {+ send(socket, {+ type: 'message',+ namespace: COLLAB_ACTIONS.syncStep1,+ from: RELAY_SERVER_PEER,+ payload: Y.encodeStateVector(room.document)+ })+ }+ return peer+ }++ async function saveAndClose(room: Room) {+ if ((await persist(room)) || shuttingDown) {+ room.document.destroy()+ return+ }+ // The room holds edits the store doesn't have: keep it for whoever joins next, and save+ // again later, closing it once a save lands while nobody is in it.+ rooms.set(room.id, room)+ room.persistTimer = setTimeout(() => {+ void (room.peers.size > 0 ? persist(room) : leaveRoom(room))+ }, persistRetryMs)+ }++ async function leaveRoom(room: Room) {+ if (room.peers.size > 0 || rooms.get(room.id) !== room) return+ rooms.delete(room.id)+ const saved = saveAndClose(room)+ closing.set(room.id, saved)+ try {+ await saved+ } finally {+ if (closing.get(room.id) === saved) closing.delete(room.id)+ }+ }++ function depart(peer: Peer) {+ clearTimeout(peer.expiry)+ const room = rooms.get(peer.authorization.roomId)+ if (!room?.peers.delete(peer.id)) return+ for (const other of room.peers.values()) send(other.socket, { type: 'leave', peerId: peer.id })+ void leaveRoom(room)+ }++ return {+ connect(socket: RelaySocket): RelayConnection {+ let peer: Peer | null = null+ /** Read through an object, since it changes across awaits and between messages. */+ const state = { closed: false, authenticating: false }+ const isClosed = () => state.closed+ const queued: Uint8Array[] = []+ let queuedBytes = 0+ const authTimer = setTimeout(+ () => socket.close(RELAY_CLOSE.unauthorized, 'Expected a collaboration ticket'),+ authTimeoutMs+ )++ async function authenticate(token: string) {+ let authorization: RelayAuthorization+ try {+ authorization = await authorizeRelayTicket(token, options.authSecret)+ } catch {+ socket.close(RELAY_CLOSE.unauthorized, 'Invalid collaboration ticket')+ return+ }+ if (state.closed) return+ if (peer) {+ // A refreshed ticket keeps the peer in its room as the same person; a lowered+ // permission applies from now on.+ const current = peer.authorization+ if (+ authorization.roomId !== current.roomId ||+ principalKey(authorization.principal) !== principalKey(current.principal)+ ) {+ socket.close(RELAY_CLOSE.unauthorized, 'Ticket is for a different room or person')+ return+ }+ peer.authorization = authorization+ scheduleExpiry(peer)+ return+ }+ clearTimeout(authTimer)+ const admitted = await admit(socket, authorization)+ // The socket may have closed while the room loaded.+ if (admitted && isClosed()) depart(admitted)+ else peer = admitted+ }++ function process(data: Uint8Array) {+ if (data.byteLength > options.maximumMessageBytes) {+ socket.close(RELAY_CLOSE.messageTooLarge, 'Collaboration message is too large')+ return+ }+ const frame = decodeRelayClientFrame(data)+ if (!frame) {+ socket.close(RELAY_CLOSE.protocol, 'Malformed collaboration frame')+ return+ }+ if (frame.type === 'auth') {+ state.authenticating = true+ void authenticate(frame.token)+ .catch((error: unknown) => {+ report('Admitting a collaboration peer failed:', error)+ socket.close(RELAY_CLOSE.protocol, 'Could not open the collaboration room')+ })+ .finally(() => {+ state.authenticating = false+ flush()+ })+ return+ }+ const room = peer && rooms.get(peer.authorization.roomId)+ if (!peer || !room) {+ socket.close(RELAY_CLOSE.unauthorized, 'Expected a collaboration ticket')+ return+ }+ handleMessage(room, peer, frame.namespace, frame.target, frame.payload)+ }++ function flush() {+ while (!state.authenticating && !state.closed && queued.length > 0) {+ const next = queued.shift()+ if (!next) continue+ queuedBytes -= next.byteLength+ process(next)+ }+ }++ return {+ receive(data) {+ if (state.closed) return+ queuedBytes += data.byteLength+ // Before admission a peer has sent its ticket and has nothing else to say, so what+ // waits for the room to open is held to one message's worth.+ if (!peer && queuedBytes > options.maximumMessageBytes) {+ queued.length = 0+ queuedBytes = 0+ socket.close(RELAY_CLOSE.messageTooLarge, 'Too much sent before joining the room')+ return+ }+ queued.push(data)+ flush()+ },+ closed() {+ state.closed = true+ queued.length = 0+ queuedBytes = 0+ clearTimeout(authTimer)+ if (peer) depart(peer)+ }+ }+ },++ /** Saves every open room and closes its sockets, as the runtime shuts down. */+ async close() {+ shuttingDown = true+ await Promise.all(+ [...rooms.values()].map(async (room) => {+ for (const peer of room.peers.values()) {+ clearTimeout(peer.expiry)+ peer.socket.close(1001, 'Server shutting down')+ }+ room.peers.clear()+ await leaveRoom(room)+ })+ )+ // Rooms whose last peer left just before, or during, shutdown are still saving.+ await Promise.all(closing.values())+ }+ }+}diff --git a/packages/cloud/src/server/collaboration/relay/index.ts b/packages/cloud/src/server/collaboration/relay/index.tsnew file mode 100644index 000000000..045d94531--- /dev/null+++ b/packages/cloud/src/server/collaboration/relay/index.ts@@ -0,0 +1,14 @@+export { authorizeRelayTicket, type RelayAuthorization } from './authorize'+export { stampAwareness, type StampedAwareness, type VerifiedPresence } from './awareness'+export {+ createCollaborationRelay,+ type CollaborationRelay,+ type CollaborationRelayOptions,+ type RelayConnection,+ type RelaySocket+} from './hub'+export {+ createCollaborationStateStore,+ type CollaborationRoomIdentity,+ type CollaborationStateStore+} from './persistence'diff --git a/packages/cloud/src/server/collaboration/relay/persistence.ts b/packages/cloud/src/server/collaboration/relay/persistence.tsnew file mode 100644index 000000000..2120c0ea9--- /dev/null+++ b/packages/cloud/src/server/collaboration/relay/persistence.ts@@ -0,0 +1,48 @@+import type { CloudDatabase } from '#cloud/server/db'+import type { Kysely } from 'kysely'++export type CollaborationRoomIdentity = {+ documentId: string+ roomEpoch: number+}++/** The relay's saved copy of each room's document, by document and collaboration epoch. */+export type CollaborationStateStore = {+ load(room: CollaborationRoomIdentity): Promise<Uint8Array | null>+ store(room: CollaborationRoomIdentity, state: Uint8Array): Promise<void>+}++export function createCollaborationStateStore(+ database: Kysely<CloudDatabase>+): CollaborationStateStore {+ return {+ async load(room) {+ const row = await database+ .selectFrom('documentCollaborationState')+ .select('state')+ .where('documentId', '=', room.documentId)+ .where('roomEpoch', '=', room.roomEpoch)+ .executeTakeFirst()+ return row ? new Uint8Array(row.state) : null+ },++ async store(room, state) {+ await database+ .insertInto('documentCollaborationState')+ .values({+ documentId: room.documentId,+ roomEpoch: room.roomEpoch,+ state,+ updatedAt: new Date()+ })+ .onConflict((conflict) =>+ conflict.columns(['documentId', 'roomEpoch']).doUpdateSet({+ state,+ version: (expression) => expression('documentCollaborationState.version', '+', 1),+ updatedAt: new Date()+ })+ )+ .execute()+ }+ }+}diff --git a/packages/cloud/src/server/collaboration/service.ts b/packages/cloud/src/server/collaboration/service.tsindex 5660684ec..f438aee7b 100644--- a/packages/cloud/src/server/collaboration/service.ts+++ b/packages/cloud/src/server/collaboration/service.ts@@ -32,14 +32,25 @@ async function derivedRoomKey(authSecret: string, documentId: string, roomEpoch:return base64url.encode(new Uint8Array(bits))}-async function signedTicket(- authSecret: string,- documentId: string,- principal: CollaborationPrincipal,- permission: DocumentPermission,- roomEpoch: number,- collaborationURL?: string-): Promise<CollaborationTicket> {+export type CollaborationTicketClaims = {+ authSecret: string+ documentId: string+ principal: CollaborationPrincipal+ permission: DocumentPermission+ roomEpoch: number+ /** The relay that enforces writes; without one the ticket is for peer-to-peer rooms. */+ relayURL?: string+}++/** Signs a ticket for a document's collaboration room once access has been decided. */+export async function signCollaborationTicket({+ authSecret,+ documentId,+ principal,+ permission,+ roomEpoch,+ relayURL+}: CollaborationTicketClaims): Promise<CollaborationTicket> {const issuedAt = Math.floor(Date.now() / 1000)const expiresAtSeconds = issuedAt + TICKET_LIFETIME_SECONDSconst roomId = `cloud:${documentId}:${roomEpoch}`@@ -50,7 +61,7 @@ async function signedTicket(principal,permission,roomEpoch,- serverEnforcedWrites: Boolean(collaborationURL)+ serverEnforcedWrites: Boolean(relayURL)}const token = await new SignJWT(claims).setProtectedHeader({ alg: 'HS256', typ: 'JWT' })@@ -60,8 +71,8 @@ async function signedTicket(.sign(new TextEncoder().encode(authSecret))return {token,- provider: collaborationURL ? ('hocuspocus' as const) : ('trystero' as const),- ...(collaborationURL ? { serverURL: collaborationURL } : {}),+ provider: relayURL ? ('relay' as const) : ('trystero' as const),+ ...(relayURL ? { serverURL: relayURL } : {}),...claims,roomKey,expiresAt: new Date(expiresAtSeconds * 1000).toISOString()@@ -72,7 +83,7 @@ export type CollaborationTicketServiceOptions = {database: Kysely<CloudDatabase>sharing: DocumentSharingServiceauthSecret: string- collaborationURL?: string+ relayURL?: stringpolicy?: CloudPolicydeploymentMode?: 'official' | 'self-hosted'}@@ -81,7 +92,7 @@ export function createCollaborationTicketService({database,sharing,authSecret,- collaborationURL,+ relayURL,policy,deploymentMode = 'self-hosted'}: CollaborationTicketServiceOptions) {@@ -114,14 +125,14 @@ export function createCollaborationTicketService({.where('deletedAt', 'is', null).executeTakeFirst()if (!document) throw new DocumentNotFoundError()- return signedTicket(+ return signCollaborationTicket({authSecret,documentId,- { kind: 'user', userId: actor.userId, name: actor.name, email: actor.email },- access.permission,- document.collaborationEpoch,- collaborationURL- )+ principal: { kind: 'user', userId: actor.userId, name: actor.name, email: actor.email },+ permission: access.permission,+ roomEpoch: document.collaborationEpoch,+ relayURL+ })},async issueShareTicket(@@ -157,14 +168,14 @@ export function createCollaborationTicketService({.where('deletedAt', 'is', null).executeTakeFirst()if (!document) throw new DocumentNotFoundError()- return signedTicket(+ return signCollaborationTicket({authSecret,- resolved.documentId,- resolved.principal,- resolved.permission,- document.collaborationEpoch,- collaborationURL- )+ documentId: resolved.documentId,+ principal: resolved.principal,+ permission: resolved.permission,+ roomEpoch: document.collaborationEpoch,+ relayURL+ })}}}diff --git a/packages/cloud/src/server/config/deployment.ts b/packages/cloud/src/server/config/deployment.tsindex 9fcd9b3c8..c3ddc2889 100644--- a/packages/cloud/src/server/config/deployment.ts+++ b/packages/cloud/src/server/config/deployment.ts@@ -177,9 +177,7 @@ export const cloudDeploymentConfigSchema = v.object({server_side_encryption: v.optional(v.picklist(['AES256', 'aws:kms'])),kms_key_id: v.optional(text)}),- collaboration: v.optional(- v.object({ public_url: v.pipe(v.string(), v.url()), port: v.optional(positiveInteger, 1234) })- ),+ collaboration: v.optional(v.object({ relay_url: v.pipe(v.string(), v.url()) })),email: emailSchema,workers: v.optional(v.object({@@ -387,8 +385,7 @@ export function parseCloudDeploymentConfig(s3ChecksumVerification: config.object_storage.checksum_verification,s3ServerSideEncryption: config.object_storage.server_side_encryption,s3KmsKeyId: config.object_storage.kms_key_id,- collaborationURL: config.collaboration?.public_url,- collaborationPort: config.collaboration?.port,+ relayURL: config.collaboration?.relay_url,staticEntitlements: staticEntitlements(config),...emailConfig(config, environment),...workerConfig(config),diff --git a/packages/cloud/src/server/config/schema.ts b/packages/cloud/src/server/config/schema.tsindex d7695032c..fcb3a4481 100644--- a/packages/cloud/src/server/config/schema.ts+++ b/packages/cloud/src/server/config/schema.ts@@ -32,11 +32,7 @@ const rawCloudServerConfigSchema = v.object({publicURL: httpURLSchema,appURL: v.optional(httpURLSchema),listingMinimumEditorVersion: v.optional(cloudEditorVersionSchema),- collaborationURL: v.optional(websocketURLSchema),- collaborationPort: v.optional(- v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(65_535)),- 1234- ),+ relayURL: v.optional(websocketURLSchema),technicalLimits: v.optional(v.object({maximumUploadBytes: v.optional(diff --git a/packages/cloud/src/server/index.ts b/packages/cloud/src/server/index.tsindex 871abe5a9..452564b64 100644--- a/packages/cloud/src/server/index.ts+++ b/packages/cloud/src/server/index.ts@@ -69,8 +69,21 @@ export {type UploadCleanupService} from './cleanup'export {+ authorizeRelayTicket,+ createCollaborationRelay,+ createCollaborationStateStore,+ stampAwareness,+ type CollaborationRelay,+ type CollaborationRelayOptions,+ type CollaborationRoomIdentity,+ type CollaborationStateStore,+ type RelayAuthorization,+ type RelayConnection,+ type RelaySocket,createCollaborationRoutes,createCollaborationTicketService,+ signCollaborationTicket,+ type CollaborationTicketClaims,createPublicCollaborationRoutes,type CollaborationRouteEnvironment,type CollaborationTicketServicediff --git a/packages/cloud/tests/client/auth.test.ts b/packages/cloud/tests/client/auth/client.test.tssimilarity index 100%rename from packages/cloud/tests/client/auth.test.tsrename to packages/cloud/tests/client/auth/client.test.tsdiff --git a/packages/cloud/tests/client/auth-failure.test.ts b/packages/cloud/tests/client/auth/failure.test.tssimilarity index 100%rename from packages/cloud/tests/client/auth-failure.test.tsrename to packages/cloud/tests/client/auth/failure.test.tsdiff --git a/packages/cloud/tests/client/auth-navigation.test.ts b/packages/cloud/tests/client/auth/navigation.test.tssimilarity index 100%rename from packages/cloud/tests/client/auth-navigation.test.tsrename to packages/cloud/tests/client/auth/navigation.test.tsdiff --git a/packages/cloud/tests/contract/relay.test.ts b/packages/cloud/tests/contract/relay.test.tsnew file mode 100644index 000000000..9c7d7f960--- /dev/null+++ b/packages/cloud/tests/contract/relay.test.ts@@ -0,0 +1,47 @@+import { describe, expect, test } from 'bun:test'++import {+ decodeRelayClientFrame,+ decodeRelayServerFrame,+ encodeRelayClientFrame,+ encodeRelayServerFrame,+ type RelayClientFrame,+ type RelayServerFrame+} from '#cloud/contract'++describe('relay frames', () => {+ test('round-trip every client frame', () => {+ const frames: RelayClientFrame[] = [+ { type: 'auth', token: 'ticket' },+ { type: 'message', namespace: 'yjs-update', target: null, payload: new Uint8Array([1, 2]) },+ { type: 'message', namespace: 'sync-step1', target: 'server', payload: new Uint8Array() }+ ]+ for (const frame of frames) {+ expect(decodeRelayClientFrame(encodeRelayClientFrame(frame))).toEqual(frame)+ }+ })++ test('round-trip every server frame', () => {+ const frames: RelayServerFrame[] = [+ { type: 'welcome', peerId: 'a', peers: ['server', 'b'] },+ { type: 'join', peerId: 'c' },+ { type: 'leave', peerId: 'c' },+ { type: 'message', namespace: 'awareness', from: 'b', payload: new Uint8Array([9]) }+ ]+ for (const frame of frames) {+ expect(decodeRelayServerFrame(encodeRelayServerFrame(frame))).toEqual(frame)+ }+ })++ test('reject truncated and unknown frames', () => {+ const message = encodeRelayClientFrame({+ type: 'message',+ namespace: 'yjs-update',+ target: null,+ payload: new Uint8Array([1, 2, 3])+ })+ expect(decodeRelayClientFrame(message.subarray(0, -2))).toBeNull()+ expect(decodeRelayClientFrame(new Uint8Array([7]))).toBeNull()+ expect(decodeRelayServerFrame(new Uint8Array([7]))).toBeNull()+ })+})diff --git a/packages/cloud/tests/helpers/relay.ts b/packages/cloud/tests/helpers/relay.tsnew file mode 100644index 000000000..05868384d--- /dev/null+++ b/packages/cloud/tests/helpers/relay.ts@@ -0,0 +1,118 @@+import {+ decodeRelayServerFrame,+ encodeRelayClientFrame,+ type CollaborationPrincipal,+ type DocumentPermission,+ type RelayClientFrame,+ type RelayServerFrame+} from '#cloud/contract'+import type {+ CollaborationRoomIdentity,+ CollaborationStateStore,+ RelayConnection,+ RelaySocket+} from '#cloud/server'+import { SignJWT } from 'jose'++export const relaySecret = 'relay-test-secret-at-least-32-characters'++export type RelayTicketOptions = {+ documentId: string+ permission: DocumentPermission+ principal: CollaborationPrincipal+ roomEpoch?: number+ roomId?: string+ expiresInSeconds?: number+}++export async function relayTicket(options: RelayTicketOptions): Promise<string> {+ const roomEpoch = options.roomEpoch ?? 0+ const issuedAt = Math.floor(Date.now() / 1000)+ return new SignJWT({+ documentId: options.documentId,+ roomId: options.roomId ?? `cloud:${options.documentId}:${roomEpoch}`,+ principal: options.principal,+ permission: options.permission,+ roomEpoch,+ serverEnforcedWrites: true+ })+ .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })+ .setIssuedAt(issuedAt)+ .setExpirationTime(issuedAt + (options.expiresInSeconds ?? 300))+ .sign(new TextEncoder().encode(relaySecret))+}++export function user(userId: string, name = userId): CollaborationPrincipal {+ return { kind: 'user', userId, name, email: `${userId}@example.com` }+}++export function guest(guestId: string, name = guestId): CollaborationPrincipal {+ return { kind: 'guest', guestId, name }+}++/** An in-memory socket that records what the relay sends and how it closed. */+export type TestRelayClient = {+ frames: RelayServerFrame[]+ closed: { code: number; reason: string } | null+ connection: RelayConnection+ send(frame: RelayClientFrame): void+ /** The peer ID from the relay's welcome. */+ peerId(): string | undefined+ messages(namespace: string): Extract<RelayServerFrame, { type: 'message' }>[]+}++export function connectTestClient(connect: (socket: RelaySocket) => RelayConnection) {+ const client: Omit<TestRelayClient, 'connection'> = {+ frames: [],+ closed: null,+ send(frame) {+ connection.receive(encodeRelayClientFrame(frame))+ },+ peerId() {+ const welcome = client.frames.find((frame) => frame.type === 'welcome')+ return welcome?.type === 'welcome' ? welcome.peerId : undefined+ },+ messages(namespace) {+ return client.frames.flatMap((frame) =>+ frame.type === 'message' && frame.namespace === namespace ? [frame] : []+ )+ }+ }+ const connection = connect({+ send(data) {+ const frame = decodeRelayServerFrame(data)+ if (frame) client.frames.push(frame)+ },+ close(code, reason) {+ if (client.closed) return+ client.closed = { code, reason }+ connection.closed()+ }+ })+ return Object.assign(client, { connection })+}++/** Resolves once `condition` holds, yielding to pending work between checks. */+export async function until(condition: () => boolean, attempts = 200): Promise<void> {+ for (let attempt = 0; attempt < attempts; attempt++) {+ if (condition()) return+ await new Promise((resolve) => {+ setTimeout(resolve, 1)+ })+ }+ throw new Error('Condition was not met')+}++export function memoryStateStore() {+ const states = new Map<string, Uint8Array>()+ const key = (room: CollaborationRoomIdentity) => `${room.documentId}:${room.roomEpoch}`+ const store: CollaborationStateStore = {+ async load(room) {+ return states.get(key(room)) ?? null+ },+ async store(room, state) {+ states.set(key(room), state)+ }+ }+ return { store, states }+}diff --git a/packages/cloud/tests/integration/server/collaboration/relay.test.ts b/packages/cloud/tests/integration/server/collaboration/relay.test.tsnew file mode 100644index 000000000..b5e6a2309--- /dev/null+++ b/packages/cloud/tests/integration/server/collaboration/relay.test.ts@@ -0,0 +1,139 @@+import { describe, expect, test } from 'bun:test'++import { createCloudTestDatabase } from '#cloud-tests/helpers/database'+import { connectTestClient, until } from '#cloud-tests/helpers/relay'+import {+ COLLAB_ACTIONS,+ decodeRoomUpdate,+ MAX_COLLAB_MESSAGE_BYTES,+ RELAY_SERVER_PEER+} from '#cloud/contract'+import {+ createCollaborationRelay,+ createCollaborationStateStore,+ createCollaborationTicketService,+ createDocumentSharingService+} from '#cloud/server'+import * as Y from 'yjs'++const authSecret = 'collaboration-test-secret-at-least-32-characters'+const relayURL = 'wss://cloud.example.com/api/collaboration/relay'++async function seed() {+ const runtime = await createCloudTestDatabase()+ const workspaceId = crypto.randomUUID()+ const documentId = crypto.randomUUID()+ await runtime.database+ .insertInto('workspace')+ .values({ id: workspaceId, name: 'Design', slug: `design-${workspaceId}`, createdBy: 'owner' })+ .execute()+ await runtime.database+ .insertInto('workspaceMember')+ .values([+ { workspaceId, userId: 'owner', role: 'admin' },+ { workspaceId, userId: 'viewer', role: 'viewer' }+ ])+ .execute()+ await runtime.database+ .insertInto('document')+ .values({ id: documentId, workspaceId, name: 'Homepage', createdBy: 'owner' })+ .execute()+ const tickets = createCollaborationTicketService({+ database: runtime.database,+ sharing: createDocumentSharingService(runtime.database),+ authSecret,+ relayURL+ })+ const store = createCollaborationStateStore(runtime.database)+ const relay = () =>+ createCollaborationRelay({+ authSecret,+ store,+ maximumMessageBytes: 1_048_576,+ maximumConnectionsPerRoom: 100,+ persistDelayMs: 0+ })+ return { runtime, documentId, tickets, store, relay }+}++describe('collaboration relay with issued tickets', () => {+ test('admits ticket holders and keeps the room in PostgreSQL across relay restarts', async () => {+ const context = await seed()+ try {+ const owner = { userId: 'owner', name: 'Owner', email: '[email protected]' }+ const ticket = await context.tickets.issueUserTicket(owner, context.documentId)+ expect(ticket).toMatchObject({+ provider: 'relay',+ serverURL: relayURL,+ serverEnforcedWrites: true+ })++ const first = context.relay()+ const editor = connectTestClient((socket) => first.connect(socket))+ editor.send({ type: 'auth', token: ticket.token })+ await until(() => editor.peerId() !== undefined)+ const document = new Y.Doc()+ document.getText('t').insert(0, 'saved')+ editor.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: Y.encodeStateAsUpdateV2(document)+ })+ editor.connection.closed()+ await first.close()++ const stored = await context.store.load({ documentId: context.documentId, roomEpoch: 0 })+ expect(stored).not.toBeNull()++ const second = context.relay()+ const viewerTicket = await context.tickets.issueUserTicket(+ { userId: 'viewer', name: 'Viewer', email: '[email protected]' },+ context.documentId+ )+ const viewer = connectTestClient((socket) => second.connect(socket))+ viewer.send({ type: 'auth', token: viewerTicket.token })+ await until(() => viewer.peerId() !== undefined)+ viewer.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.syncStep1,+ target: RELAY_SERVER_PEER,+ payload: Y.encodeStateVector(new Y.Doc())+ })+ await until(() => viewer.messages(COLLAB_ACTIONS.syncReply).length > 0)+ const restored = new Y.Doc()+ const reply = decodeRoomUpdate(+ viewer.messages(COLLAB_ACTIONS.syncReply)[0]?.payload ?? new Uint8Array(),+ { limit: MAX_COLLAB_MESSAGE_BYTES, compressed: true }+ )+ if (reply) Y.applyUpdateV2(restored, reply)+ expect(restored.getText('t').toString()).toBe('saved')+ await second.close()+ } finally {+ await context.runtime.close()+ }+ })++ test('issues peer-to-peer tickets the relay refuses when no relay is configured', async () => {+ const context = await seed()+ try {+ const tickets = createCollaborationTicketService({+ database: context.runtime.database,+ sharing: createDocumentSharingService(context.runtime.database),+ authSecret+ })+ const ticket = await tickets.issueUserTicket(+ { userId: 'owner', name: 'Owner', email: '[email protected]' },+ context.documentId+ )+ expect(ticket).toMatchObject({ provider: 'trystero', serverEnforcedWrites: false })+ const relay = context.relay()+ const client = connectTestClient((socket) => relay.connect(socket))+ client.send({ type: 'auth', token: ticket.token })+ await until(() => client.closed !== null)+ expect(client.closed?.code).toBe(4401)+ } finally {+ await context.runtime.close()+ }+ })+})diff --git a/packages/cloud/tests/runtime/node/entitlements-command.test.ts b/packages/cloud/tests/runtime/node/entitlements/refusal.test.tssimilarity index 97%rename from packages/cloud/tests/runtime/node/entitlements-command.test.tsrename to packages/cloud/tests/runtime/node/entitlements/refusal.test.tsindex 4c052f21e..815de5f7e 100644--- a/packages/cloud/tests/runtime/node/entitlements-command.test.ts+++ b/packages/cloud/tests/runtime/node/entitlements/refusal.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'bun:test'-import { entitlementWriteRefusal } from '#cloud/runtime/node/entitlements-command'+import { entitlementWriteRefusal } from '#cloud/runtime/node/entitlements/refusal'const staticConfig = {staticEntitlements: { documents: {}, sharing: {}, storage: {}, collaboration: {} }diff --git a/packages/cloud/tests/runtime/node/relay.test.ts b/packages/cloud/tests/runtime/node/relay.test.tsnew file mode 100644index 000000000..f19e17360--- /dev/null+++ b/packages/cloud/tests/runtime/node/relay.test.ts@@ -0,0 +1,106 @@+import { afterEach, describe, expect, test } from 'bun:test'+import { createServer, type Server } from 'node:http'++import { memoryStateStore, relaySecret, relayTicket, user } from '#cloud-tests/helpers/relay'+import {+ decodeRelayServerFrame,+ encodeRelayClientFrame,+ RELAY_CLOSE,+ RELAY_PATH,+ type RelayServerFrame+} from '#cloud/contract'+import { attachCollaborationRelay, defaultRelayURL } from '#cloud/runtime/node'+import { createCollaborationRelay } from '#cloud/server'++const cleanups: (() => Promise<void>)[] = []++afterEach(async () => {+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup()+})++async function listening(maximumMessageBytes = 1_048_576) {+ const server: Server = createServer()+ const relay = createCollaborationRelay({+ authSecret: relaySecret,+ store: memoryStateStore().store,+ maximumMessageBytes,+ maximumConnectionsPerRoom: 10+ })+ const attached = attachCollaborationRelay(server, relay, maximumMessageBytes)+ await new Promise<void>((resolve) => {+ server.listen(0, '127.0.0.1', resolve)+ })+ const address = server.address()+ if (!address || typeof address === 'string') throw new Error('Expected a TCP address')+ cleanups.push(async () => {+ await attached.close()+ await new Promise<void>((resolve) => {+ server.close(() => resolve())+ })+ })+ return `ws://127.0.0.1:${address.port}`+}++function open(url: string) {+ const socket = new WebSocket(url)+ socket.binaryType = 'arraybuffer'+ const frames: RelayServerFrame[] = []+ const closed = new Promise<number>((resolve) => {+ socket.addEventListener('close', (event) => resolve(event.code))+ })+ const opened = new Promise<void>((resolve, reject) => {+ socket.addEventListener('open', () => resolve())+ socket.addEventListener('error', () => reject(new Error('WebSocket failed')))+ })+ const welcomed = new Promise<RelayServerFrame>((resolve) => {+ socket.addEventListener('message', (event: MessageEvent<ArrayBuffer>) => {+ const frame = decodeRelayServerFrame(new Uint8Array(event.data))+ if (!frame) return+ frames.push(frame)+ if (frame.type === 'welcome') resolve(frame)+ })+ })+ return { socket, frames, opened, welcomed, closed }+}++describe('Node collaboration relay listener', () => {+ test('admits a ticket holder over a real WebSocket', async () => {+ const base = await listening()+ const client = open(`${base}${RELAY_PATH}`)+ cleanups.push(async () => client.socket.close())+ await client.opened+ const documentId = crypto.randomUUID()+ client.socket.send(+ encodeRelayClientFrame({+ type: 'auth',+ token: await relayTicket({ documentId, permission: 'edit', principal: user('alice') })+ })+ )+ expect(await client.welcomed).toMatchObject({ type: 'welcome', peers: ['server'] })+ })++ test('refuses upgrades on other paths', async () => {+ const base = await listening()+ const client = open(`${base}/elsewhere`)+ expect(client.opened).rejects.toThrow()+ await client.closed+ })++ test('closes sockets that send more than the message limit', async () => {+ const base = await listening(1_024)+ const client = open(`${base}${RELAY_PATH}`)+ await client.opened+ client.socket.send(new Uint8Array(4_096))+ // ws refuses the frame with 1009 under Node; Bun's ws ignores maxPayload and the relay refuses it.+ expect([1009, RELAY_CLOSE.messageTooLarge]).toContain(await client.closed)+ })+})++describe('default relay URL', () => {+ test('uses the API origin with a WebSocket scheme', () => {+ expect(defaultRelayURL('https://cloud.example.com')).toBe(+ `wss://cloud.example.com${RELAY_PATH}`+ )+ expect(defaultRelayURL('http://localhost:8787/')).toBe(`ws://localhost:8787${RELAY_PATH}`)+ })+})diff --git a/packages/cloud/tests/server/collaboration/relay/awareness.test.ts b/packages/cloud/tests/server/collaboration/relay/awareness.test.tsnew file mode 100644index 000000000..9e957e5f0--- /dev/null+++ b/packages/cloud/tests/server/collaboration/relay/awareness.test.ts@@ -0,0 +1,70 @@+import { describe, expect, test } from 'bun:test'++import { guest, user } from '#cloud-tests/helpers/relay'+import { stampAwareness } from '#cloud/server'+import * as awarenessProtocol from 'y-protocols/awareness'+import * as Y from 'yjs'++function presence(state: Record<string, unknown> | null) {+ const awareness = new awarenessProtocol.Awareness(new Y.Doc())+ awareness.setLocalState(state)+ return {+ awareness,+ update: awarenessProtocol.encodeAwarenessUpdate(awareness, [awareness.clientID])+ }+}++function received(update: Uint8Array) {+ const awareness = new awarenessProtocol.Awareness(new Y.Doc())+ awarenessProtocol.applyAwarenessUpdate(awareness, update, 'remote')+ return awareness+}++describe('relay presence stamping', () => {+ test('replaces the claimed name with the verified one and adds the verified identity', () => {+ const source = presence({ user: { name: 'Mallory', color: '#f00' }, cursor: { x: 1 } })+ const stamped = stampAwareness(+ source.update,+ { principal: user('alice', 'Alice'), permission: 'view' },+ () => false+ )+ expect(stamped.claimed).toEqual([source.awareness.clientID])+ if (!stamped.update) throw new Error('Expected a forwarded update')+ expect(received(stamped.update).getStates().get(source.awareness.clientID)).toEqual({+ user: { name: 'Alice', color: '#f00' },+ cursor: { x: 1 },+ cloud: { kind: 'user', id: 'alice', name: 'Alice', permission: 'view' }+ })+ })++ test('never exposes a user email', () => {+ const source = presence({ user: { name: 'x' } })+ const stamped = stampAwareness(+ source.update,+ { principal: user('alice'), permission: 'edit' },+ () => false+ )+ if (!stamped.update) throw new Error('Expected a forwarded update')+ expect(new TextDecoder().decode(stamped.update)).not.toContain('@example.com')+ })++ test('drops entries for presence clients another peer owns', () => {+ const source = presence({ user: { name: 'Guest' } })+ const stamped = stampAwareness(+ source.update,+ { principal: guest('g1'), permission: 'view' },+ (clientId) => clientId === source.awareness.clientID+ )+ expect(stamped).toEqual({ update: null, claimed: [] })+ })++ test('drops malformed updates', () => {+ expect(+ stampAwareness(+ new Uint8Array([5, 1]),+ { principal: guest('g1'), permission: 'view' },+ () => false+ )+ ).toEqual({ update: null, claimed: [] })+ })+})diff --git a/packages/cloud/tests/server/collaboration/relay/hub.test.ts b/packages/cloud/tests/server/collaboration/relay/hub.test.tsnew file mode 100644index 000000000..78611a62f--- /dev/null+++ b/packages/cloud/tests/server/collaboration/relay/hub.test.ts@@ -0,0 +1,505 @@+import { describe, expect, test } from 'bun:test'++import {+ connectTestClient,+ guest,+ memoryStateStore,+ relaySecret,+ relayTicket,+ until,+ user,+ type RelayTicketOptions+} from '#cloud-tests/helpers/relay'+import {+ COLLAB_ACTIONS,+ decodeRoomUpdate,+ encodeSyncReply,+ MAX_COLLAB_MESSAGE_BYTES,+ RELAY_CLOSE,+ RELAY_SERVER_PEER+} from '#cloud/contract'+import { createCollaborationRelay, type CollaborationRelayOptions } from '#cloud/server'+import * as awarenessProtocol from 'y-protocols/awareness'+import * as Y from 'yjs'++const documentId = crypto.randomUUID()++function relay(options: Partial<CollaborationRelayOptions> = {}) {+ const state = memoryStateStore()+ const instance = createCollaborationRelay({+ authSecret: relaySecret,+ store: state.store,+ maximumMessageBytes: 1_048_576,+ maximumConnectionsPerRoom: 100,+ persistDelayMs: 0,+ onError: () => undefined,+ ...options+ })+ return { relay: instance, ...state }+}++async function join(+ hub: ReturnType<typeof relay>['relay'],+ ticket: Partial<RelayTicketOptions> = {}+) {+ const client = connectTestClient((socket) => hub.connect(socket))+ client.send({+ type: 'auth',+ token: await relayTicket({+ documentId,+ permission: 'edit',+ principal: user(crypto.randomUUID()),+ ...ticket+ })+ })+ await until(() => client.peerId() !== undefined || client.closed !== null)+ return client+}++function edit(text: string) {+ const document = new Y.Doc()+ document.getText('t').insert(0, text)+ return Y.encodeStateAsUpdateV2(document)+}++/** What an editor holding `text` answers a sync request from an empty peer with. */+function syncReply(text: string) {+ const document = new Y.Doc()+ document.getText('t').insert(0, text)+ return encodeSyncReply(document, Y.encodeStateVector(new Y.Doc()))+}++/** The text a sync reply carries, which travels as a compressed V2 update. */+function textOf(reply: Uint8Array) {+ const document = new Y.Doc()+ const update = decodeRoomUpdate(reply, { limit: MAX_COLLAB_MESSAGE_BYTES, compressed: true })+ if (update) Y.applyUpdateV2(document, update)+ return document.getText('t').toString()+}++describe('collaboration relay', () => {+ test('welcomes peers with everyone in the room and announces arrivals and departures', async () => {+ const { relay: hub } = relay()+ const alice = await join(hub)+ const bob = await join(hub)+ const [aliceId, bobId] = [alice.peerId() ?? '', bob.peerId() ?? '']++ expect(alice.frames[0]).toEqual({+ type: 'welcome',+ peerId: aliceId,+ peers: [RELAY_SERVER_PEER]+ })+ expect(bob.frames[0]).toEqual({+ type: 'welcome',+ peerId: bobId,+ peers: [RELAY_SERVER_PEER, aliceId]+ })+ expect(alice.frames).toContainEqual({ type: 'join', peerId: bobId })++ bob.connection.closed()+ expect(alice.frames).toContainEqual({ type: 'leave', peerId: bobId })+ })++ test('keeps the document from editors and serves it to newcomers', async () => {+ const { relay: hub } = relay()+ const alice = await join(hub)+ alice.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: edit('hello')+ })++ const bob = await join(hub, { permission: 'view' })+ bob.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.syncStep1,+ target: RELAY_SERVER_PEER,+ payload: Y.encodeStateVector(new Y.Doc())+ })+ const [reply] = bob.messages(COLLAB_ACTIONS.syncReply)+ expect(reply?.from).toBe(RELAY_SERVER_PEER)+ expect(textOf(reply?.payload ?? new Uint8Array())).toBe('hello')+ })++ test('asks editors, not viewers, for what they have that the room lacks', async () => {+ const { relay: hub } = relay()+ const editor = await join(hub)+ const viewer = await join(hub, { permission: 'view' })+ expect(editor.messages(COLLAB_ACTIONS.syncStep1).map((frame) => frame.from)).toEqual([+ RELAY_SERVER_PEER+ ])+ expect(viewer.messages(COLLAB_ACTIONS.syncStep1)).toEqual([])+ })++ test('takes an editor’s compressed answer into the room', async () => {+ const { relay: hub } = relay()+ const editor = await join(hub)+ editor.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.syncReply,+ target: RELAY_SERVER_PEER,+ payload: syncReply('offline')+ })+ expect(editor.closed).toBeNull()++ const bob = await join(hub)+ bob.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.syncStep1,+ target: RELAY_SERVER_PEER,+ payload: Y.encodeStateVector(new Y.Doc())+ })+ expect(textOf(bob.messages(COLLAB_ACTIONS.syncReply)[0]?.payload ?? new Uint8Array())).toBe(+ 'offline'+ )+ })++ test('forwards editor messages to everyone or to the named peer', async () => {+ const { relay: hub } = relay()+ const alice = await join(hub)+ const bob = await join(hub)+ const carol = await join(hub)+ const update = edit('x')+ alice.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: update+ })+ alice.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.agentPreview,+ target: carol.peerId() ?? null,+ payload: new Uint8Array([1])+ })++ for (const peer of [bob, carol]) {+ expect(peer.messages(COLLAB_ACTIONS.yjsUpdate)).toEqual([+ {+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ from: alice.peerId() ?? '',+ payload: update+ }+ ])+ }+ expect(alice.messages(COLLAB_ACTIONS.yjsUpdate)).toEqual([])+ expect(bob.messages(COLLAB_ACTIONS.agentPreview)).toEqual([])+ expect(carol.messages(COLLAB_ACTIONS.agentPreview)).toHaveLength(1)+ })++ test('drops document writes from viewers', async () => {+ const { relay: hub } = relay()+ const editor = await join(hub)+ const viewer = await join(hub, { permission: 'view' })+ for (const namespace of [+ COLLAB_ACTIONS.yjsUpdate,+ COLLAB_ACTIONS.syncReply,+ COLLAB_ACTIONS.agentPreview+ ]) {+ viewer.send({ type: 'message', namespace, target: null, payload: edit('vandal') })+ }+ viewer.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.syncReply,+ target: RELAY_SERVER_PEER,+ payload: edit('vandal')+ })++ expect(+ editor.frames.filter((frame) => frame.type === 'message' && frame.from === viewer.peerId())+ ).toEqual([])+ const newcomer = await join(hub, { permission: 'view' })+ newcomer.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.syncStep1,+ target: RELAY_SERVER_PEER,+ payload: Y.encodeStateVector(new Y.Doc())+ })+ expect(+ textOf(newcomer.messages(COLLAB_ACTIONS.syncReply)[0]?.payload ?? new Uint8Array())+ ).toBe('')+ })++ test('forwards viewer presence under the identity on their ticket', async () => {+ const { relay: hub } = relay()+ const editor = await join(hub)+ const viewer = await join(hub, { permission: 'view', principal: guest('g1', 'Grace') })+ const awareness = new awarenessProtocol.Awareness(new Y.Doc())+ awareness.setLocalState({ user: { name: 'Admin' } })+ viewer.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.awareness,+ target: null,+ payload: awarenessProtocol.encodeAwarenessUpdate(awareness, [awareness.clientID])+ })++ const [forwarded] = editor.messages(COLLAB_ACTIONS.awareness)+ const seen = new awarenessProtocol.Awareness(new Y.Doc())+ awarenessProtocol.applyAwarenessUpdate(seen, forwarded?.payload ?? new Uint8Array(), 'remote')+ expect(seen.getStates().get(awareness.clientID)).toMatchObject({+ user: { name: 'Grace' },+ cloud: { kind: 'guest', id: 'g1', permission: 'view' }+ })+ })++ test('saves the room when its last peer leaves and loads it when the room reopens', async () => {+ const first = relay()+ const alice = await join(first.relay)+ alice.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: edit('kept')+ })+ alice.connection.closed()+ await until(() => first.states.size > 0)++ const second = createCollaborationRelay({+ authSecret: relaySecret,+ store: first.store,+ maximumMessageBytes: 1_048_576,+ maximumConnectionsPerRoom: 100+ })+ const bob = await join(second, { permission: 'view' })+ bob.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.syncStep1,+ target: RELAY_SERVER_PEER,+ payload: Y.encodeStateVector(new Y.Doc())+ })+ expect(textOf(bob.messages(COLLAB_ACTIONS.syncReply)[0]?.payload ?? new Uint8Array())).toBe(+ 'kept'+ )+ await second.close()+ })++ test('admits a newcomer to the live room when the last peer leaves while it is checked', async () => {+ let releaseLimit: (() => void) | undefined+ let checks = 0+ const hub = relay({+ async maximumParticipants() {+ checks+++ if (checks === 2) {+ await new Promise<void>((resolve) => {+ releaseLimit = resolve+ })+ }+ return 10+ }+ })+ const alice = await join(hub.relay)+ alice.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: edit('kept')+ })+ const bobJoining = join(hub.relay, { permission: 'view' })+ await until(() => releaseLimit !== undefined)+ alice.connection.closed()+ await until(() => hub.states.size > 0)+ releaseLimit?.()++ const bob = await bobJoining+ bob.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.syncStep1,+ target: RELAY_SERVER_PEER,+ payload: Y.encodeStateVector(new Y.Doc())+ })+ await until(() => bob.messages(COLLAB_ACTIONS.syncReply).length > 0 || bob.closed !== null)+ expect(bob.closed).toBeNull()+ expect(textOf(bob.messages(COLLAB_ACTIONS.syncReply)[0]?.payload ?? new Uint8Array())).toBe(+ 'kept'+ )+ })++ test('keeps a room whose save failed and hands it to the next peer', async () => {+ const state = memoryStateStore()+ let refuse = true+ const hub = createCollaborationRelay({+ authSecret: relaySecret,+ store: {+ load: state.store.load,+ async store(room, update) {+ if (refuse) throw new Error('Database unavailable')+ await state.store.store(room, update)+ }+ },+ maximumMessageBytes: 1_048_576,+ maximumConnectionsPerRoom: 100,+ persistDelayMs: 0,+ persistRetryMs: 10,+ onError: () => undefined+ })+ const alice = await join(hub)+ alice.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: edit('unsaved')+ })+ alice.connection.closed()++ const bob = await join(hub, { permission: 'view' })+ bob.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.syncStep1,+ target: RELAY_SERVER_PEER,+ payload: Y.encodeStateVector(new Y.Doc())+ })+ await until(() => bob.messages(COLLAB_ACTIONS.syncReply).length > 0)+ expect(textOf(bob.messages(COLLAB_ACTIONS.syncReply)[0]?.payload ?? new Uint8Array())).toBe(+ 'unsaved'+ )++ // Once the store accepts it again, the retry saves what the room held.+ refuse = false+ bob.connection.closed()+ await until(() => state.states.size > 0)+ await hub.close()+ })++ test('stops retrying a failed save once the relay closes', async () => {+ let attempts = 0+ const hub = createCollaborationRelay({+ authSecret: relaySecret,+ store: {+ load: memoryStateStore().store.load,+ async store() {+ attempts+++ throw new Error('Database unavailable')+ }+ },+ maximumMessageBytes: 1_048_576,+ maximumConnectionsPerRoom: 100,+ persistDelayMs: 60_000,+ persistRetryMs: 5,+ onError: () => undefined+ })+ const alice = await join(hub)+ alice.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: edit('unsaved')+ })+ await hub.close()+ const afterClose = attempts+ await Bun.sleep(30)+ expect(attempts).toBe(afterClose)+ })++ test('closes a socket that sends too much before it joins the room', async () => {+ let releaseLimit: (() => void) | undefined+ const { relay: hub } = relay({+ maximumMessageBytes: 4096,+ async maximumParticipants() {+ await new Promise<void>((resolve) => {+ releaseLimit = resolve+ })+ return 10+ }+ })+ const client = connectTestClient((socket) => hub.connect(socket))+ client.send({+ type: 'auth',+ token: await relayTicket({ documentId, permission: 'edit', principal: user('flooder') })+ })+ await until(() => releaseLimit !== undefined)+ for (let index = 0; index < 4; index++) {+ client.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: new Uint8Array(2048)+ })+ }+ expect(client.closed?.code).toBe(RELAY_CLOSE.messageTooLarge)+ releaseLimit?.()+ })++ test('refuses sockets without a valid ticket for the room', async () => {+ const { relay: hub } = relay({ authTimeoutMs: 5 })+ const silent = connectTestClient((socket) => hub.connect(socket))+ await until(() => silent.closed !== null)+ expect(silent.closed?.code).toBe(RELAY_CLOSE.unauthorized)++ const forged = connectTestClient((socket) => hub.connect(socket))+ forged.send({ type: 'auth', token: 'not-a-ticket' })+ await until(() => forged.closed !== null)+ expect(forged.closed?.code).toBe(RELAY_CLOSE.unauthorized)++ const elsewhere = await join(hub, { roomId: `cloud:${crypto.randomUUID()}:0` })+ expect(elsewhere.closed?.code).toBe(RELAY_CLOSE.unauthorized)++ const early = connectTestClient((socket) => hub.connect(socket))+ early.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: edit('x')+ })+ expect(early.closed?.code).toBe(RELAY_CLOSE.unauthorized)+ })++ test('keeps a peer that refreshes its ticket and closes one that changes identity', async () => {+ const { relay: hub } = relay()+ const principal = user('alice')+ const alice = await join(hub, { principal })+ alice.send({+ type: 'auth',+ token: await relayTicket({ documentId, permission: 'view', principal })+ })+ await until(() => alice.closed === null)+ alice.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: edit('x')+ })+ const bob = await join(hub)+ expect(bob.messages(COLLAB_ACTIONS.yjsUpdate)).toEqual([])++ alice.send({+ type: 'auth',+ token: await relayTicket({ documentId, permission: 'edit', principal: user('mallory') })+ })+ await until(() => alice.closed !== null)+ expect(alice.closed?.code).toBe(RELAY_CLOSE.unauthorized)+ })++ test('enforces room capacity, participant limits, and message size', async () => {+ const full = relay({ maximumConnectionsPerRoom: 1 })+ await join(full.relay)+ expect((await join(full.relay)).closed?.code).toBe(RELAY_CLOSE.roomFull)++ const limited = relay({ maximumParticipants: async () => 1 })+ await join(limited.relay)+ expect((await join(limited.relay)).closed?.code).toBe(RELAY_CLOSE.roomFull)++ const small = relay({ maximumMessageBytes: 4_096 })+ const alice = await join(small.relay)+ alice.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: new Uint8Array(8_192)+ })+ expect(alice.closed?.code).toBe(RELAY_CLOSE.messageTooLarge)+ })++ test('closes peers that send malformed document updates', async () => {+ const { relay: hub } = relay()+ const alice = await join(hub)+ alice.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: new Uint8Array([255, 255, 255])+ })+ expect(alice.closed?.code).toBe(RELAY_CLOSE.protocol)+ })+})diff --git a/packages/cloud/tests/server/config/deployment.test.ts b/packages/cloud/tests/server/config/deployment.test.tsindex b0b948367..9d6f6a42b 100644--- a/packages/cloud/tests/server/config/deployment.test.ts+++ b/packages/cloud/tests/server/config/deployment.test.ts@@ -183,6 +183,19 @@ describe('Cloud TOML deployment configuration', () => {).toThrow()})+ test('reads a relay URL override and requires a WebSocket scheme', () => {+ const relay = (url: string) =>+ parseCloudDeploymentTOML(+ `${minimalSource}\n[collaboration]\nrelay_url = "${url}"\n`,+ environment+ )+ expect(relay('wss://relay.example.com/api/collaboration/relay').relayURL).toBe(+ 'wss://relay.example.com/api/collaboration/relay'+ )+ expect(() => relay('https://relay.example.com')).toThrow()+ expect(parseCloudDeploymentTOML(minimalSource, environment).relayURL).toBeUndefined()+ })+test('supports explicit secret-reference names', () => {const input = parseTOML(minimalSource)const parsed = v.parse(cloudDeploymentConfigSchema, input)diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.mdindex 80ac52a8c..d217b6b75 100644--- a/packages/docs/development/cloud.md+++ b/packages/docs/development/cloud.md@@ -66,6 +66,41 @@ headers. Invitation continuations through OAuth are single-use compact JWE.Collaboration tickets are signed, epoch-scoped JWTs naming the principal and permission. Rotating acapability secret keeps the current epoch; revoking access advances it so old tickets stop working.+## Live collaboration++Collaboration in the editor runs Yjs sync and awareness over a `CollabRoomTransport`. Local+documents use Trystero peer-to-peer; Cloud documents use the Cloud relay, a WebSocket endpoint at+`/api/collaboration/relay` on the API origin. Both carry the same room messages, so the editor has+one sync implementation.++```mermaid+sequenceDiagram+ participant A as Editor+ participant R as Relay (server peer)+ participant B as Viewer+ A->>R: auth (ticket)+ R-->>A: welcome [server]+ R->>A: sync-step1+ A->>R: sync-reply (offline edits)+ B->>R: auth (ticket)+ R-->>B: welcome [server, A]+ B->>R: sync-step1 to server+ R-->>B: sync-reply (room document)+ A->>R: yjs-update+ R-->>B: yjs-update+ B->>R: yjs-update (dropped)+```++The relay joins every room as a peer named `server`. It holds the room's Yjs document, saved in+PostgreSQL by document and collaboration epoch, so a newcomer gets the document even when nobody+else is online. Tickets are short-lived signed JWTs; the client presents a fresh one before the+current one expires, and the relay closes a socket whose ticket lapsed or changed identity.++The relay enforces what the ticket allows: a viewer's document updates and sync replies never leave+it, and presence updates are rewritten so others see the ticket's name and a `cloud` field with the+verified identity and permission. A peer cannot claim presence clients another peer owns. Voice is+not carried over the relay yet; the transport reports no media.+## Enrollment and administrationEnrollment is `open`, `approval`, or `closed`. In approval mode a verified identity creates adiff --git a/src/AGENTS.md b/src/AGENTS.mdindex c685d479d..6309d58aa 100644--- a/src/AGENTS.md+++ b/src/AGENTS.md@@ -25,7 +25,7 @@ Root Tauri/Vite app. Services and state live under `src/app/**`, views under `sr- `src/app/ai/tools/index.ts` binds Core ToolDefs to the active editor's `FigmaAPI`. The chat and ACP prompt compose the Core authoring reference rather than copying it (`packages/core/AGENTS.md`, Tools).- ACP transport lives under `src/app/ai/acp/**`; provider definitions in `packages/core/src/constants.ts`; profiles in `src/app/ai/models/**`. Keep provider connections, reusable profiles, and role assignments separate, and resolve credentials lazily. ACP process changes require checking `desktop/capabilities/**`.- Browser-native WebMCP registration lives under `src/app/automation/webmcp/`, consumes per-tool exposure metadata, and is feature-detected through `document.modelContext`. App completion under `src/app/automation/execution/` loads fonts after commit.-- Collaboration lives under `src/app/collab/**` on Trystero, Yjs, and awareness; preserve crypto-safe room IDs and peer cleanup.+- Collaboration lives under `src/app/collab/**` on Yjs and awareness over a `CollabRoomTransport`: Trystero for peer-to-peer rooms, the Cloud relay (`transport/cloud.ts`) for Cloud documents. Preserve crypto-safe room IDs and peer cleanup. Room channels are named in `COLLAB_ACTIONS` from `@open-pencil/cloud/contract`, because the relay reads the document ones to persist rooms and drop viewer writes (`tests/integration/collab/cloud-relay.test.ts`).- A room is a document: every room tab owns its session (`src/app/collab/rooms.ts`, `session.ts`), joining always opens a new tab, and only Share binds an existing document; the collaboration UI reads the active tab's room through `useCollab()` and publishes cursors through the canvas's own tab (`tests/app/collab/session.test.ts`, `tests/e2e/collab/rooms.spec.ts`).- A shared document records each layer's parent history, order key and page, never `parentId` or `childIds`, and only Share or a room's conversion sets its root in `meta`; local edits are written by `writeLocalPlacement` and remote changes applied by `applySharedTree` in `src/app/collab/shared-tree/sync.ts`, which resolve the tree with `LayerTree` from `src/app/collab/tree/` (`tests/app/collab/random-edits.test.ts`).- A room's voice call lives in its session (`src/app/collab/voice/room.ts`): who is in it and muted travels in awareness, the microphone goes only to peers in the call through the transport's `media`, and speaking comes from WebRTC's reported audio levels. One window holds one call, owned by `useVoiceCall()` in `src/app/collab/voice/call.ts`, which opens the microphone with VueUse and ends the call when its room goes (`tests/app/collab/voice/room.test.ts`).diff --git a/src/app/collab/room/connection.ts b/src/app/collab/room/connection.tsindex edf57ba86..3fe3bebed 100644--- a/src/app/collab/room/connection.ts+++ b/src/app/collab/room/connection.ts@@ -1,11 +1,16 @@-import { deflateSync, Inflate } from 'fflate'import * as decoding from 'lib0/decoding'import * as awarenessProtocol from 'y-protocols/awareness'import * as Y from 'yjs'+import {+ COLLAB_ACTIONS,+ encodeSyncReply,+ decodeRoomUpdate,+ MAX_COLLAB_MESSAGE_BYTES+} from '@open-pencil/cloud/contract'+import { joinCollabRoom, type JoinCollabRoom } from '@/app/collab/transport'import type { CollabAction } from '@/app/collab/transport/types'-import { MAX_COLLAB_MESSAGE_BYTES } from '@/constants'export type CollabRoomOptions = {roomId: string@@ -32,43 +37,6 @@ export type CollabRoomConnection = {type AwarenessEntry = { clientId: number; removed: boolean }-/**- * What a peer joining needs is the whole document, which repeats the same field names across- * every layer, so the reply to its state vector travels compressed; Yjs's V2 encoding already- * groups that repetition, and together they make a room's first sync about a twelfth the size.- * Edits travel as V2 updates uncompressed: they are small, and arrive in a stream.- */-function encodeSyncReply(ydoc: Y.Doc, stateVector: Uint8Array): Uint8Array {- return deflateSync(Y.encodeStateAsUpdateV2(ydoc, stateVector))-}--/**- * Compressed input is inflated this much at a time, so a reply stops within a step of passing- * the limit: deflate expands at most about 1,032 times, so a step can overshoot by about 16 MB.- */-const INFLATE_STEP = 16 * 1024--/** `data` inflated, or null once it would decode past `limit` bytes. */-function inflateWithin(data: Uint8Array, limit: number): Uint8Array | null {- const chunks: Uint8Array[] = []- let size = 0- const inflate = new Inflate((chunk) => {- size += chunk.length- if (size <= limit) chunks.push(chunk)- })- for (let offset = 0; offset < data.length; offset += INFLATE_STEP) {- inflate.push(data.subarray(offset, offset + INFLATE_STEP), offset + INFLATE_STEP >= data.length)- if (size > limit) return null- }- const inflated = new Uint8Array(size)- let at = 0- for (const chunk of chunks) {- inflated.set(chunk, at)- at += chunk.length- }- return inflated-}-/*** Applies what a peer sent, inflated first when `compressed`, as a sync reply is. An update past* `limit` is dropped with a warning; data that does not inflate or decode came from a build that@@ -81,9 +49,7 @@ function applyRemote({ limit, peerId, compressed = false }: { limit: number; peerId: string; compressed?: boolean }): boolean {try {- let update: Uint8Array | null = null- if (compressed) update = inflateWithin(data, limit)- else if (data.length <= limit) update = data+ const update = decodeRoomUpdate(data, { limit, compressed })if (!update) {console.warn(`[Collab] Dropped an update from peer ${peerId} past ${limit} bytes`)return false@@ -120,11 +86,11 @@ export function connectCollabRoom({maxMessageBytes = MAX_COLLAB_MESSAGE_BYTES}: CollabRoomOptions): CollabRoomConnection {const room = joinRoom(roomId)- const [sendYjsUpdate, getUpdate] = room.makeAction('yjs-update')- const [sendAwareness, getAwareness] = room.makeAction('awareness')- const [sendSyncStep1, getSyncStep1] = room.makeAction('sync-step1')- const [sendSyncReply, getSyncReply] = room.makeAction('sync-reply')- const agentPreview = room.makeAction('agent-preview')+ const [sendYjsUpdate, getUpdate] = room.makeAction(COLLAB_ACTIONS.yjsUpdate)+ const [sendAwareness, getAwareness] = room.makeAction(COLLAB_ACTIONS.awareness)+ const [sendSyncStep1, getSyncStep1] = room.makeAction(COLLAB_ACTIONS.syncStep1)+ const [sendSyncReply, getSyncReply] = room.makeAction(COLLAB_ACTIONS.syncReply)+ const agentPreview = room.makeAction(COLLAB_ACTIONS.agentPreview)// A transport keeps one leave handler, so the connection shares it with its users.const leaveHandlers = new Set<(peerId: string) => void>()diff --git a/src/app/collab/transport/actions.ts b/src/app/collab/transport/actions.tsnew file mode 100644index 000000000..9c3add6b9--- /dev/null+++ b/src/app/collab/transport/actions.ts@@ -0,0 +1,25 @@+import type { CollabAction, CollabActionReceiver } from './types'++/** Names room channels on a transport and delivers what arrives on each to its one receiver. */+export function createActionRegistry(+ send: (namespace: string, data: Uint8Array, peerId?: string) => void+) {+ const receivers = new Map<string, CollabActionReceiver>()+ return {+ makeAction: (namespace: string): CollabAction => [+ (data, peerId) => send(namespace, data, peerId),+ (handler) => {+ if (receivers.has(namespace)) {+ throw new Error(`Collaboration action ${namespace} is already registered`)+ }+ receivers.set(namespace, handler)+ }+ ],+ deliver(namespace: string, data: Uint8Array, peerId: string) {+ receivers.get(namespace)?.(data, peerId)+ },+ clear() {+ receivers.clear()+ }+ }+}diff --git a/src/app/collab/transport/cloud.ts b/src/app/collab/transport/cloud.tsnew file mode 100644index 000000000..e9888db96--- /dev/null+++ b/src/app/collab/transport/cloud.ts@@ -0,0 +1,201 @@+import {+ decodeRelayServerFrame,+ encodeRelayClientFrame,+ RELAY_CLOSE,+ type RelayClientFrame+} from '@open-pencil/cloud/contract'++import { createActionRegistry } from './actions'+import type { CollabRoomTransport, JoinCollabRoom } from './types'++/** The relay announces everyone in the room in its welcome, so nobody is still on the way. */+const RELAY_DISCOVERY_MS = 1000+/** How long before a ticket expires the transport presents a fresh one. */+const TICKET_REFRESH_LEAD_MS = 60_000+const MINIMUM_REFRESH_MS = 5_000+const MAXIMUM_RECONNECT_MS = 30_000++/** A collaboration ticket the relay accepts, as the Cloud API issues it. */+export type CloudRelayTicket = { token: string; expiresAt: string }++export type CloudRelayOptions = {+ /** The relay's WebSocket URL from the ticket. */+ url: string+ /** Issues a fresh ticket for the room, on connecting and before the current one expires. */+ ticket: (roomId: string) => Promise<CloudRelayTicket>+ createSocket?: (url: string) => WebSocket+ /** How long to wait before reconnection attempt `attempt`, counting from zero. */+ reconnectDelayMs?: (attempt: number) => number+ onError?: (message: string, error: unknown) => void+}++/** Close codes after which reconnecting cannot help: the ticket or the room refused this peer. */+const FINAL_CLOSE_CODES = new Set<number>([+ RELAY_CLOSE.unauthorized,+ RELAY_CLOSE.roomFull,+ RELAY_CLOSE.messageTooLarge,+ RELAY_CLOSE.protocol+])++function defaultReconnectDelay(attempt: number): number {+ return Math.min(MAXIMUM_RECONNECT_MS, 1000 * 2 ** attempt)+}++/**+ * Joins rooms through an OpenPencil Cloud relay. The relay is a peer too: it holds the room's+ * document, so a newcomer gets it without anyone else online, and it drops writes from viewers.+ */+export function createCloudRelayJoin(options: CloudRelayOptions): JoinCollabRoom {+ return (roomId) => joinCloudRelayRoom(roomId, options)+}++function joinCloudRelayRoom(roomId: string, options: CloudRelayOptions): CollabRoomTransport {+ const createSocket = options.createSocket ?? ((url: string) => new WebSocket(url))+ const reconnectDelay = options.reconnectDelayMs ?? defaultReconnectDelay+ const report =+ options.onError ?? ((message, error) => console.error(`[Collab] ${message}`, error))+ const actions = createActionRegistry((namespace, payload, target) => {+ // Before the welcome there is nobody to reach; the relay asks for missed edits on join.+ if (welcomed) send({ type: 'message', namespace, target: target ?? null, payload })+ })+ const peers = new Set<string>()+ let joinHandler: ((peerId: string) => void) | null = null+ let leaveHandler: ((peerId: string) => void) | null = null+ let socket: WebSocket | null = null+ let welcomed = false+ let left = false+ let attempt = 0+ let refreshTimer: ReturnType<typeof setTimeout> | undefined+ let ticketExpiresAt = 0+ let reconnectTimer: ReturnType<typeof setTimeout> | undefined++ function send(frame: RelayClientFrame) {+ if (socket?.readyState === WebSocket.OPEN) socket.send(encodeRelayClientFrame(frame))+ }++ async function refresh() {+ try {+ const next = await options.ticket(roomId)+ if (left) return+ send({ type: 'auth', token: next.token })+ scheduleRefresh(next)+ } catch (error) {+ report('Refreshing the collaboration ticket failed:', error)+ // Try again while the current ticket still holds, rather than wait for the relay to drop us.+ if (!left && ticketExpiresAt - Date.now() > MINIMUM_REFRESH_MS) {+ refreshTimer = setTimeout(() => void refresh(), MINIMUM_REFRESH_MS)+ }+ }+ }++ function scheduleRefresh(ticket: CloudRelayTicket) {+ clearTimeout(refreshTimer)+ ticketExpiresAt = Date.parse(ticket.expiresAt)+ const delay = Math.max(+ MINIMUM_REFRESH_MS,+ Date.parse(ticket.expiresAt) - Date.now() - TICKET_REFRESH_LEAD_MS+ )+ refreshTimer = setTimeout(() => void refresh(), delay)+ }++ function forgetPeers() {+ welcomed = false+ const departed = Array.from(peers)+ peers.clear()+ for (const peerId of departed) leaveHandler?.(peerId)+ }++ function addPeer(peerId: string) {+ if (peers.has(peerId)) return+ peers.add(peerId)+ joinHandler?.(peerId)+ }++ function handleFrame(data: ArrayBuffer) {+ const frame = decodeRelayServerFrame(new Uint8Array(data))+ if (!frame) return+ switch (frame.type) {+ case 'welcome':+ welcomed = true+ attempt = 0+ for (const peerId of frame.peers) addPeer(peerId)+ return+ case 'join':+ addPeer(frame.peerId)+ return+ case 'leave':+ if (peers.delete(frame.peerId)) leaveHandler?.(frame.peerId)+ return+ case 'message':+ actions.deliver(frame.namespace, frame.payload, frame.from)+ }+ }++ function reconnect() {+ if (left) return+ reconnectTimer = setTimeout(() => void connect(), reconnectDelay(attempt))+ attempt += 1+ }++ async function connect() {+ let ticket: CloudRelayTicket+ try {+ ticket = await options.ticket(roomId)+ } catch (error) {+ report('Requesting a collaboration ticket failed:', error)+ reconnect()+ return+ }+ if (left) return+ const next = createSocket(options.url)+ next.binaryType = 'arraybuffer'+ socket = next+ // A socket that was replaced or left behind by `leave()` no longer speaks for this room.+ next.addEventListener('open', () => {+ if (socket !== next) return+ send({ type: 'auth', token: ticket.token })+ scheduleRefresh(ticket)+ })+ next.addEventListener('message', (event: MessageEvent<ArrayBuffer>) => {+ if (socket === next) handleFrame(event.data)+ })+ next.addEventListener('close', (event) => {+ if (socket !== next) return+ socket = null+ clearTimeout(refreshTimer)+ forgetPeers()+ if (FINAL_CLOSE_CODES.has(event.code)) {+ report('The collaboration relay refused this peer:', event.reason || event.code)+ return+ }+ reconnect()+ })+ }++ void connect()++ return {+ makeAction: actions.makeAction,+ onPeerJoin(handler) {+ joinHandler = handler+ for (const peerId of peers) queueMicrotask(() => handler(peerId))+ },+ onPeerLeave(handler) {+ leaveHandler = handler+ },+ signalingConnected: () => welcomed && socket?.readyState === WebSocket.OPEN,+ discoveryMs: RELAY_DISCOVERY_MS,+ media: null,+ async leave() {+ if (left) return+ left = true+ clearTimeout(refreshTimer)+ clearTimeout(reconnectTimer)+ actions.clear()+ peers.clear()+ const current = socket+ socket = null+ current?.close(1000, 'Left the room')+ }+ }+}diff --git a/src/app/collab/transport/test.ts b/src/app/collab/transport/test.tsindex ae35d04fe..90407929b 100644--- a/src/app/collab/transport/test.ts+++ b/src/app/collab/transport/test.ts@@ -1,7 +1,8 @@import { appRuntimeConfig } from '@/app/runtime/config'import { COLLAB_APP_ID, IS_BROWSER } from '@/constants'-import type { CollabAction, CollabActionReceiver, CollabRoomTransport } from './types'+import { createActionRegistry } from './actions'+import type { CollabRoomTransport } from './types'const MAX_TEST_MESSAGE_BYTES = 8 * 1024 * 1024/** The relay introduces peers as soon as they say hello. */@@ -71,7 +72,6 @@ export function joinTestCollabRoom(roomId: string): CollabRoomTransport {const peerId = crypto.randomUUID()const socket = new WebSocket(relayURL(roomId))const peers = new Set<string>()- const receivers = new Map<string, CollabActionReceiver>()const pending: TestTransportMessage[] = []let joinHandler: ((peerId: string) => void) | null = nulllet leaveHandler: ((peerId: string) => void) | null = null@@ -82,6 +82,10 @@ export function joinTestCollabRoom(roomId: string): CollabRoomTransport {else pending.push(message)}+ const actions = createActionRegistry((namespace, data, targetId) => {+ post({ type: 'action', senderId: peerId, targetId, namespace, data: Array.from(data) })+ })+function addPeer(id: string) {if (id === peerId || peers.has(id)) returnpeers.add(id)@@ -112,30 +116,12 @@ export function joinTestCollabRoom(roomId: string): CollabRoomTransport {if (peers.delete(message.senderId)) leaveHandler?.(message.senderId)} else {addPeer(message.senderId)- receivers.get(message.namespace)?.(new Uint8Array(message.data), message.senderId)+ actions.deliver(message.namespace, new Uint8Array(message.data), message.senderId)}})return {- makeAction(namespace): CollabAction {- return [- (data, targetId) => {- post({- type: 'action',- senderId: peerId,- targetId,- namespace,- data: Array.from(data)- })- },- (handler) => {- if (receivers.has(namespace)) {- throw new Error(`Collaboration action ${namespace} is already registered`)- }- receivers.set(namespace, handler)- }- ]- },+ makeAction: actions.makeAction,onPeerJoin(handler) {joinHandler = handlerfor (const id of peers) queueMicrotask(() => handler(id))@@ -150,7 +136,7 @@ export function joinTestCollabRoom(roomId: string): CollabRoomTransport {if (left) returnleft = truepeers.clear()- receivers.clear()+ actions.clear()const leaveMessage = JSON.stringify({ type: 'leave', senderId: peerId })if (socket.readyState === WebSocket.CONNECTING) {await new Promise<void>((resolve) => {diff --git a/src/constants.ts b/src/constants.tsindex b1a5f9bbb..46ba0e45a 100644--- a/src/constants.ts+++ b/src/constants.ts@@ -70,11 +70,6 @@ import type { Color } from '@open-pencil/scene-graph/primitives'*/export const COLLAB_APP_ID = 'openpencil/5'-/**- * The most a room message may decode to, compressed or not. A peer's update past it is dropped- * before it is decoded, so a small compressed reply cannot expand without bound.- */-export const MAX_COLLAB_MESSAGE_BYTES = 256 * 1024 * 1024// 32 base36 characters provide roughly 165 bits of entropy. The room ID is a// bearer credential and must resist offline enumeration from public signaling topics.export const ROOM_ID_LENGTH = 32diff --git a/tests/app/collab/transport/cloud.test.ts b/tests/app/collab/transport/cloud.test.tsnew file mode 100644index 000000000..10a9551b9--- /dev/null+++ b/tests/app/collab/transport/cloud.test.ts@@ -0,0 +1,200 @@+import { describe, expect, jest, test } from 'bun:test'++import {+ decodeRelayClientFrame,+ encodeRelayServerFrame,+ RELAY_CLOSE,+ type RelayClientFrame,+ type RelayServerFrame+} from '@open-pencil/cloud/contract'++import { createCloudRelayJoin } from '@/app/collab/transport/cloud'++import { asDouble } from '#tests/helpers/doubles'++/** A socket the test opens, feeds, and closes by hand. */+class FakeSocket extends EventTarget {+ readyState: number = WebSocket.CONNECTING+ binaryType = 'blob'+ readonly sent: RelayClientFrame[] = []++ send(data: Uint8Array) {+ const frame = decodeRelayClientFrame(data)+ if (frame) this.sent.push(frame)+ }++ open() {+ this.readyState = WebSocket.OPEN+ this.dispatchEvent(new Event('open'))+ }++ receive(frame: RelayServerFrame) {+ const data = encodeRelayServerFrame(frame)+ this.dispatchEvent(new MessageEvent('message', { data: data.slice().buffer }))+ }++ close(code = 1000, reason = '') {+ this.readyState = WebSocket.CLOSED+ this.dispatchEvent(new CloseEvent('close', { code, reason }))+ }+}++async function settle() {+ for (let index = 0; index < 5; index++) await Promise.resolve()+}++function room(options: { failTicket?: (attempt: number) => boolean } = {}) {+ const sockets: FakeSocket[] = []+ let tickets = 0+ const errors: unknown[] = []+ const join = createCloudRelayJoin({+ url: 'wss://cloud.example.com/api/collaboration/relay',+ ticket: async () => {+ tickets += 1+ if (options.failTicket?.(tickets)) throw new Error('Ticket endpoint unavailable')+ return { token: `ticket-${tickets}`, expiresAt: new Date(Date.now() + 300_000).toISOString() }+ },+ createSocket: () => {+ const socket = new FakeSocket()+ sockets.push(socket)+ return asDouble<WebSocket>(socket)+ },+ reconnectDelayMs: () => 0,+ onError: (_message, error) => errors.push(error)+ })+ const transport = join('cloud:room:0')+ const joined: string[] = []+ const left: string[] = []+ transport.onPeerJoin((peerId) => joined.push(peerId))+ transport.onPeerLeave((peerId) => left.push(peerId))+ return { transport, sockets, joined, left, errors, tickets: () => tickets }+}++describe('Cloud relay transport', () => {+ test('presents its ticket, then reports the peers the relay announces', async () => {+ const { transport, sockets, joined } = room()+ await settle()+ const socket = sockets[0]+ if (!socket) throw new Error('Expected a socket')+ socket.open()+ expect(socket.sent).toEqual([{ type: 'auth', token: 'ticket-1' }])+ expect(transport.signalingConnected()).toBe(false)++ socket.receive({ type: 'welcome', peerId: 'me', peers: ['server', 'alice'] })+ socket.receive({ type: 'join', peerId: 'bob' })+ expect(joined).toEqual(['server', 'alice', 'bob'])+ expect(transport.signalingConnected()).toBe(true)+ await transport.leave()+ })++ test('sends only once welcomed, and delivers messages by namespace and sender', async () => {+ const { transport, sockets } = room()+ const [send, receive] = transport.makeAction('yjs-update')+ const received: [number[], string][] = []+ receive((data, peerId) => received.push([[...data], peerId]))+ await settle()+ const socket = sockets[0]+ if (!socket) throw new Error('Expected a socket')+ socket.open()+ send(new Uint8Array([1]))+ socket.receive({ type: 'welcome', peerId: 'me', peers: ['server'] })+ send(new Uint8Array([2]), 'server')+ socket.receive({+ type: 'message',+ namespace: 'yjs-update',+ from: 'alice',+ payload: new Uint8Array([3])+ })+ socket.receive({+ type: 'message',+ namespace: 'other',+ from: 'alice',+ payload: new Uint8Array([4])+ })++ expect(socket.sent.slice(1)).toEqual([+ { type: 'message', namespace: 'yjs-update', target: 'server', payload: new Uint8Array([2]) }+ ])+ expect(received).toEqual([[[3], 'alice']])+ await transport.leave()+ })++ test('reconnects with a fresh ticket after losing the relay, saying its peers left', async () => {+ const { transport, sockets, left, tickets } = room()+ await settle()+ sockets[0]?.open()+ sockets[0]?.receive({ type: 'welcome', peerId: 'me', peers: ['server', 'alice'] })+ sockets[0]?.close(1006)+ expect(left).toEqual(['server', 'alice'])+ expect(transport.signalingConnected()).toBe(false)++ await new Promise((resolve) => {+ setTimeout(resolve, 0)+ })+ await settle()+ expect(sockets).toHaveLength(2)+ sockets[1]?.open()+ expect(sockets[1]?.sent).toEqual([{ type: 'auth', token: 'ticket-2' }])+ expect(tickets()).toBe(2)+ await transport.leave()+ })++ test('stops when the relay refuses the ticket or the room', async () => {+ for (const code of [RELAY_CLOSE.unauthorized, RELAY_CLOSE.roomFull]) {+ const { sockets, errors } = room()+ await settle()+ sockets[0]?.open()+ sockets[0]?.close(code, 'refused')+ await new Promise((resolve) => {+ setTimeout(resolve, 0)+ })+ await settle()+ expect(sockets).toHaveLength(1)+ expect(errors).toEqual(['refused'])+ }+ })++ test('leaving closes the socket and never reconnects', async () => {+ const { transport, sockets } = room()+ await settle()+ sockets[0]?.open()+ await transport.leave()+ expect(sockets[0]?.readyState).toBe(WebSocket.CLOSED)+ await new Promise((resolve) => {+ setTimeout(resolve, 0)+ })+ expect(sockets).toHaveLength(1)+ })++ test('retries a failed ticket refresh while the current ticket still holds', async () => {+ jest.useFakeTimers()+ try {+ const { transport, sockets, errors } = room({ failTicket: (attempt) => attempt === 2 })+ await settle()+ sockets[0]?.open()+ // The first refresh comes a minute before the five-minute ticket expires, and fails.+ jest.advanceTimersByTime(240_000)+ await settle()+ expect(errors).toHaveLength(1)+ jest.advanceTimersByTime(5_000)+ await settle()+ const auths = sockets[0]?.sent.filter((frame) => frame.type === 'auth')+ expect(auths?.map((frame) => (frame.type === 'auth' ? frame.token : ''))).toEqual([+ 'ticket-1',+ 'ticket-3'+ ])+ await transport.leave()+ } finally {+ jest.useRealTimers()+ }+ })++ test('ignores frames from a socket it left', async () => {+ const { transport, sockets, joined } = room()+ await settle()+ const socket = sockets[0]+ await transport.leave()+ socket?.receive({ type: 'welcome', peerId: 'me', peers: ['server', 'ada'] })+ expect(joined).toEqual([])+ })+})diff --git a/tests/integration/collab/cloud-relay.test.ts b/tests/integration/collab/cloud-relay.test.tsnew file mode 100644index 000000000..3af326e0a--- /dev/null+++ b/tests/integration/collab/cloud-relay.test.ts@@ -0,0 +1,160 @@+import { afterEach, describe, expect, test } from 'bun:test'+import { createServer } from 'node:http'++import * as awarenessProtocol from 'y-protocols/awareness'+import * as Y from 'yjs'++import { RELAY_PATH, type DocumentPermission } from '@open-pencil/cloud/contract'+import { attachCollaborationRelay } from '@open-pencil/cloud/runtime/node'+import {+ createCollaborationRelay,+ signCollaborationTicket,+ type CollaborationStateStore+} from '@open-pencil/cloud/server'++import { connectCollabRoom } from '@/app/collab/room/connection'+import { createCloudRelayJoin } from '@/app/collab/transport/cloud'++const authSecret = 'relay-integration-secret-at-least-32-characters'+const documentId = crypto.randomUUID()+const roomId = `cloud:${documentId}:0`++const cleanups: (() => Promise<void> | void)[] = []++afterEach(async () => {+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup()+})++async function until(condition: () => boolean, attempts = 500): Promise<void> {+ for (let attempt = 0; attempt < attempts; attempt++) {+ if (condition()) return+ await new Promise((resolve) => {+ setTimeout(resolve, 2)+ })+ }+ throw new Error('Condition was not met')+}++async function startRelay() {+ const states = new Map<string, Uint8Array>()+ const store: CollaborationStateStore = {+ load: async (room) => states.get(`${room.documentId}:${room.roomEpoch}`) ?? null,+ store: async (room, state) => {+ states.set(`${room.documentId}:${room.roomEpoch}`, state)+ }+ }+ const relay = createCollaborationRelay({+ authSecret,+ store,+ maximumMessageBytes: 1_048_576,+ maximumConnectionsPerRoom: 10,+ persistDelayMs: 0+ })+ const server = createServer()+ const attached = attachCollaborationRelay(server, relay, 1_048_576)+ await new Promise<void>((resolve) => {+ server.listen(0, '127.0.0.1', resolve)+ })+ const address = server.address()+ if (!address || typeof address === 'string') throw new Error('Expected a TCP address')+ cleanups.push(async () => {+ await attached.close()+ await new Promise<void>((resolve) => {+ server.close(() => resolve())+ })+ })+ return { url: `ws://127.0.0.1:${address.port}${RELAY_PATH}`, states }+}++function joinAs(url: string, name: string, permission: DocumentPermission) {+ const ydoc = new Y.Doc()+ const awareness = new awarenessProtocol.Awareness(ydoc)+ const join = createCloudRelayJoin({+ url,+ ticket: async () =>+ signCollaborationTicket({+ authSecret,+ documentId,+ principal: { kind: 'guest', guestId: crypto.randomUUID(), name },+ permission,+ roomEpoch: 0,+ relayURL: url+ })+ })+ const connection = connectCollabRoom({+ roomId,+ ydoc,+ awareness,+ updatePeersList: () => undefined,+ joinRoom: join+ })+ const peer = {+ ydoc,+ awareness,+ connection,+ text: () => ydoc.getText('t').toString(),+ async leave() {+ await connection.room.leave()+ awareness.destroy()+ ydoc.destroy()+ }+ }+ cleanups.push(() => peer.leave())+ return peer+}++describe('collaboration through the Cloud relay', () => {+ test('editors sync live and newcomers get the document from the relay', async () => {+ const { url } = await startRelay()+ const alice = joinAs(url, 'Alice', 'edit')+ await until(() => alice.connection.room.signalingConnected())+ alice.ydoc.getText('t').insert(0, 'hello')++ const bob = joinAs(url, 'Bob', 'edit')+ await until(() => bob.text() === 'hello')+ bob.ydoc.getText('t').insert(5, ' world')+ await until(() => alice.text() === 'hello world')++ await alice.leave()+ await bob.leave()+ const carol = joinAs(url, 'Carol', 'view')+ await until(() => carol.text() === 'hello world')+ })++ test('viewers receive edits but their own never reach anyone', async () => {+ const { url, states } = await startRelay()+ const editor = joinAs(url, 'Editor', 'edit')+ const viewer = joinAs(url, 'Viewer', 'view')+ await until(+ () =>+ editor.connection.room.signalingConnected() && viewer.connection.room.signalingConnected()+ )+ viewer.ydoc.getText('t').insert(0, 'vandal ')+ editor.ydoc.getText('t').insert(0, 'kept')+ await until(() => viewer.text().includes('kept'))++ expect(editor.text()).toBe('kept')+ await editor.leave()+ await viewer.leave()+ await until(() => states.size > 0)+ const saved = new Y.Doc()+ Y.applyUpdate(saved, [...states.values()][0] ?? new Uint8Array())+ expect(saved.getText('t').toString()).toBe('kept')+ })++ test('presence carries the name on the ticket, not the one a peer claims', async () => {+ const { url } = await startRelay()+ const editor = joinAs(url, 'Editor', 'edit')+ const guest = joinAs(url, 'Grace', 'view')+ await until(+ () =>+ editor.connection.room.signalingConnected() && guest.connection.room.signalingConnected()+ )+ guest.awareness.setLocalStateField('user', { name: 'Admin', color: '#000' })+ await until(() => editor.awareness.getStates().has(guest.awareness.clientID))+ expect(editor.awareness.getStates().get(guest.awareness.clientID)).toMatchObject({+ user: { name: 'Grace', color: '#000' },+ cloud: { kind: 'guest', name: 'Grace', permission: 'view' }+ })+ })+})diff --git a/tools/checks/architecture/file-prefix-baseline.txt b/tools/checks/architecture/file-prefix-baseline.txtnew file mode 100644index 000000000..9355b8707--- /dev/null+++ b/tools/checks/architecture/file-prefix-baseline.txt@@ -0,0 +1,31 @@+# Folders that group files by a filename prefix next to a file of that name, from before+# check:arch caught it. Move a group into its own folder, then delete its line here.+packages/core/src/editor/history::snapshot+packages/core/src/editor/structure::group+packages/core/src/io/formats/design-tokens::plan+packages/core/src/kiwi/fig/session::archive+packages/core/src/tools::registry+packages/core/tests/canvas/text::derived+packages/core/tests/editor/graph::events+packages/dom-css/src/runtime::headless+packages/vue/src/shared/input::move+packages/vue/src/shared/input::pan+src/app/diagnostics/events::storage+src/app/diagnostics/events::transport+src/app/document/io::save+src/app/document/io::source+src/app/document/io::watch+src/app/editor/clipboard::paste+src/theme/collaboration::avatar+src/theme/input::input+src/theme/panel::field+tests/app/libraries::update+tests/e2e/canvas/shape-handles::handles+tests/e2e/properties::panel+tests/e2e/settings::mcp+tests/engine/app/ai::model+tests/engine/figma/api::grouping+tests/engine/mcp::webmcp+tests/engine/render/canvas/visual::boolean+tests/engine/render/canvas::text+tests/helpers/collab::agentdiff --git a/tools/checks/architecture/src/steiger-rules/index.ts b/tools/checks/architecture/src/steiger-rules/index.tsindex fa8a7b2b6..e2779f230 100644--- a/tools/checks/architecture/src/steiger-rules/index.ts+++ b/tools/checks/architecture/src/steiger-rules/index.ts@@ -16,7 +16,10 @@ import {createImportRule,createTextRule,filePrefix,+ FILE_PREFIX_BASELINE_PATH,FILE_PREFIX_GROUP_ALLOWLIST,+ fileStem,+ readFilePrefixBaseline,PACKAGE_ALIASES,PACKAGE_ALIAS_OWNERS,relativePath,@@ -30,11 +33,15 @@ const preferDomainFoldersOverFilenamePrefixes: Rule = {name: 'open-pencil/prefer-domain-folders-over-filename-prefixes',check(root) {const diagnostics: Diagnostic[] = []+ const baseline = readFilePrefixBaseline(root.path)+ const seen = new Set<string>()for (const folder of collectFolders(root)) {const folderRel = relativePath(root.path, folder.path)const groups = new Map<string, string[]>()+ const names = new Set<string>()for (const child of folder.children ?? []) {if (child.type !== 'file' || !TEXT_EXTENSIONS.has(path.extname(child.path))) continue+ names.add(fileStem(child.path))const prefix = filePrefix(child.path)if (!prefix) continueconst files = groups.get(prefix) ?? []@@ -42,14 +49,27 @@ const preferDomainFoldersOverFilenamePrefixes: Rule = {groups.set(prefix, files)}for (const [prefix, files] of groups) {- if (files.length < 3) continue- if (FILE_PREFIX_GROUP_ALLOWLIST.has(`${folderRel}::${prefix}`)) continue+ // `email.ts` beside `email-runtime.ts` is a domain as much as three `email-*` files are.+ if (files.length < 3 && !names.has(prefix)) continue+ const entry = `${folderRel}::${prefix}`+ if (FILE_PREFIX_GROUP_ALLOWLIST.has(entry)) continue+ if (baseline.has(entry)) {+ seen.add(entry)+ continue+ }diagnostics.push({- message: `Use a ${prefix}/ domain folder instead of ${files.length} sibling files with the ${prefix}- filename prefix.`,+ message: `Use a ${prefix}/ domain folder instead of sibling files named ${prefix} and ${prefix}-*.`,location: { path: folder.path }})}}+ for (const entry of baseline) {+ if (seen.has(entry)) continue+ diagnostics.push({+ message: `${entry} no longer groups files by prefix; remove it from ${FILE_PREFIX_BASELINE_PATH}.`,+ location: { path: path.join(root.path, FILE_PREFIX_BASELINE_PATH) }+ })+ }return { diagnostics }}}diff --git a/tools/checks/architecture/src/steiger-rules/support.ts b/tools/checks/architecture/src/steiger-rules/support.tsindex a021638c2..0a2d10c7f 100644--- a/tools/checks/architecture/src/steiger-rules/support.ts+++ b/tools/checks/architecture/src/steiger-rules/support.ts@@ -194,8 +194,28 @@ export function createImportRule(}}+/** A file's name without its test kind and extension: `email-runtime.test.ts` is `email-runtime`. */+export function fileStem(filePath: string): string {+ return path.basename(filePath).replace(/\.(test|spec|bench)?\.?[cm]?[tj]sx?$|\.vue$/, '')+}+export function filePrefix(filePath: string): string | null {- const name = path.basename(filePath).replace(/\.(test|spec|bench)?\.?[cm]?[tj]sx?$|\.vue$/, '')- const match = /^([a-z][a-z0-9]+)-[a-z0-9-]+$/.exec(name)+ const match = /^([a-z][a-z0-9]+)-[a-z0-9-]+$/.exec(fileStem(filePath))return match?.[1] ?? null}++/**+ * Prefix groups that existed before the rule counted a bare `prefix` file, as `folder::prefix`.+ * The list only shrinks: moving a group into its folder means deleting its line.+ */+export const FILE_PREFIX_BASELINE_PATH = 'tools/checks/architecture/file-prefix-baseline.txt'++export function readFilePrefixBaseline(rootPath: string): Set<string> {+ const text = readFileSync(path.join(rootPath, FILE_PREFIX_BASELINE_PATH), 'utf8')+ return new Set(+ text+ .split('\n')+ .map((line) => line.trim())+ .filter((line) => line && !line.startsWith('#'))+ )+}diff --git a/tools/checks/architecture/tests/file-prefixes.test.ts b/tools/checks/architecture/tests/file-prefixes.test.tsnew file mode 100644index 000000000..f18b42965--- /dev/null+++ b/tools/checks/architecture/tests/file-prefixes.test.ts@@ -0,0 +1,45 @@+import { expect, test } from 'bun:test'+import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { openPencilArchitecturePlugin } from '../src/steiger-rules/index'+import { FILE_PREFIX_BASELINE_PATH } from '../src/steiger-rules/support'++const rule = openPencilArchitecturePlugin.ruleDefinitions.find(+ (candidate) => candidate.name === 'open-pencil/prefer-domain-folders-over-filename-prefixes'+)++async function check(files: string[], baseline: string[] = []) {+ if (!rule) throw new Error('Missing file prefix rule')+ const root = await mkdtemp(join(tmpdir(), 'open-pencil-file-prefixes-'))+ await mkdir(join(root, 'tools/checks/architecture'), { recursive: true })+ await writeFile(join(root, FILE_PREFIX_BASELINE_PATH), baseline.join('\n'))+ const folder = join(root, 'src/runtime')+ return rule.check({+ type: 'folder',+ path: root,+ children: [+ {+ type: 'folder',+ path: folder,+ children: files.map((file) => ({ type: 'file' as const, path: join(folder, file) }))+ }+ ]+ }).diagnostics.length+}++test('asks for a folder when a file sits beside files named after it', async () => {+ expect(await check(['email.ts', 'email-runtime.ts'])).toBe(1)+ expect(await check(['auth-failure.ts', 'auth-navigation.ts', 'auth-session.ts'])).toBe(1)+})++test('accepts names that only share a word', async () => {+ expect(await check(['sign-in.ts', 'sign-out.ts'])).toBe(0)+ expect(await check(['email.ts', 'server.ts'])).toBe(0)+})++test('keeps grandfathered groups until they move, then asks to drop their line', async () => {+ expect(await check(['email.ts', 'email-runtime.ts'], ['src/runtime::email'])).toBe(0)+ expect(await check(['server.ts'], ['src/runtime::email'])).toBe(1)+})diff --git a/vite/aliases.ts b/vite/aliases.tsindex eef6507d3..f40ff0cfa 100644--- a/vite/aliases.ts+++ b/vite/aliases.ts@@ -48,6 +48,11 @@ export function createOpenPencilAliases(rootDir: string) {replacement: resolve(rootDir, 'packages/scene-graph/src/text/picture.ts')},{ find: '@open-pencil/scene-graph', replacement: resolve(rootDir, 'packages/scene-graph/src') },+ { find: '#cloud', replacement: resolve(rootDir, 'packages/cloud/src') },+ {+ find: /^@open-pencil\/cloud\/(contract|client)$/,+ replacement: resolve(rootDir, 'packages/cloud/src/$1/index.ts')+ },{ find: '#emit', replacement: resolve(rootDir, 'packages/emit/src') },{find: /^@open-pencil\/emit$/,