Skip to content

AI-native design editor. Open-source Figma alternative.

feat(cloud): run Cloud on Cloudflare Workers with a relay per document (#1370)

Danila Poyarkovc0eee7f48695
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 51bb8e546..e8fe8332f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -325,6 +325,11 @@ jobs:
# Garage's S3 compatibility for the object-store checks.
- store: Garage
script: test:e2e:garage
+ # The Cloudflare Worker under wrangler dev, with its relay Durable Object, against
+ # PostgreSQL and SeaweedFS.
+ - store: Cloudflare Workers
+ script: test:e2e:cloudflare
+ worker: true
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
@@ -335,6 +340,15 @@ jobs:
- name: Generate package declarations
run: bun run build:packages
+ # The Worker serves the portal as static assets, and every official deployment bundles it.
+ - name: Build the Cloud portal and bundle the official Workers
+ if: matrix.worker
+ run: |
+ bun run build:cloud-portal
+ for deployment in packages/cloud/deploy/openpencil/*/; do
+ (cd "$deployment" && bunx wrangler deploy --dry-run)
+ done
+
- name: Run Cloud end-to-end tests against ${{ matrix.store }}
env:
CLOUD_E2E_SCRIPT: ${{ matrix.script }}
diff --git a/.github/workflows/cloud.yml b/.github/workflows/cloud.yml
new file mode 100644
index 000000000..600616752
--- /dev/null
+++ b/.github/workflows/cloud.yml
@@ -0,0 +1,86 @@
+name: Deploy Cloud
+
+# Deploys an official OpenPencil Cloud deployment: packages/cloud/deploy/openpencil/<target>, with
+# the secrets and reviewers of the cloud-<target> GitHub environment.
+on:
+ workflow_dispatch:
+ inputs:
+ target:
+ description: Deployment
+ type: choice
+ options: [staging]
+
+concurrency:
+ group: cloud-${{ inputs.target }}
+ cancel-in-progress: false
+
+jobs:
+ deploy:
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ environment:
+ name: cloud-${{ inputs.target }}
+ url: ${{ vars.CLOUD_URL }}
+ permissions:
+ contents: read
+ deployments: write
+ env:
+ DEPLOYMENT: packages/cloud/deploy/openpencil/${{ inputs.target }}
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ persist-credentials: false
+
+ - uses: ./.github/actions/setup-bun
+
+ # The Worker serves the portal as static assets.
+ - name: Build the Cloud portal
+ run: bun run build:packages && bun run build:cloud-portal
+
+ # Migrations run before the new code, over the direct connection rather than Hyperdrive. The
+ # config reads every secret it names, so only this step and the next one see them.
+ - name: Migrate the database
+ env:
+ OPENPENCIL_CLOUD_CONFIG: ${{ github.workspace }}/${{ env.DEPLOYMENT }}/openpencil-cloud.toml
+ DATABASE_URL: ${{ secrets.NEON_MIGRATOR_DATABASE_URL }}
+ BETTER_AUTH_SECRET: ${{ secrets.BETTER_AUTH_SECRET }}
+ GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }}
+ GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }}
+ S3_ACCESS_KEY_ID: ${{ secrets.S3_ACCESS_KEY_ID }}
+ S3_SECRET_ACCESS_KEY: ${{ secrets.S3_SECRET_ACCESS_KEY }}
+ run: bun --filter @open-pencil/cloud migrate
+
+ - name: Collect the Worker's secrets
+ env:
+ BETTER_AUTH_SECRET: ${{ secrets.BETTER_AUTH_SECRET }}
+ GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }}
+ GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }}
+ S3_ACCESS_KEY_ID: ${{ secrets.S3_ACCESS_KEY_ID }}
+ S3_SECRET_ACCESS_KEY: ${{ secrets.S3_SECRET_ACCESS_KEY }}
+ run: |
+ umask 077
+ jq -n '{BETTER_AUTH_SECRET: env.BETTER_AUTH_SECRET, GOOGLE_CLIENT_ID: env.GOOGLE_CLIENT_ID,
+ GOOGLE_CLIENT_SECRET: env.GOOGLE_CLIENT_SECRET, S3_ACCESS_KEY_ID: env.S3_ACCESS_KEY_ID,
+ S3_SECRET_ACCESS_KEY: env.S3_SECRET_ACCESS_KEY}' > "$RUNNER_TEMP/cloud-secrets.json"
+
+ - uses: cloudflare/wrangler-action@v4
+ with:
+ apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+ accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
+ workingDirectory: ${{ env.DEPLOYMENT }}
+ packageManager: bun
+ command: deploy --secrets-file ${{ runner.temp }}/cloud-secrets.json
+
+ - name: Check the deployment
+ env:
+ CLOUD_URL: ${{ vars.CLOUD_URL }}
+ # Only a 200 counts: a redirect to a sign-in or access page would mean the Worker isn't there.
+ run: |
+ for path in /health /ready /.well-known/openpencil /auth/sign-in; do
+ status=$(curl --silent --show-error --retry 10 --retry-all-errors --retry-delay 3 \
+ --output /dev/null --write-out '%{http_code}' "$CLOUD_URL$path")
+ if [ "$status" != 200 ]; then
+ echo "::error::$path answered HTTP $status"
+ exit 1
+ fi
+ done
diff --git a/bun.lock b/bun.lock
index 9c29beb71..1969d0687 100644
--- a/bun.lock
+++ b/bun.lock
@@ -235,6 +235,7 @@
"yjs": "^13.6.32",
},
"devDependencies": {
+ "@cloudflare/workers-types": "^5.20261011.1",
"@electric-sql/pglite": "0.4.1",
"@types/bun": "^1.3.14",
"@types/nodemailer": "^8.0.1",
@@ -243,6 +244,7 @@
"kysely-pglite-dialect": "1.3.1",
"tsdown": "^0.22.14",
"typescript": "~5.8.3",
+ "wrangler": "4.149.0",
"y-protocols": "^1.0.7",
},
"optionalDependencies": {
diff --git a/packages/cloud/deploy/README.md b/packages/cloud/deploy/README.md
index d543092b5..6238b469d 100644
--- a/packages/cloud/deploy/README.md
+++ b/packages/cloud/deploy/README.md
@@ -1,7 +1,9 @@
# Deploying OpenPencil Cloud
OpenPencil Cloud runs as one Node 22+ process in front of PostgreSQL and an S3-compatible object
-store, with optional SMTP for email. See [security.md](./security.md) for hardening checks.
+store, with optional SMTP for email, or on Cloudflare Workers by copying [`cloudflare/`](./cloudflare). The project's own deployments
+live in [`openpencil/`](./openpencil). See
+[security.md](./security.md) for hardening checks.
## Local development
@@ -37,8 +39,11 @@ commands, email, storage, backups, and upgrades are covered in the
```sh
bun --filter @open-pencil/cloud test:e2e # PostgreSQL and SeaweedFS
bun --filter @open-pencil/cloud test:e2e:garage # Garage S3 compatibility
+bun --filter @open-pencil/cloud test:e2e:cloudflare # the Worker under wrangler dev
```
+The Cloudflare run needs `dist-cloud-portal/` (`bun run build:cloud-portal`), which the Worker serves.
+
Each runner starts an isolated Compose project and removes it with its volumes afterwards. The main
suite checks object-store readiness, a presigned single PUT and a 33 MiB three-part multipart upload
(ordered ETags, metadata SHA-256, size, verified GET, deletion), then the full revision flow against
diff --git a/packages/cloud/deploy/cloudflare/config.d.ts b/packages/cloud/deploy/cloudflare/config.d.ts
new file mode 100644
index 000000000..e891f753c
--- /dev/null
+++ b/packages/cloud/deploy/cloudflare/config.d.ts
@@ -0,0 +1,5 @@
+// Wrangler bundles a deployment's TOML as text (`rules` in its wrangler.jsonc).
+declare module '*.toml' {
+ const source: string
+ export default source
+}
diff --git a/packages/cloud/deploy/cloudflare/worker.ts b/packages/cloud/deploy/cloudflare/worker.ts
new file mode 100644
index 000000000..887197655
--- /dev/null
+++ b/packages/cloud/deploy/cloudflare/worker.ts
@@ -0,0 +1,8 @@
+import { createCloudflareCloud } from '#cloud/runtime/cloudflare'
+
+import config from './openpencil-cloud.toml'
+
+const cloud = createCloudflareCloud(config)
+
+export default cloud.worker
+export const CollaborationRelayObject = cloud.CollaborationRelayObject
diff --git a/packages/cloud/deploy/cloudflare/wrangler.jsonc b/packages/cloud/deploy/cloudflare/wrangler.jsonc
new file mode 100644
index 000000000..95698c265
--- /dev/null
+++ b/packages/cloud/deploy/cloudflare/wrangler.jsonc
@@ -0,0 +1,39 @@
+// OpenPencil Cloud on Cloudflare Workers. To deploy, copy this folder next to it (for example to
+// deploy/mine), add your deployment TOML as openpencil-cloud.toml, replace the values marked below,
+// and run `wrangler deploy` there. The self-hosting guide walks through it.
+{
+ "$schema": "../../node_modules/wrangler/config-schema.json",
+ "name": "openpencil-cloud",
+ "main": "worker.ts",
+ "compatibility_date": "2026-10-01",
+ "compatibility_flags": ["nodejs_compat"],
+ "tsconfig": "../../src/runtime/cloudflare/tsconfig.json",
+ // The deployment TOML is bundled as text and parsed when the Worker starts.
+ "rules": [{ "type": "Text", "globs": ["**/*.toml"], "fallthrough": false }],
+ "observability": { "enabled": true },
+ // The Cloud portal from `bun run build:cloud-portal` at the repository root. The Worker always
+ // answers first: API routes win, portal pages get `cloud.html`, and only then files.
+ "assets": {
+ "directory": "../../../../dist-cloud-portal",
+ "binding": "ASSETS",
+ "html_handling": "none",
+ "run_worker_first": true
+ },
+ // Replace with your domain.
+ "routes": [{ "pattern": "cloud.example.com", "custom_domain": true }],
+ "workers_dev": false,
+ // Replace with the ID from `wrangler hyperdrive create`. Locally the connection string comes from
+ // CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE instead.
+ "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "your-hyperdrive-id" }],
+ // One object per document holds its live collaboration rooms.
+ "durable_objects": {
+ "bindings": [{ "name": "RELAY", "class_name": "CollaborationRelayObject" }]
+ },
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["CollaborationRelayObject"] }],
+ // Used by `[email] transport = "cloudflare"`.
+ "send_email": [{ "name": "EMAIL" }],
+ // Cleanup, and email that failed to send after its request.
+ "triggers": { "crons": ["*/5 * * * *"] },
+ // Add the other secrets your TOML names, such as GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET.
+ "secrets": { "required": ["BETTER_AUTH_SECRET", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY"] }
+}
diff --git a/packages/cloud/deploy/openpencil/staging/openpencil-cloud.toml b/packages/cloud/deploy/openpencil/staging/openpencil-cloud.toml
new file mode 100644
index 000000000..18fe23892
--- /dev/null
+++ b/packages/cloud/deploy/openpencil/staging/openpencil-cloud.toml
@@ -0,0 +1,81 @@
+# cloud-staging.openpencil.dev, the official staging deployment. Secrets come from the Worker's
+# secrets: BETTER_AUTH_SECRET, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, S3_ACCESS_KEY_ID, and
+# S3_SECRET_ACCESS_KEY; DATABASE_URL is Hyperdrive's.
+schema_version = 2
+
+[deployment]
+mode = "official"
+public_url = "https://cloud-staging.openpencil.dev"
+app_url = "https://app.openpencil.dev"
+indexing = "deny"
+trusted_origins = ["https://app.openpencil.dev", "https://cloud-staging.openpencil.dev"]
+
+[database]
+
+[authentication]
+enrollment_mode = "approval"
+admin_notification_emails = ["[email protected]"]
+
+[authentication.mfa]
+deployment_admin_required = false
+totp_enabled = false
+passkeys_enabled = false
+recovery_codes_enabled = false
+trusted_device_days = 14
+
+[authentication.email_password]
+enabled = false
+
+[authentication.trusted_proxies]
+headers = ["cf-connecting-ip"]
+addresses = []
+
+[authentication.providers.google]
+client_id = { from_env = "GOOGLE_CLIENT_ID" }
+
+[object_storage]
+endpoint = "https://br-lucky-forest-aeigmjr4.storage.c-2.us-east-2.aws.neon.tech"
+region = "us-east-2"
+bucket = "openpencil-cloud-staging"
+force_path_style = true
+checksum_verification = "metadata"
+
+[email]
+transport = "cloudflare"
+
+[workers.email]
+batch_size = 50
+interval_ms = 30000
+lease_ms = 300000
+maximum_attempts = 5
+
+[workers.cleanup]
+enabled = true
+batch_size = 100
+interval_ms = 60000
+lease_ms = 300000
+document_retention_days = 30
+
+[entitlements]
+source = "static"
+
+[entitlements.documents]
+maximum_file_bytes = 1_073_741_824
+revision_history = true
+
+[entitlements.storage]
+maximum_bytes = 107_374_182_400
+
+[entitlements.sharing]
+capability_links = true
+anonymous_view = true
+anonymous_edit = true
+guest_presence = true
+
+[entitlements.collaboration]
+enabled = true
+maximum_participants = 100
+
+[entitlements.ai]
+enabled = false
diff --git a/packages/cloud/deploy/openpencil/staging/worker.ts b/packages/cloud/deploy/openpencil/staging/worker.ts
new file mode 100644
index 000000000..887197655
--- /dev/null
+++ b/packages/cloud/deploy/openpencil/staging/worker.ts
@@ -0,0 +1,8 @@
+import { createCloudflareCloud } from '#cloud/runtime/cloudflare'
+
+import config from './openpencil-cloud.toml'
+
+const cloud = createCloudflareCloud(config)
+
+export default cloud.worker
+export const CollaborationRelayObject = cloud.CollaborationRelayObject
diff --git a/packages/cloud/deploy/openpencil/staging/wrangler.jsonc b/packages/cloud/deploy/openpencil/staging/wrangler.jsonc
new file mode 100644
index 000000000..4da9951ab
--- /dev/null
+++ b/packages/cloud/deploy/openpencil/staging/wrangler.jsonc
@@ -0,0 +1,36 @@
+// cloud-staging.openpencil.dev, deployed by the Deploy Cloud workflow with target `staging`: a
+// filled-in copy of ../../cloudflare. For a deployment of your own, copy that folder instead.
+{
+ "$schema": "../../../node_modules/wrangler/config-schema.json",
+ "name": "openpencil-cloud-staging",
+ "main": "worker.ts",
+ "compatibility_date": "2026-10-01",
+ "compatibility_flags": ["nodejs_compat"],
+ "tsconfig": "../../../src/runtime/cloudflare/tsconfig.json",
+ "rules": [{ "type": "Text", "globs": ["**/*.toml"], "fallthrough": false }],
+ "observability": { "enabled": true },
+ "assets": {
+ "directory": "../../../../../dist-cloud-portal",
+ "binding": "ASSETS",
+ "html_handling": "none",
+ "run_worker_first": true
+ },
+ "routes": [{ "pattern": "cloud-staging.openpencil.dev", "custom_domain": true }],
+ "workers_dev": false,
+ "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "4e4c4652a8a14c77bfdb2d50862d2e64" }],
+ "durable_objects": {
+ "bindings": [{ "name": "RELAY", "class_name": "CollaborationRelayObject" }]
+ },
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["CollaborationRelayObject"] }],
+ "send_email": [{ "name": "EMAIL" }],
+ "triggers": { "crons": ["*/5 * * * *"] },
+ "secrets": {
+ "required": [
+ "BETTER_AUTH_SECRET",
+ "GOOGLE_CLIENT_ID",
+ "GOOGLE_CLIENT_SECRET",
+ "S3_ACCESS_KEY_ID",
+ "S3_SECRET_ACCESS_KEY"
+ ]
+ }
+}
diff --git a/packages/cloud/package.json b/packages/cloud/package.json
index 3855743c0..d5933bbad 100644
--- a/packages/cloud/package.json
+++ b/packages/cloud/package.json
@@ -61,12 +61,13 @@
"test:integration": "bun test --max-concurrency 8 tests/integration",
"test:e2e": "bun tests/e2e/run.ts",
"test:e2e:garage": "bun tests/e2e/garage.ts",
+ "test:e2e:cloudflare": "bun tests/e2e/cloudflare/run.ts",
"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/main.ts",
"admin": "bun src/runtime/node/admin.ts",
- "typecheck": "bunx tsc --noEmit -p tsconfig.json"
+ "typecheck": "bunx tsc --noEmit -p tsconfig.json && bunx tsc -p src/runtime/cloudflare/tsconfig.json"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.1149.0",
@@ -100,6 +101,7 @@
"pg": "^8.23.0"
},
"devDependencies": {
+ "@cloudflare/workers-types": "^5.20261011.1",
"@electric-sql/pglite": "0.4.1",
"@types/bun": "^1.3.14",
"@types/nodemailer": "^8.0.1",
@@ -108,6 +110,7 @@
"kysely-pglite-dialect": "1.3.1",
"tsdown": "^0.22.14",
"typescript": "~5.8.3",
+ "wrangler": "4.149.0",
"y-protocols": "^1.0.7"
}
}
diff --git a/packages/cloud/src/contract/relay.ts b/packages/cloud/src/contract/relay.ts
index ea3ca1d8e..72d638a5a 100644
--- a/packages/cloud/src/contract/relay.ts
+++ b/packages/cloud/src/contract/relay.ts
@@ -6,6 +6,19 @@ import * as Y from 'yjs'
/** Where the relay accepts WebSocket upgrades, under the Cloud API origin. */
export const RELAY_PATH = '/api/collaboration/relay'
+/**
+ * The relay URL's query parameter naming the ticket's document, so a runtime that keeps each
+ * document's room in its own place can route the socket there before the ticket arrives.
+ */
+export const RELAY_DOCUMENT_PARAM = 'document'
+
+/** 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
+}
+
/**
* 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.
diff --git a/packages/cloud/src/runtime/cloudflare/email.ts b/packages/cloud/src/runtime/cloudflare/email.ts
new file mode 100644
index 000000000..e7fa896e7
--- /dev/null
+++ b/packages/cloud/src/runtime/cloudflare/email.ts
@@ -0,0 +1,70 @@
+import {
+ TransactionalEmailTransportError,
+ type TransactionalEmailEnvelope,
+ type TransactionalEmailTransport,
+ type TransactionalEmailTransportErrorKind
+} from '#cloud/server/email'
+
+/** The part of a Worker's `send_email` binding the transport uses. */
+export type CloudflareEmailBinding = {
+ send(message: {
+ to: string
+ from: string
+ subject: string
+ html: string
+ text: string
+ headers?: Record<string, string>
+ }): Promise<{ messageId: string }>
+}
+
+/** Cloudflare Email Service error codes, by what retrying them would do. */
+const ERROR_KINDS: Record<string, TransactionalEmailTransportErrorKind> = {
+ E_SENDER_NOT_VERIFIED: 'configuration',
+ E_RECIPIENT_NOT_ALLOWED: 'configuration',
+ E_SENDER_DOMAIN_NOT_AVAILABLE: 'configuration',
+ E_RECIPIENT_SUPPRESSED: 'suppressed',
+ E_VALIDATION_ERROR: 'permanent',
+ E_FIELD_MISSING: 'permanent',
+ E_TOO_MANY_RECIPIENTS: 'permanent',
+ E_TOO_MANY_ATTACHMENTS: 'permanent',
+ E_CONTENT_TOO_LARGE: 'permanent',
+ E_DELIVERY_FAILED: 'permanent',
+ E_RATE_LIMIT_EXCEEDED: 'rate-limited',
+ E_DAILY_LIMIT_EXCEEDED: 'rate-limited'
+}
+
+function errorCode(error: unknown): string {
+ return error instanceof Error && 'code' in error && typeof error.code === 'string'
+ ? error.code
+ : 'E_UNKNOWN'
+}
+
+/** Sends transactional email through a Worker's `send_email` binding. */
+export function createCloudflareEmailTransport(
+ binding: CloudflareEmailBinding
+): TransactionalEmailTransport {
+ return {
+ id: 'cloudflare-email-service',
+ async send(message: TransactionalEmailEnvelope) {
+ try {
+ const result = await binding.send({
+ to: message.to,
+ from: message.from,
+ subject: message.subject,
+ html: message.html,
+ text: message.text,
+ headers: message.headers
+ })
+ return { transportMessageId: result.messageId, acceptedAt: new Date().toISOString() }
+ } catch (error) {
+ const code = errorCode(error)
+ throw new TransactionalEmailTransportError(
+ ERROR_KINDS[code] ?? 'transient',
+ code,
+ 'Cloudflare Email Service rejected a transactional email',
+ { cause: error }
+ )
+ }
+ }
+ }
+}
diff --git a/packages/cloud/src/runtime/cloudflare/environment.ts b/packages/cloud/src/runtime/cloudflare/environment.ts
new file mode 100644
index 000000000..be771e896
--- /dev/null
+++ b/packages/cloud/src/runtime/cloudflare/environment.ts
@@ -0,0 +1,57 @@
+import {
+ loadAISigningKey,
+ parseCloudDeploymentTOML,
+ type AISigningKey,
+ type CloudEnvironment,
+ type CloudServerConfig
+} from '#cloud/server'
+
+import type { CollaborationRelayRPC } from './relay'
+
+/** The bindings `deploy/cloudflare/wrangler.jsonc` gives the Worker and its relay objects. */
+export type CloudflareCloudBindings = {
+ /** PostgreSQL, through Hyperdrive. */
+ HYPERDRIVE: Hyperdrive
+ /** The collaboration relay, one object per document. */
+ RELAY: DurableObjectNamespace<CollaborationRelayRPC>
+ /** The built portal, `dist-cloud-portal`. */
+ ASSETS: Fetcher
+ /** Required by `[email] transport = "cloudflare"`. */
+ EMAIL?: SendEmail
+}
+
+/** The bindings, plus the variables and secrets the deployment TOML names. */
+export type CloudflareCloudEnvironment = CloudflareCloudBindings & Record<string, unknown>
+
+export type PreparedCloudflareCloud = {
+ config: CloudServerConfig
+ aiSigningKey: AISigningKey | undefined
+}
+
+/** The Worker's string variables and secrets, with `DATABASE_URL` from Hyperdrive. */
+function configEnvironment(env: CloudflareCloudEnvironment): CloudEnvironment {
+ return {
+ ...Object.fromEntries(
+ Object.entries(env).filter((entry): entry is [string, string] => typeof entry[1] === 'string')
+ ),
+ DATABASE_URL: env.HYPERDRIVE.connectionString
+ }
+}
+
+/**
+ * Reads the deployment TOML once per isolate: its config and AI signing key stay the same for the
+ * Worker's lifetime. A failure is not kept, so the next request tries again.
+ */
+export function cloudflareCloudSetup(source: string) {
+ let prepared: Promise<PreparedCloudflareCloud> | null = null
+ return (env: CloudflareCloudEnvironment): Promise<PreparedCloudflareCloud> => {
+ prepared ??= (async () => {
+ const config = parseCloudDeploymentTOML(source, configEnvironment(env))
+ return { config, aiSigningKey: await loadAISigningKey(config) }
+ })().catch((error: unknown) => {
+ prepared = null
+ throw error
+ })
+ return prepared
+ }
+}
diff --git a/packages/cloud/src/runtime/cloudflare/index.ts b/packages/cloud/src/runtime/cloudflare/index.ts
new file mode 100644
index 000000000..40772bf42
--- /dev/null
+++ b/packages/cloud/src/runtime/cloudflare/index.ts
@@ -0,0 +1,3 @@
+export { createCloudflareEmailTransport, type CloudflareEmailBinding } from './email'
+export type { CloudflareCloudBindings, CloudflareCloudEnvironment } from './environment'
+export { createCloudflareCloud } from './worker'
diff --git a/packages/cloud/src/runtime/cloudflare/portal.ts b/packages/cloud/src/runtime/cloudflare/portal.ts
new file mode 100644
index 000000000..40cd1a723
--- /dev/null
+++ b/packages/cloud/src/runtime/cloudflare/portal.ts
@@ -0,0 +1,13 @@
+import type { PortalFiles } from '#cloud/runtime/portal/server'
+
+/** The built portal's files from the Worker's static assets. */
+export function assetPortalFiles(assets: Fetcher): PortalFiles {
+ return async (path, request) => {
+ const file = await assets.fetch(new URL(path, request.url))
+ if (!file.ok || !file.body) return null
+ return {
+ body: file.body,
+ type: file.headers.get('Content-Type') ?? 'application/octet-stream'
+ }
+ }
+}
diff --git a/packages/cloud/src/runtime/cloudflare/relay.ts b/packages/cloud/src/runtime/cloudflare/relay.ts
new file mode 100644
index 000000000..ff369722f
--- /dev/null
+++ b/packages/cloud/src/runtime/cloudflare/relay.ts
@@ -0,0 +1,134 @@
+import { RELAY_DOCUMENT_PARAM } from '#cloud/contract'
+import { createPostgresCloudDatabase } from '#cloud/runtime/postgres/database'
+import {
+ createCollaborationRelay,
+ createCollaborationStateStore,
+ createConfiguredCloudPolicy,
+ relayDocumentLookups,
+ type CollaborationRelay,
+ type RelayConnection
+} from '#cloud/server'
+import { DurableObject } from 'cloudflare:workers'
+import type { Context } from 'hono'
+import * as v from 'valibot'
+
+import type { CloudflareCloudEnvironment, PreparedCloudflareCloud } from './environment'
+
+/** What the Worker calls on a document's relay object. */
+export interface CollaborationRelayRPC extends DurableObject<CloudflareCloudEnvironment> {
+ /** Ends the document's live rooms after a restore, without saving them. */
+ startOver(documentId: string): void
+ /** Tells the document's live rooms its version history changed. */
+ announceVersions(documentId: string): void
+}
+
+const documentIdSchema = v.pipe(v.string(), v.uuid())
+
+/** The document's relay object. */
+export function relayFor(env: CloudflareCloudEnvironment, documentId: string) {
+ return env.RELAY.get(env.RELAY.idFromName(documentId))
+}
+
+/**
+ * Sends a relay socket to its document's relay object. The ticket's URL names the document; the
+ * object refuses tickets for any other.
+ */
+export function routeToRelay(c: Context<{ Bindings: CloudflareCloudEnvironment }>) {
+ if (c.req.header('Upgrade')?.toLowerCase() !== 'websocket') {
+ return c.text('Expected a WebSocket upgrade', 426)
+ }
+ const documentId = c.req.query(RELAY_DOCUMENT_PARAM)
+ if (!v.is(documentIdSchema, documentId)) return c.text('Missing document', 400)
+ return relayFor(c.env, documentId).fetch(c.req.raw)
+}
+
+/** A socket message's bytes; text is passed on as bytes for the relay to refuse. */
+function bytes(data: unknown): Uint8Array {
+ if (data instanceof ArrayBuffer) return new Uint8Array(data)
+ return new TextEncoder().encode(typeof data === 'string' ? data : '')
+}
+
+/** Hands a WebSocket the object accepted to the relay, as the Node runtime does with `ws`. */
+function accept(relay: CollaborationRelay): Response {
+ const { 0: client, 1: server } = new WebSocketPair()
+ // Standard sockets deliver binary messages as Blobs unless asked otherwise.
+ server.binaryType = 'arraybuffer'
+ server.accept()
+ let connection: RelayConnection | null = null
+ const closed = () => {
+ connection?.closed()
+ connection = null
+ }
+ // A closing socket throws on send and close, which would stop a broadcast to the others.
+ const open = () => server.readyState === WebSocket.OPEN
+ connection = relay.connect({
+ send(data) {
+ if (open()) server.send(data)
+ },
+ close(code, reason) {
+ if (open()) server.close(code, reason)
+ }
+ })
+ server.addEventListener('message', ({ data }: { data: unknown }) =>
+ connection?.receive(bytes(data))
+ )
+ server.addEventListener('close', closed)
+ server.addEventListener('error', closed)
+ return new Response(null, { status: 101, webSocket: client })
+}
+
+/**
+ * The Durable Object class holding one document's live rooms: every epoch of the document meets
+ * on one relay, so a restore or a version change reaches all of them in one call. Sockets stay
+ * open without hibernation, so the rooms' documents and timers live in memory as on Node.
+ */
+export function createCloudflareRelayObject(
+ prepare: (env: CloudflareCloudEnvironment) => Promise<PreparedCloudflareCloud>
+) {
+ return class CollaborationRelayObject
+ extends DurableObject<CloudflareCloudEnvironment>
+ implements CollaborationRelayRPC
+ {
+ #relay: Promise<CollaborationRelay> | null = null
+ /** Set by the first socket; restores and version changes before it have no rooms to reach. */
+ #opened: CollaborationRelay | null = null
+
+ #open(documentId: string) {
+ this.#relay ??= prepare(this.env).then(({ config }) => {
+ const database = createPostgresCloudDatabase({ connectionString: config.databaseURL })
+ this.#opened = createCollaborationRelay({
+ authSecret: config.authSecret,
+ documentId,
+ store: createCollaborationStateStore(database),
+ maximumMessageBytes: config.technicalLimits.maximumCollaborationMessageBytes,
+ maximumConnectionsPerRoom: config.technicalLimits.maximumConnectionsPerRoom,
+ ...relayDocumentLookups(
+ database,
+ createConfiguredCloudPolicy(config, database),
+ config.deployment
+ )
+ })
+ return this.#opened
+ })
+ this.#relay.catch(() => {
+ this.#relay = null
+ })
+ return this.#relay
+ }
+
+ /** Accepts a socket that `routeToRelay` sent here. */
+ override async fetch(request: Request): Promise<Response> {
+ const documentId = new URL(request.url).searchParams.get(RELAY_DOCUMENT_PARAM)
+ if (!v.is(documentIdSchema, documentId)) return new Response(null, { status: 400 })
+ return accept(await this.#open(documentId))
+ }
+
+ startOver(documentId: string) {
+ this.#opened?.startOver(documentId)
+ }
+
+ announceVersions(documentId: string) {
+ this.#opened?.announceVersions(documentId)
+ }
+ }
+}
diff --git a/packages/cloud/src/runtime/cloudflare/tsconfig.json b/packages/cloud/src/runtime/cloudflare/tsconfig.json
new file mode 100644
index 000000000..e54e3e467
--- /dev/null
+++ b/packages/cloud/src/runtime/cloudflare/tsconfig.json
@@ -0,0 +1,21 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "noUncheckedIndexedAccess": true,
+ "noImplicitOverride": true,
+ "useUnknownInCatchVariables": true,
+ "noFallthroughCasesInSwitch": true,
+ "lib": ["ES2023"],
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "noEmit": true,
+ "skipLibCheck": true,
+ "types": ["@cloudflare/workers-types"],
+ "paths": {
+ "#cloud/*": ["../../*"]
+ }
+ },
+ "include": ["./**/*.ts", "../../../deploy/**/*.ts"],
+ "exclude": ["../../../deploy/generated"]
+}
diff --git a/packages/cloud/src/runtime/cloudflare/worker.ts b/packages/cloud/src/runtime/cloudflare/worker.ts
new file mode 100644
index 000000000..4cf19174c
--- /dev/null
+++ b/packages/cloud/src/runtime/cloudflare/worker.ts
@@ -0,0 +1,160 @@
+import { defaultRelayURL, RELAY_PATH } from '#cloud/contract'
+import { createCloudServer } from '#cloud/runtime/portal/server'
+import { createPostgresCloudDatabase } from '#cloud/runtime/postgres/database'
+import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
+import {
+ cleanupPassOptions,
+ createCleanupServices,
+ createCloudApp,
+ createCloudAuthenticationRuntime,
+ createConfiguredCloudPolicy,
+ createInvitationOutbox,
+ createTransactionalEmailService,
+ runCleanup,
+ type TransactionalEmailService
+} from '#cloud/server'
+import { Hono } from 'hono'
+
+import { createCloudflareEmailTransport } from './email'
+import {
+ cloudflareCloudSetup,
+ type CloudflareCloudEnvironment,
+ type PreparedCloudflareCloud
+} from './environment'
+import { assetPortalFiles } from './portal'
+import { createCloudflareRelayObject, relayFor, routeToRelay } from './relay'
+
+function emailTransport({ config }: PreparedCloudflareCloud, env: CloudflareCloudEnvironment) {
+ if (config.emailTransport !== 'cloudflare') return undefined
+ if (!env.EMAIL) throw new Error('[email] transport = "cloudflare" needs the EMAIL binding')
+ return createCloudflareEmailTransport(env.EMAIL)
+}
+
+/**
+ * What one request or cron run needs. Workers can't share connections between requests, so each
+ * gets its own database client, closed once its background work settles.
+ */
+function cloudServices(
+ prepared: PreparedCloudflareCloud,
+ env: CloudflareCloudEnvironment,
+ context: Pick<ExecutionContext, 'waitUntil'>
+) {
+ const { config } = prepared
+ const database = createPostgresCloudDatabase({ connectionString: config.databaseURL })
+ const objects = createS3ObjectStore(config)
+ const transport = emailTransport(prepared, env)
+ const queued = createTransactionalEmailService(database, {
+ encryptionSecret: config.authSecret,
+ from: config.emailFrom ?? '',
+ transport
+ })
+ // Mail is sent once the request is done rather than by a polling worker, so sign-in links
+ // don't wait for the next cron run.
+ let enqueued = false
+ const email: TransactionalEmailService = {
+ ...queued,
+ enqueue(input, transaction) {
+ enqueued = true
+ return queued.enqueue(input, transaction)
+ }
+ }
+ const background: Promise<unknown>[] = []
+ const runInBackground = (task: Promise<unknown>) => {
+ background.push(
+ task.catch((error: unknown) => console.error('[Cloud] Background work failed:', error))
+ )
+ }
+ const deliver = () =>
+ email.deliverPending({
+ batchSize: config.emailBatchSize,
+ leaseDurationMs: config.emailLeaseDurationMs,
+ maximumAttempts: config.emailMaximumAttempts
+ })
+ return {
+ config,
+ database,
+ objects,
+ email,
+ transport,
+ runInBackground,
+ deliver,
+ /** Sends what the request queued and closes the database after everything it started. */
+ finish() {
+ context.waitUntil(
+ Promise.allSettled(background)
+ .then(() => (enqueued && transport ? deliver() : undefined))
+ .catch((error: unknown) => console.error('[Cloud] Sending email failed:', error))
+ .then(() => database.destroy())
+ )
+ }
+ }
+}
+
+/**
+ * OpenPencil Cloud on Cloudflare Workers, configured by a deployment TOML. The Worker serves the
+ * API and portal per request, a Durable Object per document runs its collaboration rooms, and a
+ * Cron Trigger runs cleanup and retries email.
+ */
+export function createCloudflareCloud(configSource: string) {
+ const prepare = cloudflareCloudSetup(configSource)
+
+ const router = new Hono<{ Bindings: CloudflareCloudEnvironment }>()
+ .get(RELAY_PATH, routeToRelay)
+ .all('*', async (c) => {
+ const prepared = await prepare(c.env)
+ const services = cloudServices(prepared, c.env, c.executionCtx)
+ const { config, database, email, transport, runInBackground } = services
+ try {
+ const { auth, enrollment } = createCloudAuthenticationRuntime(config, database, email, {
+ runInBackground,
+ validateSchema: false
+ })
+ const app = createCloudApp({
+ config,
+ database,
+ auth,
+ objects: services.objects,
+ invitationOutbox: transport ? createInvitationOutbox(email) : undefined,
+ transactionalEmail: email,
+ enrollment,
+ aiSigningKey: prepared.aiSigningKey,
+ relayURL: config.relayURL ?? defaultRelayURL(config.publicURL),
+ onDocumentRestored: (documentId) =>
+ runInBackground(relayFor(c.env, documentId).startOver(documentId)),
+ onDocumentVersionsChanged: (documentId) =>
+ runInBackground(relayFor(c.env, documentId).announceVersions(documentId))
+ })
+ return await createCloudServer(app, {
+ portal: assetPortalFiles(c.env.ASSETS),
+ indexingPolicy: config.indexingPolicy
+ }).fetch(c.req.raw)
+ } finally {
+ services.finish()
+ }
+ })
+
+ const worker: ExportedHandler<CloudflareCloudEnvironment> = {
+ fetch: (request, env, context) => router.fetch(request, env, context),
+
+ async scheduled(_controller, env, context) {
+ const prepared = await prepare(env)
+ const services = cloudServices(prepared, env, context)
+ const { config, database, objects } = services
+ try {
+ if (config.cleanupEnabled) {
+ const policy = createConfiguredCloudPolicy(config, database)
+ await runCleanup(
+ createCleanupServices(config, database, objects, policy),
+ cleanupPassOptions(config)
+ )
+ }
+ // Retries what failed to send after its request, and what a full batch left behind.
+ if (services.transport) await services.deliver()
+ } finally {
+ services.finish()
+ }
+ }
+ }
+
+ return { worker, CollaborationRelayObject: createCloudflareRelayObject(prepare) }
+}
diff --git a/packages/cloud/src/runtime/node/application.ts b/packages/cloud/src/runtime/node/application.ts
index 10278a422..aad3b9c46 100644
--- a/packages/cloud/src/runtime/node/application.ts
+++ b/packages/cloud/src/runtime/node/application.ts
@@ -1,3 +1,4 @@
+import { createPostgresCloudDatabase } from '#cloud/runtime/postgres/database'
import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
import {
createCloudAuthenticationRuntime,
@@ -10,7 +11,6 @@ import {
} from '#cloud/server'
import { loadNodeCloudServerConfig } from './config'
-import { createNodeCloudDatabase } from './database'
import { createNodeTransactionalEmailRuntime } from './email/runtime'
export type NodeCloudApplicationOptions = {
@@ -23,14 +23,14 @@ export async function createNodeCloudApplication(
): Promise<{
app: CloudApp
config: CloudServerConfig
- database: ReturnType<typeof createNodeCloudDatabase>
+ database: ReturnType<typeof createPostgresCloudDatabase>
objects: ObjectStore
email: ReturnType<typeof createNodeTransactionalEmailRuntime>['email']
}> {
const environment = options.environment ?? process.env
const config = await loadNodeCloudServerConfig(environment)
const aiSigningKey = await loadAISigningKey(config)
- const database = createNodeCloudDatabase({
+ const database = createPostgresCloudDatabase({
connectionString: options.databaseURL ?? config.databaseURL
})
const objects = createS3ObjectStore(config)
diff --git a/packages/cloud/src/runtime/node/bootstrap.ts b/packages/cloud/src/runtime/node/bootstrap.ts
index d7e13dacb..d11ce4bdd 100644
--- a/packages/cloud/src/runtime/node/bootstrap.ts
+++ b/packages/cloud/src/runtime/node/bootstrap.ts
@@ -1,3 +1,4 @@
+import { createPostgresCloudDatabase } from '#cloud/runtime/postgres/database'
import {
createBetterAuthAdapter,
migrateCloudDatabase,
@@ -5,17 +6,16 @@ import {
} from '#cloud/server'
import { loadNodeCloudServerConfig } from './config'
-import { createNodeCloudDatabase } from './database'
export async function createMigratedNodeCloudDatabase(
environment: Readonly<Record<string, string | undefined>>
): Promise<{
config: CloudServerConfig
- database: ReturnType<typeof createNodeCloudDatabase>
+ database: ReturnType<typeof createPostgresCloudDatabase>
auth: ReturnType<typeof createBetterAuthAdapter>
}> {
const config = await loadNodeCloudServerConfig(environment)
- const database = createNodeCloudDatabase({ connectionString: config.databaseURL })
+ const database = createPostgresCloudDatabase({ connectionString: config.databaseURL })
const auth = createBetterAuthAdapter(config, database)
await migrateCloudDatabase(database, { run: auth.migrate, schemaVersion: auth.schemaVersion })
return { config, database, auth }
diff --git a/packages/cloud/src/runtime/node/cleanup.ts b/packages/cloud/src/runtime/node/cleanup.ts
index 82a01e851..45082c8f4 100644
--- a/packages/cloud/src/runtime/node/cleanup.ts
+++ b/packages/cloud/src/runtime/node/cleanup.ts
@@ -1,44 +1,24 @@
+import { createPostgresCloudDatabase } from '#cloud/runtime/postgres/database'
import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
import {
- createDefaultCloudPolicy,
- createDocumentCleanupService,
- createRevisionCompactionService,
- createUploadCleanupService,
- DatabaseEntitlementSource,
- EntitlementOpenFeatureProvider,
- REVISION_COMPACTION_GRACE_MS,
- StaticEntitlementSource,
- staticEntitlementValues
+ cleanupPassOptions,
+ createCleanupServices,
+ createConfiguredCloudPolicy,
+ runCleanup
} from '#cloud/server'
import { loadNodeCloudServerConfig } from './config'
-import { createNodeCloudDatabase } from './database'
const config = await loadNodeCloudServerConfig(process.env)
-const database = createNodeCloudDatabase({ connectionString: config.databaseURL })
+const database = createPostgresCloudDatabase({ connectionString: config.databaseURL })
const objects = createS3ObjectStore(config)
try {
- const uploads = await createUploadCleanupService(database, objects).cleanupExpiredUploads({
- batchSize: config.cleanupBatchSize,
- leaseDurationMs: config.cleanupLeaseDurationMs
- })
- const documents = await createDocumentCleanupService(database, objects).cleanupDeletedDocuments({
- batchSize: config.cleanupBatchSize,
- leaseDurationMs: config.cleanupLeaseDurationMs,
- retentionMs: config.documentRetentionMs
- })
- const policy = createDefaultCloudPolicy(
- new EntitlementOpenFeatureProvider(
- config.staticEntitlements
- ? new StaticEntitlementSource(staticEntitlementValues(config.staticEntitlements))
- : new DatabaseEntitlementSource(database)
- )
+ const policy = createConfiguredCloudPolicy(config, database)
+ const result = await runCleanup(
+ createCleanupServices(config, database, objects, policy),
+ cleanupPassOptions(config)
)
- const revisions = await createRevisionCompactionService(database, objects, {
- policy,
- deploymentMode: config.deployment
- }).compactRevisions({ batchSize: config.cleanupBatchSize, graceMs: REVISION_COMPACTION_GRACE_MS })
- console.log(JSON.stringify({ uploads, documents, revisions }))
+ console.log(JSON.stringify(result))
} finally {
await database.destroy()
}
diff --git a/packages/cloud/src/runtime/node/index.ts b/packages/cloud/src/runtime/node/index.ts
index 39031d6da..624b0f185 100644
--- a/packages/cloud/src/runtime/node/index.ts
+++ b/packages/cloud/src/runtime/node/index.ts
@@ -5,7 +5,10 @@ export {
createNodeTransactionalEmailRuntime,
type NodeTransactionalEmailRuntime
} from './email/runtime'
-export { createNodeCloudDatabase, type NodeCloudDatabaseOptions } from './database'
+export {
+ createPostgresCloudDatabase,
+ type PostgresCloudDatabaseOptions
+} from '#cloud/runtime/postgres/database'
export {
createNodemailerInvitationDelivery,
createSMTPInvitationDelivery,
@@ -17,5 +20,5 @@ export {
type SMTPTransactionalEmailTransportOptions
} from './email/transport'
export { createS3ObjectStore } from '#cloud/runtime/s3/objects'
-export { attachCollaborationRelay, defaultRelayURL } from './relay'
+export { attachCollaborationRelay } from './relay'
export { startNodeCloudServer, type NodeCloudServerOptions } from './server'
diff --git a/packages/cloud/src/runtime/node/migrate.ts b/packages/cloud/src/runtime/node/migrate.ts
index 1d8d077e0..05f7c9209 100644
--- a/packages/cloud/src/runtime/node/migrate.ts
+++ b/packages/cloud/src/runtime/node/migrate.ts
@@ -1,10 +1,10 @@
+import { createPostgresCloudDatabase } from '#cloud/runtime/postgres/database'
import { createBetterAuthAdapter, migrateCloudDatabase } from '#cloud/server'
import { loadNodeCloudServerConfig } from './config'
-import { createNodeCloudDatabase } from './database'
const config = await loadNodeCloudServerConfig(process.env)
-const database = createNodeCloudDatabase({ connectionString: config.databaseURL })
+const database = createPostgresCloudDatabase({ connectionString: config.databaseURL })
try {
const auth = createBetterAuthAdapter(config, database)
await migrateCloudDatabase(database, { run: auth.migrate, schemaVersion: auth.schemaVersion })
diff --git a/packages/cloud/src/runtime/node/portal.ts b/packages/cloud/src/runtime/node/portal.ts
index 98ecf6079..31c7785a8 100644
--- a/packages/cloud/src/runtime/node/portal.ts
+++ b/packages/cloud/src/runtime/node/portal.ts
@@ -1,69 +1,26 @@
import { readFile } from 'node:fs/promises'
import { resolve, sep } from 'node:path'
-import { isCloudPortalPage } from '#cloud/contract'
+import type { PortalFiles } from '#cloud/runtime/portal/server'
import { getMimeType } from 'hono/utils/mime'
-const PAGE_HEADERS = {
- 'Content-Type': 'text/html; charset=utf-8',
- 'Cache-Control': 'no-cache',
- // Desktop sign-in approval must never be framed by another site.
- 'Content-Security-Policy': "frame-ancestors 'none'",
- 'Referrer-Policy': 'no-referrer',
- 'X-Content-Type-Options': 'nosniff'
-}
-
-function decodedPath(request: Request): string | null {
- try {
- return decodeURIComponent(new URL(request.url).pathname)
- } catch {
- return null
- }
-}
-
-/**
- * Serves a built Cloud portal (`bun run build:cloud-portal`) from `directory`: `cloud.html` for
- * portal pages, and its hashed assets and icons for paths the API does not answer.
- */
-export function createNodeCloudPortal(directory: string) {
+/** The built portal's files in `directory`, never anything outside it. */
+export function nodePortalFiles(directory: string): PortalFiles {
const root = resolve(directory)
-
- async function read(path: string) {
- const file = resolve(root, `.${path}`)
- if (!file.startsWith(`${root}${sep}`)) return null
+ return async (path) => {
+ let decoded: string
try {
- return await readFile(file)
+ decoded = decodeURIComponent(path)
} catch {
return null
}
- }
-
- return {
- /** The portal page for `request`, or null when it is not one. */
- async page(request: Request): Promise<Response | null> {
- if (request.method !== 'GET' && request.method !== 'HEAD') return null
- if (!isCloudPortalPage(new URL(request.url).pathname)) return null
- const page = await read('/cloud.html')
- return page ? new Response(page, { headers: PAGE_HEADERS }) : null
- },
-
- /** A portal file for `request`, or null when there is none. */
- async file(request: Request): Promise<Response | null> {
- if (request.method !== 'GET' && request.method !== 'HEAD') return null
- const path = decodedPath(request)
- if (!path || path === '/cloud.html') return null
- const type = getMimeType(path)
- const body = type ? await read(path) : null
- if (!type || !body) return null
- return new Response(body, {
- headers: {
- 'Content-Type': type,
- 'Cache-Control': path.startsWith('/assets/')
- ? 'public, max-age=31536000, immutable'
- : 'public, max-age=3600',
- 'X-Content-Type-Options': 'nosniff'
- }
- })
+ const type = getMimeType(decoded)
+ const file = resolve(root, `.${decoded}`)
+ if (!type || !file.startsWith(`${root}${sep}`)) return null
+ try {
+ return { body: new Uint8Array(await readFile(file)), type }
+ } catch {
+ return null
}
}
}
diff --git a/packages/cloud/src/runtime/node/relay.ts b/packages/cloud/src/runtime/node/relay.ts
index 3410748fd..26796ef29 100644
--- a/packages/cloud/src/runtime/node/relay.ts
+++ b/packages/cloud/src/runtime/node/relay.ts
@@ -52,10 +52,3 @@ export function attachCollaborationRelay(
}
}
}
-
-/** 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.ts
index 061efc0d8..c9cc36fa4 100644
--- a/packages/cloud/src/runtime/node/server.ts
+++ b/packages/cloud/src/runtime/node/server.ts
@@ -1,32 +1,27 @@
import { createServer } from 'node:http'
+import { defaultRelayURL } from '#cloud/contract'
+import { createCloudServer } from '#cloud/runtime/portal/server'
import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
import {
- CLOUD_FEATURE_KEYS,
createCloudApp,
loadAISigningKey,
createCloudAuthenticationRuntime,
createCollaborationRelay,
createCollaborationStateStore,
- createDefaultCloudPolicy,
- DatabaseEntitlementSource,
- EntitlementOpenFeatureProvider,
- StaticEntitlementSource,
- staticEntitlementValues,
- createDocumentCleanupService,
- createRateLimitCleanupService,
- createRevisionCompactionService,
- createUploadCleanupService,
+ cleanupPassOptions,
+ createCleanupServices,
+ createConfiguredCloudPolicy,
+ relayDocumentLookups,
startCleanupWorker,
- startTransactionalEmailWorker,
- withIndexingPolicy
+ startTransactionalEmailWorker
} from '#cloud/server'
import { getRequestListener } from '@hono/node-server'
import { createMigratedNodeCloudDatabase } from './bootstrap'
import { createNodeTransactionalEmailRuntime } from './email/runtime'
-import { createNodeCloudPortal } from './portal'
-import { attachCollaborationRelay, defaultRelayURL } from './relay'
+import { nodePortalFiles } from './portal'
+import { attachCollaborationRelay } from './relay'
export type NodeCloudServerOptions = {
environment?: Readonly<Record<string, string | undefined>>
@@ -48,61 +43,20 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})
transport: emailTransport
} = createNodeTransactionalEmailRuntime(config, database)
const { auth, enrollment } = createCloudAuthenticationRuntime(config, database, email)
- const policy = createDefaultCloudPolicy(
- new EntitlementOpenFeatureProvider(
- config.staticEntitlements
- ? new StaticEntitlementSource(staticEntitlementValues(config.staticEntitlements))
- : new DatabaseEntitlementSource(database)
- )
- )
+ const policy = createConfiguredCloudPolicy(config, database)
const cleanup = config.cleanupEnabled
- ? startCleanupWorker(
- {
- documents: createDocumentCleanupService(database, objects),
- revisions: createRevisionCompactionService(database, objects, {
- policy,
- deploymentMode: config.deployment
- }),
- uploads: createUploadCleanupService(database, objects),
- rateLimits: createRateLimitCleanupService(database)
- },
- {
- batchSize: config.cleanupBatchSize,
- documentRetentionMs: config.documentRetentionMs,
- intervalMs: config.cleanupIntervalMs,
- leaseDurationMs: config.cleanupLeaseDurationMs,
- onError: (error) => console.error('[Cloud] Cleanup worker failed:', error)
- }
- )
+ ? startCleanupWorker(createCleanupServices(config, database, objects, policy), {
+ ...cleanupPassOptions(config),
+ intervalMs: config.cleanupIntervalMs,
+ onError: (error) => console.error('[Cloud] Cleanup worker failed:', error)
+ })
: undefined
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
- },
- async currentRoomEpoch(documentId) {
- const document = await database
- .selectFrom('document')
- .select('collaborationEpoch')
- .where('id', '=', documentId)
- .executeTakeFirst()
- return document?.collaborationEpoch ?? null
- }
+ ...relayDocumentLookups(database, policy, config.deployment)
})
const app = createCloudApp({
config,
@@ -127,19 +81,14 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})
})
: undefined
const portalDirectory = environment.OPENPENCIL_CLOUD_PORTAL_DIR
- const portal = portalDirectory ? createNodeCloudPortal(portalDirectory) : undefined
- // Without the portal build, sign-in, account, and administration pages answer 404.
- if (!portal)
+ if (!portalDirectory)
console.warn('[Cloud] OPENPENCIL_CLOUD_PORTAL_DIR is not set; sign-in pages are off.')
+ const cloudServer = createCloudServer(app, {
+ portal: portalDirectory ? nodePortalFiles(portalDirectory) : undefined,
+ indexingPolicy: config.indexingPolicy
+ })
const server = await listen(
- async (request) => {
- const path = new URL(request.url).pathname
- const page = await portal?.page(request)
- if (page) return withIndexingPolicy(page, path, config.indexingPolicy)
- const response = await app.fetch(request)
- const file = response.status === 404 ? await portal?.file(request) : null
- return withIndexingPolicy(file ?? response, path, config.indexingPolicy)
- },
+ async (request) => cloudServer.fetch(request),
options.port ?? Number(environment.PORT ?? 8787),
environment.HOST ?? '0.0.0.0'
)
diff --git a/packages/cloud/src/runtime/portal/server.ts b/packages/cloud/src/runtime/portal/server.ts
new file mode 100644
index 000000000..1188711d6
--- /dev/null
+++ b/packages/cloud/src/runtime/portal/server.ts
@@ -0,0 +1,65 @@
+import { CLOUD_PORTAL_PAGE_ROOTS } from '#cloud/contract'
+import { withIndexingPolicy } from '#cloud/server'
+import { Hono } from 'hono'
+
+/** A file of the built portal (`bun run build:cloud-portal`). */
+export type PortalFile = { body: ReadableStream | Uint8Array<ArrayBuffer>; type: string }
+
+/** Reads the built portal's file at a URL path, or null when there is none. */
+export type PortalFiles = (path: string, request: Request) => Promise<PortalFile | null>
+
+const PAGE_PATH = '/cloud.html'
+
+const PAGE_HEADERS = {
+ 'Content-Type': 'text/html; charset=utf-8',
+ 'Cache-Control': 'no-cache',
+ // Desktop sign-in approval must never be framed by another site.
+ 'Content-Security-Policy': "frame-ancestors 'none'",
+ 'Referrer-Policy': 'no-referrer',
+ 'X-Content-Type-Options': 'nosniff'
+}
+
+export type CloudServerOptions = {
+ /** The built portal; without it, sign-in, account, and administration pages answer 404. */
+ portal?: PortalFiles
+ indexingPolicy: 'allow' | 'deny'
+}
+
+/**
+ * A Cloud server as every runtime serves it: the portal's `cloud.html` at portal pages, the API
+ * everywhere else, and the portal's assets and icons where the API has nothing.
+ */
+export function createCloudServer(
+ api: { fetch(request: Request): Response | Promise<Response> },
+ { portal, indexingPolicy }: CloudServerOptions
+) {
+ const server = new Hono()
+ server.use(async (c, next) => {
+ await next()
+ c.res = withIndexingPolicy(c.res, c.req.path, indexingPolicy)
+ })
+ if (portal) {
+ const pages = CLOUD_PORTAL_PAGE_ROOTS.flatMap((root) => [root, `${root}/*`])
+ server.on(['GET', 'HEAD'], pages, async (c) => {
+ const page = await portal(PAGE_PATH, c.req.raw)
+ return page ? c.body(page.body, 200, PAGE_HEADERS) : c.notFound()
+ })
+ server.on(['GET', 'HEAD'], '*', async (c, next) => {
+ await next()
+ if (c.res.status !== 404 || c.req.path === PAGE_PATH) return
+ const file = await portal(c.req.path, c.req.raw)
+ if (!file) return
+ c.res = new Response(file.body, {
+ headers: {
+ 'Content-Type': file.type,
+ 'Cache-Control': c.req.path.startsWith('/assets/')
+ ? 'public, max-age=31536000, immutable'
+ : 'public, max-age=3600',
+ 'X-Content-Type-Options': 'nosniff'
+ }
+ })
+ })
+ }
+ server.all('*', (c) => api.fetch(c.req.raw))
+ return server
+}
diff --git a/packages/cloud/src/runtime/node/database.ts b/packages/cloud/src/runtime/postgres/database.ts
similarity index 75%
rename from packages/cloud/src/runtime/node/database.ts
rename to packages/cloud/src/runtime/postgres/database.ts
index 3ba74110f..e77e9ac57 100644
--- a/packages/cloud/src/runtime/node/database.ts
+++ b/packages/cloud/src/runtime/postgres/database.ts
@@ -2,12 +2,12 @@ import { createCloudDatabase } from '#cloud/server'
import { PostgresDialect } from 'kysely'
import { Pool, type PoolConfig } from 'pg'
-export type NodeCloudDatabaseOptions = {
+export type PostgresCloudDatabaseOptions = {
connectionString: string
pool?: Omit<PoolConfig, 'connectionString'>
}
-export function createNodeCloudDatabase(options: NodeCloudDatabaseOptions) {
+export function createPostgresCloudDatabase(options: PostgresCloudDatabaseOptions) {
return createCloudDatabase({
dialect: new PostgresDialect({
pool: new Pool({
diff --git a/packages/cloud/src/server/app.ts b/packages/cloud/src/server/app.ts
index d54e2aaed..042c5210c 100644
--- a/packages/cloud/src/server/app.ts
+++ b/packages/cloud/src/server/app.ts
@@ -41,12 +41,10 @@ import { createInternalRoutes, createInternalService } from '#cloud/server/inter
import type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'
import type { ObjectStore } from '#cloud/server/objects'
import {
+ createConfiguredCloudPolicy,
createDefaultCloudPolicy,
createEntitlementService,
- DatabaseEntitlementSource,
EntitlementOpenFeatureProvider,
- StaticEntitlementSource,
- staticEntitlementValues,
type CloudPolicy,
type EntitlementSource
} from '#cloud/server/policy'
@@ -204,14 +202,11 @@ export function createCloudApp(services: CloudServices) {
requireMFA: services.config.deploymentAdminMFARequired
}
)
- const entitlementSource =
- services.entitlementSource ??
- (services.config.staticEntitlements
- ? new StaticEntitlementSource(staticEntitlementValues(services.config.staticEntitlements))
- : new DatabaseEntitlementSource(services.database))
const policy =
services.policy ??
- createDefaultCloudPolicy(new EntitlementOpenFeatureProvider(entitlementSource))
+ (services.entitlementSource
+ ? createDefaultCloudPolicy(new EntitlementOpenFeatureProvider(services.entitlementSource))
+ : createConfiguredCloudPolicy(services.config, services.database))
const documents = createDocumentService(services.database, services.objects, {
policy,
technicalMaximumUploadBytes: services.config.technicalLimits.maximumUploadBytes,
diff --git a/packages/cloud/src/server/auth/factory.ts b/packages/cloud/src/server/auth/factory.ts
index a4e72a408..8c04dfb98 100644
--- a/packages/cloud/src/server/auth/factory.ts
+++ b/packages/cloud/src/server/auth/factory.ts
@@ -124,6 +124,11 @@ async function verifySecondFactor(
export type CloudAuthRuntimeOptions = {
email?: AuthenticationEmailService
runInBackground?: (promise: Promise<unknown>) => void
+ /**
+ * Whether Better Auth checks the database schema when it starts. Runtimes that start it for
+ * every request turn this off; `migrateCloudDatabase` has already checked the recorded version.
+ */
+ validateSchema?: boolean
}
export function createBetterAuthAdapter(
@@ -157,7 +162,7 @@ export function createBetterAuthAdapter(
},
session: { freshAge: ACCOUNT_SECURITY_FRESH_AGE_SECONDS },
advanced: {
- database: { generateId: 'uuid' },
+ database: { generateId: 'uuid', validateSchema: runtime.validateSchema },
ipAddress: {
ipAddressHeaders: config.authTrustedIPHeaders,
trustedProxies: config.authTrustedProxies
diff --git a/packages/cloud/src/server/auth/runtime.ts b/packages/cloud/src/server/auth/runtime.ts
index a4c608dcd..8a19bdbcc 100644
--- a/packages/cloud/src/server/auth/runtime.ts
+++ b/packages/cloud/src/server/auth/runtime.ts
@@ -11,7 +11,7 @@ export function createCloudAuthenticationRuntime(
config: CloudServerConfig,
database: Kysely<CloudDatabase>,
email: TransactionalEmailService,
- options: Pick<CloudAuthRuntimeOptions, 'runInBackground'> = {}
+ options: Pick<CloudAuthRuntimeOptions, 'runInBackground' | 'validateSchema'> = {}
) {
const enrollment = createEnrollmentService(database, {
appURL: config.appURL ?? config.publicURL,
diff --git a/packages/cloud/src/server/cleanup/configured.ts b/packages/cloud/src/server/cleanup/configured.ts
new file mode 100644
index 000000000..52c323f3e
--- /dev/null
+++ b/packages/cloud/src/server/cleanup/configured.ts
@@ -0,0 +1,38 @@
+import type { CloudServerConfig } from '#cloud/server/config'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { ObjectStore } from '#cloud/server/objects'
+import type { CloudPolicy } from '#cloud/server/policy/policy'
+import { createRateLimitCleanupService } from '#cloud/server/rate-limit/cleanup'
+import type { Kysely } from 'kysely'
+
+import { createDocumentCleanupService } from './documents'
+import { createRevisionCompactionService } from './revisions'
+import { createUploadCleanupService } from './uploads'
+import type { CleanupPassOptions, CleanupServices } from './worker'
+
+/** Every cleanup service, over a deployment's database and bucket. */
+export function createCleanupServices(
+ config: Pick<CloudServerConfig, 'deployment'>,
+ database: Kysely<CloudDatabase>,
+ objects: ObjectStore,
+ policy: CloudPolicy
+): CleanupServices {
+ return {
+ uploads: createUploadCleanupService(database, objects),
+ documents: createDocumentCleanupService(database, objects),
+ revisions: createRevisionCompactionService(database, objects, {
+ policy,
+ deploymentMode: config.deployment
+ }),
+ rateLimits: createRateLimitCleanupService(database)
+ }
+}
+
+/** The batch, lease, and retention a deployment sets for each cleanup pass. */
+export function cleanupPassOptions(config: CloudServerConfig): CleanupPassOptions {
+ return {
+ batchSize: config.cleanupBatchSize,
+ documentRetentionMs: config.documentRetentionMs,
+ leaseDurationMs: config.cleanupLeaseDurationMs
+ }
+}
diff --git a/packages/cloud/src/server/cleanup/index.ts b/packages/cloud/src/server/cleanup/index.ts
index 17a1c884e..69d693c8c 100644
--- a/packages/cloud/src/server/cleanup/index.ts
+++ b/packages/cloud/src/server/cleanup/index.ts
@@ -1,3 +1,4 @@
+export { cleanupPassOptions, createCleanupServices } from './configured'
export {
createDocumentCleanupService,
type DocumentCleanupOptions,
@@ -18,7 +19,9 @@ export {
type UploadCleanupService
} from './uploads'
export {
+ runCleanup,
startCleanupWorker,
+ type CleanupPassOptions,
type CleanupResult,
type CleanupServices,
type CleanupWorker,
diff --git a/packages/cloud/src/server/cleanup/worker.ts b/packages/cloud/src/server/cleanup/worker.ts
index 239662518..776664356 100644
--- a/packages/cloud/src/server/cleanup/worker.ts
+++ b/packages/cloud/src/server/cleanup/worker.ts
@@ -35,6 +35,37 @@ export type CleanupWorker = {
stop(): Promise<void>
}
+export type CleanupPassOptions = Pick<
+ CleanupWorkerOptions,
+ 'batchSize' | 'documentRetentionMs' | 'leaseDurationMs'
+>
+
+/** One cleanup pass, for runtimes that schedule passes themselves. */
+export async function runCleanup(
+ cleanup: CleanupServices,
+ options: CleanupPassOptions
+): Promise<CleanupResult> {
+ const uploads = await cleanup.uploads.cleanupExpiredUploads({
+ batchSize: options.batchSize,
+ leaseDurationMs: options.leaseDurationMs
+ })
+ const documents = await cleanup.documents.cleanupDeletedDocuments({
+ batchSize: options.batchSize,
+ leaseDurationMs: options.leaseDurationMs,
+ retentionMs: options.documentRetentionMs
+ })
+ const revisions = cleanup.revisions
+ ? await cleanup.revisions.compactRevisions({
+ batchSize: options.batchSize,
+ graceMs: REVISION_COMPACTION_GRACE_MS
+ })
+ : null
+ const rateLimits = cleanup.rateLimits
+ ? await cleanup.rateLimits.cleanupExpired(new Date(Date.now() - 24 * 60 * 60_000))
+ : 0
+ return { uploads, documents, revisions, rateLimits }
+}
+
export function startCleanupWorker(
cleanup: CleanupServices,
options: CleanupWorkerOptions
@@ -43,26 +74,6 @@ export function startCleanupWorker(
intervalMs: options.intervalMs,
signal: options.signal,
onError: options.onError,
- async run() {
- const uploads = await cleanup.uploads.cleanupExpiredUploads({
- batchSize: options.batchSize,
- leaseDurationMs: options.leaseDurationMs
- })
- const documents = await cleanup.documents.cleanupDeletedDocuments({
- batchSize: options.batchSize,
- leaseDurationMs: options.leaseDurationMs,
- retentionMs: options.documentRetentionMs
- })
- const revisions = cleanup.revisions
- ? await cleanup.revisions.compactRevisions({
- batchSize: options.batchSize,
- graceMs: REVISION_COMPACTION_GRACE_MS
- })
- : null
- const rateLimits = cleanup.rateLimits
- ? await cleanup.rateLimits.cleanupExpired(new Date(Date.now() - 24 * 60 * 60_000))
- : 0
- return { uploads, documents, revisions, rateLimits }
- }
+ run: () => runCleanup(cleanup, options)
})
}
diff --git a/packages/cloud/src/server/collaboration/index.ts b/packages/cloud/src/server/collaboration/index.ts
index 55cf16df9..864bd8080 100644
--- a/packages/cloud/src/server/collaboration/index.ts
+++ b/packages/cloud/src/server/collaboration/index.ts
@@ -14,6 +14,7 @@ export {
authorizeRelayTicket,
createCollaborationRelay,
createCollaborationStateStore,
+ relayDocumentLookups,
stampAwareness,
type CollaborationRelay,
type CollaborationRelayOptions,
diff --git a/packages/cloud/src/server/collaboration/relay/documents.ts b/packages/cloud/src/server/collaboration/relay/documents.ts
new file mode 100644
index 000000000..0df958c34
--- /dev/null
+++ b/packages/cloud/src/server/collaboration/relay/documents.ts
@@ -0,0 +1,39 @@
+import type { CloudDatabase } from '#cloud/server/db'
+import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'
+import type { CloudPolicy } from '#cloud/server/policy/policy'
+import type { Kysely } from 'kysely'
+
+import type { CollaborationRelayOptions } from './hub'
+
+/** The relay's lookups of a document: its participant limit under `policy`, and its epoch. */
+export function relayDocumentLookups(
+ database: Kysely<CloudDatabase>,
+ policy: CloudPolicy,
+ deploymentMode: 'official' | 'self-hosted'
+): Pick<CollaborationRelayOptions, 'maximumParticipants' | 'currentRoomEpoch'> {
+ return {
+ 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
+ })
+ return limit < 0 ? null : limit
+ },
+ async currentRoomEpoch(documentId) {
+ const document = await database
+ .selectFrom('document')
+ .select('collaborationEpoch')
+ .where('id', '=', documentId)
+ .executeTakeFirst()
+ return document?.collaborationEpoch ?? null
+ }
+ }
+}
diff --git a/packages/cloud/src/server/collaboration/relay/hub.ts b/packages/cloud/src/server/collaboration/relay/hub.ts
index 2c535297f..89f81f7aa 100644
--- a/packages/cloud/src/server/collaboration/relay/hub.ts
+++ b/packages/cloud/src/server/collaboration/relay/hub.ts
@@ -31,6 +31,11 @@ export type RelayConnection = {
export type CollaborationRelayOptions = {
authSecret: string
store: CollaborationStateStore
+ /**
+ * The one document this relay serves, for runtimes that run a relay per document; tickets for
+ * any other document are refused.
+ */
+ documentId?: string
/**
* The most one socket message may carry. An editor's larger frames arrive as fragments joined
* up to `MAX_COLLAB_MESSAGE_BYTES`; anyone else's frame must fit in one message.
@@ -366,6 +371,10 @@ export function createCollaborationRelay(options: CollaborationRelayOptions) {
socket.close(RELAY_CLOSE.unauthorized, 'Invalid collaboration ticket')
return
}
+ if (options.documentId !== undefined && authorization.documentId !== options.documentId) {
+ socket.close(RELAY_CLOSE.unauthorized, 'Ticket is for a different document')
+ return
+ }
if (state.closed) return
if (peer) {
// A refreshed ticket keeps the peer in its room as the same person; a lowered
diff --git a/packages/cloud/src/server/collaboration/relay/index.ts b/packages/cloud/src/server/collaboration/relay/index.ts
index 045d94531..71dd82219 100644
--- a/packages/cloud/src/server/collaboration/relay/index.ts
+++ b/packages/cloud/src/server/collaboration/relay/index.ts
@@ -1,5 +1,6 @@
export { authorizeRelayTicket, type RelayAuthorization } from './authorize'
export { stampAwareness, type StampedAwareness, type VerifiedPresence } from './awareness'
+export { relayDocumentLookups } from './documents'
export {
createCollaborationRelay,
type CollaborationRelay,
diff --git a/packages/cloud/src/server/collaboration/service.ts b/packages/cloud/src/server/collaboration/service.ts
index f438aee7b..b10c7d326 100644
--- a/packages/cloud/src/server/collaboration/service.ts
+++ b/packages/cloud/src/server/collaboration/service.ts
@@ -1,8 +1,9 @@
-import type {
- CollaborationPrincipal,
- CollaborationTicket,
- DocumentPermission,
- ResolveDocumentShareInput
+import {
+ RELAY_DOCUMENT_PARAM,
+ type CollaborationPrincipal,
+ type CollaborationTicket,
+ type DocumentPermission,
+ type ResolveDocumentShareInput
} from '#cloud/contract'
import type { CloudActor } from '#cloud/server/auth'
import type { CloudDatabase } from '#cloud/server/db'
@@ -13,6 +14,7 @@ import type { CloudPolicy } from '#cloud/server/policy/policy'
import type { DocumentSharingService } from '#cloud/server/sharing'
import { base64url, SignJWT } from 'jose'
import type { Kysely } from 'kysely'
+import { withQuery } from 'ufo'
const TICKET_LIFETIME_SECONDS = 5 * 60
@@ -38,7 +40,10 @@ export type CollaborationTicketClaims = {
principal: CollaborationPrincipal
permission: DocumentPermission
roomEpoch: number
- /** The relay that enforces writes; without one the ticket is for peer-to-peer rooms. */
+ /**
+ * The relay that enforces writes; without one the ticket is for peer-to-peer rooms. The ticket's
+ * URL names the document, so a runtime can route the socket to where the room lives.
+ */
relayURL?: string
}
@@ -72,7 +77,7 @@ export async function signCollaborationTicket({
return {
token,
provider: relayURL ? ('relay' as const) : ('trystero' as const),
- ...(relayURL ? { serverURL: relayURL } : {}),
+ ...(relayURL ? { serverURL: withQuery(relayURL, { [RELAY_DOCUMENT_PARAM]: documentId }) } : {}),
...claims,
roomKey,
expiresAt: new Date(expiresAtSeconds * 1000).toISOString()
diff --git a/packages/cloud/src/server/email/index.ts b/packages/cloud/src/server/email/index.ts
index 0c3255518..3d556d235 100644
--- a/packages/cloud/src/server/email/index.ts
+++ b/packages/cloud/src/server/email/index.ts
@@ -1,4 +1,8 @@
-export { createTransactionalEmailService, TransactionalEmailTransportError } from './service'
+export {
+ createTransactionalEmailService,
+ TransactionalEmailTransportError,
+ type TransactionalEmailTransportErrorKind
+} from './service'
export { createInvitationOutbox } from './invitations'
export { startTransactionalEmailWorker } from './worker'
export { decryptTransactionalEmailPayload, encryptTransactionalEmailPayload } from './crypto'
diff --git a/packages/cloud/src/server/index.ts b/packages/cloud/src/server/index.ts
index 3c11098f2..149701758 100644
--- a/packages/cloud/src/server/index.ts
+++ b/packages/cloud/src/server/index.ts
@@ -65,11 +65,15 @@ export {
type CloudServices
} from './app'
export {
+ cleanupPassOptions,
+ createCleanupServices,
createDocumentCleanupService,
createRevisionCompactionService,
createUploadCleanupService,
REVISION_COMPACTION_GRACE_MS,
+ runCleanup,
startCleanupWorker,
+ type CleanupPassOptions,
type CleanupResult,
type CleanupServices,
type CleanupWorker,
@@ -85,6 +89,7 @@ export {
authorizeRelayTicket,
createCollaborationRelay,
createCollaborationStateStore,
+ relayDocumentLookups,
stampAwareness,
type CollaborationRelay,
type CollaborationRelayOptions,
@@ -227,6 +232,7 @@ export {
export {
CLOUD_FEATURE_KEYS,
CloudPolicy,
+ createConfiguredCloudPolicy,
createWorkspaceEntitlementRepository,
DatabaseEntitlementSource,
EntitlementOpenFeatureProvider,
diff --git a/packages/cloud/src/server/policy/configured.ts b/packages/cloud/src/server/policy/configured.ts
new file mode 100644
index 000000000..2eb99edde
--- /dev/null
+++ b/packages/cloud/src/server/policy/configured.ts
@@ -0,0 +1,23 @@
+import type { CloudServerConfig } from '#cloud/server/config'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { Kysely } from 'kysely'
+
+import { DatabaseEntitlementSource } from './database'
+import { StaticEntitlementSource } from './entitlements'
+import { createDefaultCloudPolicy } from './policy'
+import { EntitlementOpenFeatureProvider } from './provider'
+import { staticEntitlementValues } from './static'
+
+/** The policy a deployment configures: its static entitlements, or the database's. */
+export function createConfiguredCloudPolicy(
+ config: Pick<CloudServerConfig, 'staticEntitlements'>,
+ database: Kysely<CloudDatabase>
+) {
+ return createDefaultCloudPolicy(
+ new EntitlementOpenFeatureProvider(
+ config.staticEntitlements
+ ? new StaticEntitlementSource(staticEntitlementValues(config.staticEntitlements))
+ : new DatabaseEntitlementSource(database)
+ )
+ )
+}
diff --git a/packages/cloud/src/server/policy/index.ts b/packages/cloud/src/server/policy/index.ts
index 0976c164b..75ddb2258 100644
--- a/packages/cloud/src/server/policy/index.ts
+++ b/packages/cloud/src/server/policy/index.ts
@@ -13,5 +13,6 @@ export {
type StaticEntitlements,
type StaticEntitlementsInput
} from './static'
+export { createConfiguredCloudPolicy } from './configured'
export { CloudPolicy, createDefaultCloudPolicy } from './policy'
export { createEntitlementService, type EntitlementService } from './service'
diff --git a/packages/cloud/tests/contract/relay.test.ts b/packages/cloud/tests/contract/relay.test.ts
index ce9966222..d53d2e11b 100644
--- a/packages/cloud/tests/contract/relay.test.ts
+++ b/packages/cloud/tests/contract/relay.test.ts
@@ -5,10 +5,12 @@ import {
createRelayServerAssembler,
decodeRelayClientFrame,
decodeRelayServerFrame,
+ defaultRelayURL,
encodeRelayClientFrame,
encodeRelayServerFrame,
RELAY_FRAGMENT_BYTES,
RELAY_MINIMUM_MESSAGE_BYTES,
+ RELAY_PATH,
relayClientMessages,
relayServerMessages,
type RelayClientFrame,
@@ -140,3 +142,12 @@ describe('relay frames', () => {
)
})
})
+
+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/e2e/cloud.ts b/packages/cloud/tests/e2e/cloud.ts
index 3fe36681c..777585ea3 100644
--- a/packages/cloud/tests/e2e/cloud.ts
+++ b/packages/cloud/tests/e2e/cloud.ts
@@ -7,7 +7,7 @@ import {
type CloudFetch,
type CloudUpload
} from '#cloud/client'
-import { createNodeCloudDatabase, createS3ObjectStore } from '#cloud/runtime/node'
+import { createPostgresCloudDatabase, createS3ObjectStore } from '#cloud/runtime/node'
import {
createCloudApp,
createBetterAuthAdapter,
@@ -76,7 +76,7 @@ function appFetch(app: CloudApp): CloudFetch {
app.fetch(input instanceof Request ? input : new Request(input, init))
}
-const database = createNodeCloudDatabase({ connectionString: config.databaseURL })
+const database = createPostgresCloudDatabase({ connectionString: config.databaseURL })
const objects = createS3ObjectStore(config)
try {
const auth = createBetterAuthAdapter(config, database)
diff --git a/packages/cloud/tests/e2e/cloudflare/checks.ts b/packages/cloud/tests/e2e/cloudflare/checks.ts
new file mode 100644
index 000000000..b7de310ef
--- /dev/null
+++ b/packages/cloud/tests/e2e/cloudflare/checks.ts
@@ -0,0 +1,216 @@
+import { textOfSyncReply, textUpdate } from '#cloud-tests/helpers/relay'
+import {
+ COLLAB_ACTIONS,
+ createRelayServerAssembler,
+ decodeRelayServerFrame,
+ defaultRelayURL,
+ MAX_COLLAB_MESSAGE_BYTES,
+ RELAY_CLOSE,
+ RELAY_SERVER_PEER,
+ relayClientMessages,
+ type RelayClientFrame,
+ type RelayServerFrame
+} from '#cloud/contract'
+import { createPostgresCloudDatabase } from '#cloud/runtime/postgres/database'
+import { createCollaborationTicketService, createDocumentSharingService } from '#cloud/server'
+import * as Y from 'yjs'
+
+// Checks a running Cloud Worker (see run.ts): the API and portal answer, and the relay's
+// Durable Object admits ticket holders, keeps the room, and saves it to PostgreSQL.
+const base = process.env.CLOUD_WORKER_URL ?? ''
+const databaseURL = process.env.DATABASE_URL ?? ''
+const authSecret = process.env.BETTER_AUTH_SECRET ?? ''
+
+function check(condition: boolean, message: string): asserts condition {
+ if (!condition) throw new Error(message)
+}
+
+async function until(condition: () => boolean | Promise<boolean>, message: string) {
+ for (let attempt = 0; attempt < 200; attempt++) {
+ if (await condition()) return
+ await Bun.sleep(50)
+ }
+ throw new Error(message)
+}
+
+type Peer = {
+ frames: RelayServerFrame[]
+ closed: { code: number; reason: string } | null
+ send(frame: RelayClientFrame): void
+ close(): void
+}
+
+async function join(url: string, token: string): Promise<Peer> {
+ const socket = new WebSocket(url)
+ socket.binaryType = 'arraybuffer'
+ const assembler = createRelayServerAssembler(() => MAX_COLLAB_MESSAGE_BYTES)
+ const peer: Peer = {
+ frames: [],
+ closed: null,
+ send(frame) {
+ for (const message of relayClientMessages(frame)) socket.send(message)
+ },
+ close: () => socket.close()
+ }
+ socket.addEventListener('message', (event) => {
+ if (!(event.data instanceof ArrayBuffer)) return
+ const assembled = assembler.push(new Uint8Array(event.data))
+ const frame = assembled.type === 'frame' ? decodeRelayServerFrame(assembled.data) : null
+ if (frame) peer.frames.push(frame)
+ })
+ socket.addEventListener('close', (event) => {
+ peer.closed = { code: event.code, reason: event.reason }
+ })
+ await new Promise<void>((resolve, reject) => {
+ socket.addEventListener('open', () => resolve(), { once: true })
+ socket.addEventListener('error', () => reject(new Error(`Could not open ${url}`)), {
+ once: true
+ })
+ })
+ peer.send({ type: 'auth', token })
+ await until(
+ () => peer.closed !== null || peer.frames.some((frame) => frame.type === 'welcome'),
+ 'The relay did not answer a ticket'
+ )
+ return peer
+}
+
+function messages(peer: Peer, namespace: string) {
+ return peer.frames.flatMap((frame) =>
+ frame.type === 'message' && frame.namespace === namespace ? [frame] : []
+ )
+}
+
+/**
+ * Asks the relay for the room until its reply holds the editor's edit. The edit and the request
+ * travel on different sockets, so the first reply can come before the room has the edit.
+ */
+async function servedEdit(peer: Peer, failure: string) {
+ const ask = () =>
+ peer.send({
+ type: 'message',
+ namespace: COLLAB_ACTIONS.syncStep1,
+ target: RELAY_SERVER_PEER,
+ payload: Y.encodeStateVector(new Y.Doc())
+ })
+ const served = () =>
+ messages(peer, COLLAB_ACTIONS.syncReply).find(
+ (reply) => textOfSyncReply(reply.payload) === 'hello from Workers'
+ )
+ let asked = 1
+ ask()
+ await until(() => {
+ if (served()) return true
+ if (messages(peer, COLLAB_ACTIONS.syncReply).length >= asked) {
+ asked++
+ ask()
+ }
+ return false
+ }, failure)
+ check(served()?.from === RELAY_SERVER_PEER, 'The sync reply did not come from the relay')
+}
+
+async function seed(database: ReturnType<typeof createPostgresCloudDatabase>) {
+ const workspaceId = crypto.randomUUID()
+ const documentId = crypto.randomUUID()
+ await database
+ .insertInto('workspace')
+ .values({
+ id: workspaceId,
+ name: 'Workers',
+ slug: `workers-${workspaceId}`,
+ createdBy: 'owner'
+ })
+ .execute()
+ await database
+ .insertInto('workspaceMember')
+ .values([
+ { workspaceId, userId: 'owner', role: 'admin' },
+ { workspaceId, userId: 'viewer', role: 'viewer' }
+ ])
+ .execute()
+ await database
+ .insertInto('document')
+ .values({ id: documentId, workspaceId, name: 'Relay', createdBy: 'owner' })
+ .execute()
+ return documentId
+}
+
+for (const path of ['/health', '/ready', '/.well-known/openpencil']) {
+ const response = await fetch(`${base}${path}`)
+ check(response.ok, `${path} answered HTTP ${response.status}`)
+}
+const page = await fetch(`${base}/auth/sign-in`)
+check(
+ page.ok && (page.headers.get('content-type') ?? '').startsWith('text/html'),
+ `The portal page answered HTTP ${page.status}`
+)
+check(
+ page.headers.get('content-security-policy') === "frame-ancestors 'none'",
+ 'The portal page is missing its headers'
+)
+const missing = await fetch(`${base}/api/collaboration/relay`)
+check(missing.status === 426, `A plain request to the relay answered HTTP ${missing.status}`)
+
+const database = createPostgresCloudDatabase({ connectionString: databaseURL })
+try {
+ const tickets = createCollaborationTicketService({
+ database,
+ sharing: createDocumentSharingService(database),
+ authSecret,
+ relayURL: defaultRelayURL(base)
+ })
+ const user = (userId: string) => ({ userId, name: userId, email: `${userId}@example.com` })
+ const documentId = await seed(database)
+ const ticket = await tickets.issueUserTicket(user('owner'), documentId)
+ const url = ticket.serverURL ?? ''
+
+ const editor = await join(url, ticket.token)
+ check(
+ editor.closed === null,
+ `The relay closed the editor: ${editor.closed?.code} ${editor.closed?.reason}`
+ )
+ editor.send({
+ type: 'message',
+ namespace: COLLAB_ACTIONS.yjsUpdate,
+ target: null,
+ payload: textUpdate('hello from Workers')
+ })
+
+ const viewer = await join(url, (await tickets.issueUserTicket(user('viewer'), documentId)).token)
+ await servedEdit(viewer, 'The relay did not serve the edit to a newcomer')
+
+ // Another document's ticket on this document's relay is refused.
+ const other = await seed(database)
+ const stranger = await join(url, (await tickets.issueUserTicket(user('owner'), other)).token)
+ await until(() => stranger.closed !== null, 'The relay admitted another document’s ticket')
+ check(
+ stranger.closed?.code === RELAY_CLOSE.unauthorized,
+ `Another document’s ticket closed with ${stranger.closed?.code}`
+ )
+
+ editor.close()
+ viewer.close()
+ await until(async () => {
+ const saved = await database
+ .selectFrom('documentCollaborationState')
+ .select('state')
+ .where('documentId', '=', documentId)
+ .executeTakeFirst()
+ return saved !== undefined
+ }, 'The relay did not save the room')
+
+ // Nobody is in the room now, so a newcomer gets it from what the relay saved.
+ const returning = await join(
+ url,
+ (await tickets.issueUserTicket(user('viewer'), documentId)).token
+ )
+ await servedEdit(returning, 'The reopened room lost the edit')
+ returning.close()
+
+ const scheduled = await fetch(`${base}/__scheduled?cron=${encodeURIComponent('*/5 * * * *')}`)
+ check(scheduled.ok, `The scheduled run answered HTTP ${scheduled.status}`)
+ console.log('Cloud Worker checks passed')
+} finally {
+ await database.destroy()
+}
diff --git a/packages/cloud/tests/e2e/cloudflare/run.ts b/packages/cloud/tests/e2e/cloudflare/run.ts
new file mode 100644
index 000000000..4f2283dad
--- /dev/null
+++ b/packages/cloud/tests/e2e/cloudflare/run.ts
@@ -0,0 +1,124 @@
+import { copyFile, mkdir, writeFile } from 'node:fs/promises'
+
+import { cloudDeployPath, cloudPackagePath } from '#cloud-tests/helpers/paths'
+import { composeCommand, runProcess } from '#cloud-tests/helpers/process'
+
+// Runs the Cloudflare Worker under `wrangler dev`, against PostgreSQL and SeaweedFS from Compose,
+// then checks it from outside as clients reach it: see checks.ts. The Worker is a copy of the
+// deploy/cloudflare template in deploy/generated, with a TOML for these services, as a
+// self-hosted deployment would be.
+const deployDirectory = cloudDeployPath()
+const compose = composeCommand(`openpencil-cloud-workers-e2e-${process.pid}`, 'compose.yml')
+const portOffset = process.pid % 1_000
+const workerPort = 23_000 + portOffset
+const databaseURL = `postgresql://openpencil:[email protected]:${20_000 + portOffset}/openpencil`
+const s3Endpoint = `http://127.0.0.1:${21_000 + portOffset}`
+const secrets = {
+ BETTER_AUTH_SECRET: 'cloudflare-e2e-secret-at-least-32-characters',
+ S3_ACCESS_KEY_ID: 'openpencil',
+ S3_SECRET_ACCESS_KEY: 'openpencil-development-secret'
+}
+const environment = {
+ ...process.env,
+ S3_BUCKET: 'openpencil',
+ POSTGRES_PORT: String(20_000 + portOffset),
+ SEAWEEDFS_S3_PORT: String(21_000 + portOffset),
+ SEAWEEDFS_MASTER_PORT: String(22_000 + portOffset),
+ ...secrets,
+ DATABASE_URL: databaseURL,
+ CLOUD_WORKER_URL: `http://127.0.0.1:${workerPort}`,
+ OPENPENCIL_CLOUD_CONFIG: cloudDeployPath('generated/openpencil-cloud.toml'),
+ CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE: databaseURL
+}
+
+const config = `schema_version = 2
+
+[deployment]
+mode = "self-hosted"
+public_url = "${environment.CLOUD_WORKER_URL}"
+indexing = "deny"
+trusted_origins = []
+
+[database]
+
+[authentication]
+enrollment_mode = "open"
+admin_notification_emails = []
+
+[authentication.mfa]
+deployment_admin_required = false
+totp_enabled = false
+passkeys_enabled = false
+recovery_codes_enabled = false
+
+[authentication.email_password]
+enabled = false
+
+[authentication.trusted_proxies]
+headers = []
+addresses = []
+
+[object_storage]
+endpoint = "${s3Endpoint}"
+region = "us-east-1"
+bucket = "openpencil"
+force_path_style = true
+checksum_verification = "metadata"
+
+[email]
+transport = "none"
+
+[entitlements]
+source = "static"
+
+[entitlements.collaboration]
+enabled = true
+maximum_participants = 10
+`
+
+async function run(command: string[], cwd = deployDirectory): Promise<void> {
+ await runProcess(command, { cwd, environment })
+}
+
+async function untilServing(worker: Bun.Subprocess) {
+ for (let attempt = 0; attempt < 600; attempt++) {
+ if (worker.exitCode !== null) throw new Error(`wrangler dev exited with ${worker.exitCode}`)
+ const health = await fetch(`${environment.CLOUD_WORKER_URL}/health`).catch(() => null)
+ if (health?.ok) return
+ await Bun.sleep(100)
+ }
+ throw new Error('The Worker did not start')
+}
+
+let worker: Bun.Subprocess | null = null
+try {
+ await mkdir(cloudDeployPath('generated'), { recursive: true })
+ for (const file of ['wrangler.jsonc', 'worker.ts']) {
+ await copyFile(cloudDeployPath('cloudflare', file), cloudDeployPath('generated', file))
+ }
+ await writeFile(environment.OPENPENCIL_CLOUD_CONFIG, config)
+ await run([...compose, 'up', '-d', '--wait', 'postgres', 'seaweedfs'])
+ await run([...compose, 'run', '--rm', 'seaweedfs-init'])
+ await run(['bun', cloudPackagePath('src/runtime/node/migrate.ts')], cloudPackagePath())
+ worker = Bun.spawn(
+ [
+ 'bunx',
+ 'wrangler',
+ 'dev',
+ '--ip',
+ '127.0.0.1',
+ '--port',
+ String(workerPort),
+ '--test-scheduled',
+ '--show-interactive-dev-session=false',
+ ...Object.entries(secrets).flatMap(([name, value]) => ['--var', `${name}:${value}`])
+ ],
+ { cwd: cloudDeployPath('generated'), env: environment, stdout: 'inherit', stderr: 'inherit' }
+ )
+ await untilServing(worker)
+ await run(['bun', cloudPackagePath('tests/e2e/cloudflare/checks.ts')], cloudPackagePath())
+} finally {
+ worker?.kill()
+ await worker?.exited
+ await run([...compose, 'down', '--volumes'])
+}
diff --git a/packages/cloud/tests/integration/server/collaboration/relay.test.ts b/packages/cloud/tests/integration/server/collaboration/relay.test.ts
index b5e6a2309..ded209b33 100644
--- a/packages/cloud/tests/integration/server/collaboration/relay.test.ts
+++ b/packages/cloud/tests/integration/server/collaboration/relay.test.ts
@@ -64,7 +64,7 @@ describe('collaboration relay with issued tickets', () => {
const ticket = await context.tickets.issueUserTicket(owner, context.documentId)
expect(ticket).toMatchObject({
provider: 'relay',
- serverURL: relayURL,
+ serverURL: `${relayURL}?document=${context.documentId}`,
serverEnforcedWrites: true
})
diff --git a/packages/cloud/tests/runtime/cloudflare/email.test.ts b/packages/cloud/tests/runtime/cloudflare/email.test.ts
new file mode 100644
index 000000000..099d14be0
--- /dev/null
+++ b/packages/cloud/tests/runtime/cloudflare/email.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ createCloudflareEmailTransport,
+ type CloudflareEmailBinding
+} from '#cloud/runtime/cloudflare/email'
+import { TransactionalEmailTransportError } from '#cloud/server'
+
+const envelope = {
+ deliveryId: 'delivery-id',
+ subject: 'Welcome',
+ html: '<p>Welcome</p>',
+ text: 'Welcome',
+ headers: { 'X-OpenPencil-Delivery-ID': 'delivery-id' }
+}
+
+function failingWith(code?: string): CloudflareEmailBinding {
+ return {
+ async send() {
+ throw Object.assign(new Error('Rejected'), code ? { code } : {})
+ }
+ }
+}
+
+describe('Cloudflare Email Service transport', () => {
+ test('sends HTML, text, and headers through the Worker binding', async () => {
+ const sent: unknown[] = []
+ const transport = createCloudflareEmailTransport({
+ async send(message) {
+ sent.push(message)
+ return { messageId: 'cloudflare-message-id' }
+ }
+ })
+ expect(await transport.send(envelope)).toMatchObject({
+ transportMessageId: 'cloudflare-message-id'
+ })
+ expect(sent).toEqual([
+ {
+ from: envelope.from,
+ to: envelope.to,
+ subject: envelope.subject,
+ html: envelope.html,
+ text: envelope.text,
+ headers: envelope.headers
+ }
+ ])
+ })
+
+ test('tells a delivery to stop, wait, or retry by the error code', async () => {
+ const kinds = await Promise.all(
+ ['E_RECIPIENT_SUPPRESSED', 'E_SENDER_NOT_VERIFIED', 'E_DAILY_LIMIT_EXCEEDED', undefined].map(
+ (code) =>
+ createCloudflareEmailTransport(failingWith(code))
+ .send(envelope)
+ .catch((error: unknown) => error)
+ )
+ )
+ for (const error of kinds) expect(error).toBeInstanceOf(TransactionalEmailTransportError)
+ expect(kinds).toMatchObject([
+ { kind: 'suppressed', code: 'E_RECIPIENT_SUPPRESSED' },
+ { kind: 'configuration', code: 'E_SENDER_NOT_VERIFIED' },
+ { kind: 'rate-limited', code: 'E_DAILY_LIMIT_EXCEEDED' },
+ { kind: 'transient', code: 'E_UNKNOWN' }
+ ])
+ })
+})
diff --git a/packages/cloud/tests/runtime/node/portal.test.ts b/packages/cloud/tests/runtime/node/portal.test.ts
index 2b20f1dd2..177626066 100644
--- a/packages/cloud/tests/runtime/node/portal.test.ts
+++ b/packages/cloud/tests/runtime/node/portal.test.ts
@@ -3,16 +3,14 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import { createNodeCloudPortal } from '#cloud/runtime/node/portal'
+import { nodePortalFiles } from '#cloud/runtime/node/portal'
let directory = ''
beforeAll(async () => {
directory = await mkdtemp(join(tmpdir(), 'openpencil-portal-'))
await mkdir(join(directory, 'assets'))
- await writeFile(join(directory, 'cloud.html'), '<!doctype html><title>Portal</title>')
await writeFile(join(directory, 'assets', 'cloud-abc.js'), 'export {}')
- await writeFile(join(directory, 'favicon.svg'), '<svg/>')
await writeFile(join(tmpdir(), 'openpencil-portal-outside.txt'), 'secret')
})
@@ -21,39 +19,20 @@ afterAll(async () => {
await rm(join(tmpdir(), 'openpencil-portal-outside.txt'), { force: true })
})
-const request = (path: string, method = 'GET') =>
- new Request(`https://cloud.example${path}`, { method })
+const request = new Request('https://cloud.example/')
-describe('Node Cloud portal', () => {
- test('serves the page for portal paths, never framed and never cached', async () => {
- const page = await createNodeCloudPortal(directory).page(
- request('/cloud/device?user_code=ABCD')
+describe('Node portal files', () => {
+ test('reads a file with its media type', async () => {
+ const file = await nodePortalFiles(directory)('/assets/cloud-abc.js', request)
+ expect(file?.type).toContain('javascript')
+ expect(new TextDecoder().decode(file?.body instanceof Uint8Array ? file.body : undefined)).toBe(
+ 'export {}'
)
- expect(await page?.text()).toContain('Portal')
- expect(page?.headers.get('Content-Security-Policy')).toBe("frame-ancestors 'none'")
- expect(page?.headers.get('Cache-Control')).toBe('no-cache')
- })
-
- test('leaves other paths and methods to the API', async () => {
- const portal = createNodeCloudPortal(directory)
- expect(await portal.page(request('/api/session'))).toBeNull()
- expect(await portal.page(request('/account', 'POST'))).toBeNull()
- })
-
- test('serves hashed assets as immutable and icons briefly cached', async () => {
- const portal = createNodeCloudPortal(directory)
- const asset = await portal.file(request('/assets/cloud-abc.js'))
- expect(asset?.headers.get('Content-Type')).toContain('javascript')
- expect(asset?.headers.get('Cache-Control')).toContain('immutable')
- const icon = await portal.file(request('/favicon.svg'))
- expect(icon?.headers.get('Content-Type')).toContain('image/svg+xml')
- expect(icon?.headers.get('Cache-Control')).not.toContain('immutable')
})
test('never reads outside its directory or answers missing files', async () => {
- const portal = createNodeCloudPortal(directory)
- expect(await portal.file(request('/..%2Fopenpencil-portal-outside.txt'))).toBeNull()
- expect(await portal.file(request('/assets/missing.js'))).toBeNull()
- expect(await portal.file(request('/cloud.html'))).toBeNull()
+ const files = nodePortalFiles(directory)
+ expect(await files('/..%2Fopenpencil-portal-outside.txt', request)).toBeNull()
+ expect(await files('/assets/missing.js', request)).toBeNull()
})
})
diff --git a/packages/cloud/tests/runtime/node/relay.test.ts b/packages/cloud/tests/runtime/node/relay.test.ts
index f19e17360..b611753f8 100644
--- a/packages/cloud/tests/runtime/node/relay.test.ts
+++ b/packages/cloud/tests/runtime/node/relay.test.ts
@@ -9,7 +9,7 @@ import {
RELAY_PATH,
type RelayServerFrame
} from '#cloud/contract'
-import { attachCollaborationRelay, defaultRelayURL } from '#cloud/runtime/node'
+import { attachCollaborationRelay } from '#cloud/runtime/node'
import { createCollaborationRelay } from '#cloud/server'
const cleanups: (() => Promise<void>)[] = []
@@ -95,12 +95,3 @@ describe('Node collaboration relay listener', () => {
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/runtime/portal/server.test.ts b/packages/cloud/tests/runtime/portal/server.test.ts
new file mode 100644
index 000000000..7c293fe45
--- /dev/null
+++ b/packages/cloud/tests/runtime/portal/server.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudServer, type PortalFiles } from '#cloud/runtime/portal/server'
+
+const files: Record<string, string> = {
+ '/cloud.html': '<!doctype html><title>Portal</title>',
+ '/assets/cloud-abc.js': 'export {}',
+ '/favicon.svg': '<svg/>'
+}
+
+const portal: PortalFiles = async (path) => {
+ const text = files[path]
+ return text === undefined
+ ? null
+ : {
+ body: Uint8Array.from(new TextEncoder().encode(text)),
+ type: path.endsWith('.svg') ? 'image/svg+xml' : 'text/plain'
+ }
+}
+
+const api = {
+ fetch: (request: Request) =>
+ new URL(request.url).pathname === '/api/session'
+ ? Response.json({ ok: true })
+ : new Response('Not found', { status: 404 })
+}
+
+const server = createCloudServer(api, { portal, indexingPolicy: 'deny' })
+const request = (path: string, method = 'GET') =>
+ server.request(new Request(`https://cloud.example${path}`, { method }))
+
+describe('Cloud server', () => {
+ test('serves the page at portal paths, never framed and never cached', async () => {
+ const page = await request('/cloud/device?user_code=ABCD')
+ expect(await page.text()).toContain('Portal')
+ expect(page.headers.get('Content-Security-Policy')).toBe("frame-ancestors 'none'")
+ expect(page.headers.get('Cache-Control')).toBe('no-cache')
+ expect((await request('/account')).status).toBe(200)
+ })
+
+ test('leaves other paths and methods to the API', async () => {
+ expect(await (await request('/api/session')).json()).toEqual({ ok: true })
+ expect((await request('/account', 'POST')).status).toBe(404)
+ })
+
+ test('serves hashed assets as immutable and icons briefly cached where the API has nothing', async () => {
+ const asset = await request('/assets/cloud-abc.js')
+ expect(await asset.text()).toBe('export {}')
+ expect(asset.headers.get('Cache-Control')).toContain('immutable')
+ const icon = await request('/favicon.svg')
+ expect(icon.headers.get('Content-Type')).toBe('image/svg+xml')
+ expect(icon.headers.get('Cache-Control')).not.toContain('immutable')
+ expect((await request('/assets/missing.js')).status).toBe(404)
+ expect((await request('/cloud.html')).status).toBe(404)
+ })
+
+ test('applies the indexing policy to every answer', async () => {
+ for (const path of ['/account', '/api/session', '/favicon.svg']) {
+ expect((await request(path)).headers.get('X-Robots-Tag')).toContain('noindex')
+ }
+ })
+
+ test('answers 404 at portal paths without a portal build', async () => {
+ const bare = createCloudServer(api, { indexingPolicy: 'allow' })
+ expect((await bare.request('https://cloud.example/account')).status).toBe(404)
+ })
+})
diff --git a/packages/cloud/tests/server/collaboration/relay/hub.test.ts b/packages/cloud/tests/server/collaboration/relay/hub.test.ts
index 849cce9f3..ff0bf186e 100644
--- a/packages/cloud/tests/server/collaboration/relay/hub.test.ts
+++ b/packages/cloud/tests/server/collaboration/relay/hub.test.ts
@@ -478,6 +478,13 @@ describe('collaboration relay', () => {
expect(early.closed?.code).toBe(RELAY_CLOSE.unauthorized)
})
+ test('a relay for one document refuses tickets for another', async () => {
+ const { relay: hub } = relay({ documentId })
+ const stranger = await joinTestRelay(hub, crypto.randomUUID())
+ expect(stranger.closed?.code).toBe(RELAY_CLOSE.unauthorized)
+ expect((await join(hub)).closed).toBeNull()
+ })
+
test('keeps a peer that refreshes its ticket and closes one that changes identity', async () => {
const { relay: hub } = relay()
const principal = user('alice')
diff --git a/packages/cloud/tsconfig.json b/packages/cloud/tsconfig.json
index aa0446d65..981bb2634 100644
--- a/packages/cloud/tsconfig.json
+++ b/packages/cloud/tsconfig.json
@@ -26,5 +26,12 @@
}
},
"include": ["src/**/*.ts", "tests/**/*.ts", "deploy/**/*.ts"],
- "exclude": ["node_modules", "dist"]
+ "exclude": [
+ "node_modules",
+ "dist",
+ "src/runtime/cloudflare",
+ "deploy/cloudflare",
+ "deploy/openpencil",
+ "deploy/generated"
+ ]
}
diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.md
index d132a3327..c3836cc63 100644
--- a/packages/docs/development/cloud.md
+++ b/packages/docs/development/cloud.md
@@ -5,7 +5,8 @@ documents. The editor stays local-first: opening, editing, and saving local file
package, a network connection, or an account.
`@open-pencil/cloud` holds the network contracts, a typed client, a runtime-neutral Hono server, and
-the Node runtime that wires PostgreSQL, S3-compatible storage, SMTP, and background workers into it.
+two runtimes that wire PostgreSQL, S3-compatible storage, email, and background work into it: a Node
+process, and Cloudflare Workers.
```mermaid
flowchart LR
@@ -30,6 +31,13 @@ flowchart LR
| `@open-pencil/cloud/server` | Hono routes and services; every dependency is injected |
| `@open-pencil/cloud/runtime/node` | PostgreSQL, S3, SMTP, the HTTP listener, workers, and operator commands |
+The Cloudflare runtime, `src/runtime/cloudflare`, isn't a subpath: Wrangler bundles it from
+a deployment folder, type-checked against the Workers types by its own `tsconfig.json`.
+`deploy/cloudflare` is the folder self-hosters copy; the official deployments are filled-in copies
+under `deploy/openpencil/<target>`, which the Deploy Cloud workflow deploys with the secrets of the
+`cloud-<target>` GitHub environment. A new target needs its folder, that environment, and an option
+in the workflow.
+
The server never imports `pg`, opens a listener, runs migrations, or starts timers; runtimes do.
Browser code imports only `contract` and `client`, so it never pulls in server dependencies.
@@ -158,6 +166,11 @@ a ticket, a full room, or a frame past those limits, leaves the room: the docume
is not editing live and offers to rejoin, a viewer stays read-only, and an editor saves on its own,
since a tab that was not the room's saver had its edits counted as saved by the room.
+Each runtime decides where rooms live. The Node process holds every room in one relay. On
+Cloudflare, a Durable Object per document holds that document's rooms, and the Worker routes a
+socket to it by the document named in the ticket's relay URL (`?document=`), since the ticket itself
+arrives only after the upgrade; the object refuses tickets for any other document.
+
A Cloud room names its images instead of carrying them: an editor stores an image it adds in the
document's workspace and puts only its SHA-256 in the room's `imageRefs` map, and every peer loads
the images it lacks through links the server signs for anyone who may view the document, or for a
@@ -192,8 +205,10 @@ provider or a second sign-in step, it opens them in a browser and gets the perso
`CLOUD_PORTAL_PAGE_ROOTS` in the contract lists the page paths, and every runtime serves
`cloud.html` at and below them with `frame-ancestors 'none'`, so the approval page cannot be
-framed. The Node runtime serves the build named by `OPENPENCIL_CLOUD_PORTAL_DIR`, answering portal
-pages before the API and portal assets only where the API returns 404. `bun run cloud:dev` keeps a
+framed. Both runtimes put the API behind the same Hono router, `createCloudServer` in
+`src/runtime/portal`, which answers portal pages before the API and portal assets only where the
+API returns 404; Node reads the build named by `OPENPENCIL_CLOUD_PORTAL_DIR`, and the Worker reads
+its static assets. `bun run cloud:dev` keeps a
watched portal build next to the server.
## Editor client
@@ -276,7 +291,8 @@ hashed, namespaced keys, so limits hold across instances. Better Auth keeps its
Vue Email renders matching HTML and plain-text bodies. Email goes through a PostgreSQL outbox: the
row is written in the same transaction as the change that caused it, payloads are encrypted at rest,
and a worker claims bounded batches with retries. The Node runtime sends through SMTP with
-Nodemailer; `email.transport = "none"` disables delivery.
+Nodemailer. On Cloudflare, Email Service sends what a request queued once the request finishes, and
+a Cron Trigger retries the rest; `email.transport = "none"` disables delivery.
## Tests
@@ -288,7 +304,9 @@ Nodemailer; `email.transport = "none"` disables delivery.
`bun run test:cloud` type-checks the package and runs unit and integration tests. The end-to-end
runners start PostgreSQL and SeaweedFS (or Garage) in an isolated Compose project, exercise presigned
-and multipart uploads and the full revision flow, and remove the project afterwards.
+and multipart uploads and the full revision flow, and remove the project afterwards. `test:e2e:cloudflare`
+runs the Worker under `wrangler dev` against the same services and checks the API, the portal, and
+the relay's Durable Object from outside.
## Decisions
@@ -401,3 +419,10 @@ and the same check serves the official service and self-hosted ones. Entitlement
token is signed, so a plan change reaches the service within one token lifetime; asking Cloud on
every request would have made model calls depend on Cloud's database. Entitlements are pushed to
Cloud rather than read from billing, so documents keep opening when billing is down.
+
+**2026-10 · On Cloudflare, a Durable Object per document runs the relay.** The relay holds a room's
+Yjs document and its peers in memory, which a stateless Worker can't, and keeping every epoch of a
+document in one object lets a restore or a version change reach all its rooms in one call. Routing
+needs the document before the ticket arrives, so the ticket's relay URL names it. Objects keep their
+sockets without hibernation, so the relay runs unchanged; hibernating would need the relay to
+rebuild rooms and peers on every wake.
diff --git a/packages/docs/reference/self-hosting-cloud.md b/packages/docs/reference/self-hosting-cloud.md
index b8499abe7..09a2e9f7a 100644
--- a/packages/docs/reference/self-hosting-cloud.md
+++ b/packages/docs/reference/self-hosting-cloud.md
@@ -1,11 +1,11 @@
---
title: Self-hosting OpenPencil Cloud
-description: Run your own OpenPencil Cloud server with PostgreSQL and an S3-compatible bucket.
+description: Run your own OpenPencil Cloud server with PostgreSQL and an S3-compatible bucket, as a Node process or on Cloudflare Workers.
---
# Self-hosting OpenPencil Cloud
-OpenPencil Cloud is one Node 22+ process in front of PostgreSQL 15 or later and an S3-compatible object store, with optional SMTP for email. The same process serves the API, the collaboration relay, and the server's own pages for signing in, account security, and administration. People connect to it from the editor as described in [OpenPencil Cloud](/user-guide/openpencil-cloud).
+OpenPencil Cloud is one Node 22+ process in front of PostgreSQL 15 or later and an S3-compatible object store, with optional SMTP for email. The same process serves the API, the collaboration relay, and the server's own pages for signing in, account security, and administration. It also runs on [Cloudflare Workers](#cloudflare-workers) with the same configuration. People connect to it from the editor as described in [OpenPencil Cloud](/user-guide/openpencil-cloud).
## Build
@@ -54,6 +54,18 @@ Either way, the desktop app connects to the server directly, and the web editor
- Forward WebSocket upgrades for `/api/collaboration/relay`. Collaboration tickets name the relay at `public_url` with a `ws:` or `wss:` scheme; set `[collaboration] relay_url` when clients reach it elsewhere.
- The object store must accept presigned uploads from the editor's origins: allow `PUT` and `GET` from `trusted_origins` in its CORS rules, with the `Range` request header, which Home uses to read a document's preview without downloading the whole file.
+## Cloudflare Workers
+
+On Cloudflare a Worker serves the API and the portal, a Durable Object for each document runs its collaboration rooms, Hyperdrive connects to PostgreSQL, and a Cron Trigger every five minutes runs cleanup and retries email. [`packages/cloud/deploy/cloudflare`](https://github.com/open-pencil/open-pencil/tree/master/packages/cloud/deploy/cloudflare) is the deployment to copy: a Wrangler configuration and the Worker's entry, which reads `openpencil-cloud.toml` from the same folder.
+
+1. Copy the folder beside it, for example to `packages/cloud/deploy/mine`, so its relative paths still reach the runtime and the portal build.
+2. Create a Hyperdrive configuration for the database with `wrangler hyperdrive create`, and put its ID, your domain, and a Worker name in the copy's `wrangler.jsonc`.
+3. Add your TOML as `openpencil-cloud.toml` in the copy; Wrangler bundles it as text. Leave `[database]` empty, since `DATABASE_URL` comes from Hyperdrive, and trust `cf-connecting-ip` under `[authentication.trusted_proxies]`.
+4. Migrate from a checkout, with that TOML as `OPENPENCIL_CLOUD_CONFIG` and a direct connection string as `DATABASE_URL`: `bun --filter @open-pencil/cloud migrate`. The Worker never migrates, so do this before every deploy.
+5. Build the portal with `bun run build:packages && bun run build:cloud-portal`, then deploy from the copy with `bunx wrangler deploy --secrets-file <file>`, where the JSON file holds the secrets the TOML names.
+
+The operator commands below work the same way, from a checkout with a direct connection. The `[workers]` intervals don't apply: mail a request queues is sent when the request finishes, and the Cron Trigger handles the rest.
+
## The first administrator
Set `authentication.enrollment_mode = "approval"` for a controlled deployment: a verified identity then creates a pending request that an administrator reviews. Startup never grants roles, so bootstrap the first operator from a repository checkout that reads the same configuration and secrets and can reach the server's database at `DATABASE_URL`:
@@ -80,11 +92,11 @@ Each runs from a repository checkout with the same `OPENPENCIL_CLOUD_CONFIG` and
## Email
-Set `email.transport = "smtp"` with an `[email.smtp]` table, or `"none"` to send nothing; invitations still work through their links. Messages go through an encrypted outbox in PostgreSQL, tuned under `[workers.email]`. Delivery records that the SMTP server accepted a message, not that it reached the inbox.
+Set `email.transport = "smtp"` with an `[email.smtp]` table, `"cloudflare"` on Cloudflare Workers to send through Cloudflare Email Service from an address on a domain onboarded to it (the Worker needs the `send_email` binding named `EMAIL`, and sending to addresses you haven't verified needs Workers Paid), or `"none"` to send nothing; invitations still work through their links. Messages go through an encrypted outbox in PostgreSQL, tuned under `[workers.email]`. Delivery records that the SMTP server accepted a message, not that it reached the inbox.
## Storage
-Any S3-compatible store works; the project tests against SeaweedFS and Garage. Keep `object_storage.checksum_verification = "metadata"` for stores without native SHA-256 checksums: OpenPencil stores each document's digest as object metadata and verifies it before committing a revision. For Garage, set `region = "garage"` and `force_path_style = true`, and leave server-side encryption unset.
+Any S3-compatible store works; the project tests against SeaweedFS and Garage. Keep `object_storage.checksum_verification = "metadata"` for stores without native SHA-256 checksums: OpenPencil stores each document's digest as object metadata and verifies it before committing a revision. For Garage, set `region = "garage"` and `force_path_style = true`, and leave server-side encryption unset. For Cloudflare R2, use the endpoint `https://<account ID>.r2.cloudflarestorage.com` with `region = "auto"` and `force_path_style = false`.
Revision keys are immutable, so bucket versioning isn't needed, but it isn't a backup either. Size `[workers.cleanup]` for your upload volume and retention, or set `enabled = false` and run `cleanup` from a scheduler.