Skip to content

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

feat(cloud): add the self-hostable Cloud server package (#1053)

Danila Poyarkov3fbad48f2992
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 177e96433..683b91d4d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -285,9 +285,28 @@ jobs:
- name: Typecheck and test the feedback Worker against a local D1
run: bun run test:feedback
+ cloud-tests:
+ name: Cloud package
+ needs: changes
+ if: needs.changes.outputs.scope == 'code'
+ timeout-minutes: 10
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
+ with:
+ persist-credentials: false
+
+ - uses: ./.github/actions/setup-bun
+
+ - name: Generate package declarations
+ run: bun run build:packages
+
+ - name: Typecheck and run Cloud unit and integration tests
+ run: bun run test:cloud
+
result:
name: CI result
- needs: [changes, commit-messages, documentation, source-quality, package-quality, repository-quality, storybook, native-test-contracts, unit-tests, feedback-tests]
+ needs: [changes, commit-messages, documentation, source-quality, package-quality, repository-quality, storybook, native-test-contracts, unit-tests, feedback-tests, cloud-tests]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 3
diff --git a/.gitignore b/.gitignore
index c557696fc..7c8c67204 100644
--- a/.gitignore
+++ b/.gitignore
@@ -96,3 +96,7 @@ scratch/
# Feedback Worker local state and secrets
packages/feedback/.wrangler/
packages/feedback/.dev.vars
+
+# OpenPencil Cloud local and build outputs
+packages/cloud/deploy/generated/
+packages/cloud/dist-standalone/
diff --git a/.gitleaks.toml b/.gitleaks.toml
index 8c061273c..e24a5ac87 100644
--- a/.gitleaks.toml
+++ b/.gitleaks.toml
@@ -13,6 +13,7 @@ paths = [
'''^desktop/target/''',
'''^packages/[^/]+/dist/''',
'''^packages/docs/\.vitepress/cache/''',
+ '''^packages/cloud/dist-standalone/''',
'''^test-results/''',
'''^scratch/'''
]
@@ -35,6 +36,19 @@ regexTarget = "line"
paths = ['''tests/e2e/chat/panel\.spec\.ts''']
regexes = ['''sk-or-test-key-12345''']
+[[allowlists]]
+description = "The local Garage profile's fixed RPC secret"
+regexTarget = "line"
+paths = ['''packages/cloud/deploy/garage/garage\.toml''']
+regexes = [
+ '''rpc_secret\s*=\s*"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"'''
+]
+
+[[allowlists]]
+description = "Cloud test fixtures' made-up auth secrets"
+paths = ['''packages/cloud/tests/.*\.ts''']
+regexes = ['''^[a-z-]+-secret-at-least-32-characters(-long)?$''']
+
[[allowlists]]
description = "Figma fixture identifiers are public test metadata"
regexTarget = "line"
diff --git a/AGENTS.md b/AGENTS.md
index f457048fe..9df3c1913 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -6,8 +6,8 @@ This file holds the repository map and the rules that apply everywhere. Rules fo
## Map
-| Path | Owns | Guide |
-| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
+| Path | Owns | Guide |
+| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
| `packages/scene-graph` | Framework-neutral graph, node types, geometry, copy/snap/undo, variables, instances, hit testing, plus the shared primitives formats need: color conversion and management, CSS value parsing, text/layout direction | `packages/scene-graph/AGENTS.md` |
| `packages/pen` | Pencil.dev `.pen` model, parser, SceneGraph adapter | — |
| `packages/kiwi` | SceneGraph-independent Kiwi schema/runtime, codecs, containers, parse helpers | `packages/fig/AGENTS.md` |
@@ -21,6 +21,7 @@ This file holds the repository map and the rules that apply everywhere. Rules fo
| `packages/mcp` | stdio and Hono HTTP MCP server reusing Core tools | `packages/mcp/AGENTS.md` |
| `packages/harness` | Optional Node companion for HarnessAgent sessions | `packages/harness/AGENTS.md` |
| `packages/feedback` | Cloudflare Worker at `feedback.openpencil.dev`: daily ping counts, opt-in usage stats proxied to PostHog, Cloud waitlist; its contract defines every field the app may send | `packages/feedback/AGENTS.md` |
+| `packages/cloud` | Optional self-hostable backend: contracts, typed client, Hono server, Node runtime, PostgreSQL migrations, transactional email | `packages/cloud/AGENTS.md` |
| `packages/docs` | Published VitePress site | `packages/docs/AGENTS.md` |
| `src` | Tauri/Vite app: services and state in `src/app/**`, views in `src/views/**`, UI in `src/components/**` | `src/AGENTS.md` |
| `desktop` | Tauri v2 shell, capabilities, native credentials, menus | `desktop/AGENTS.md` |
@@ -48,7 +49,7 @@ Before a PR run `bun run check`, `bun run format`, `bun run test:unit`, and `bun
- Across package/app boundaries import the owning package's public exports, never workspace internals or forwarding-only shims. `@open-pencil/scene-graph` owns graph types and primitives; `@open-pencil/kiwi` owns low-level Kiwi/FIG helpers; `@open-pencil/core` provides the compatibility barrel plus the subpaths listed in `packages/core/package.json`.
- `bun run check:arch` enforces: public workspace exports, framework-neutral Core, no app services in views or shared UI, property-panel internals scoped to that panel.
- The app, CLI, MCP server, and Vue SDK build layers from authored content (HTML, JSX, `.pen`) only through Core: IO `readDocument`, `readHTMLDocument`, `sceneGraphFromStyledHTML`, or `@open-pencil/core/design-jsx`, which lay the layers out. Format packages' own builders, such as `htmlToSceneGraph` or `parsePenFile`, skip that; `open-pencil/no-graph-builders-in-front-ends` (`check:arch`) rejects them outside Core.
-- Package aliases are `#core/*`, `#fig/*`, `#vue/*`, `#cli/*`, `#mcp/*`, `#dom-css/*`, `#design-jsx/*`, `#emit/*`; a package's own tests use `#core-tests/*`, `#fig-tests/*`, and `#dom-css-tests/*`; the app uses `@/`. Prefer clear relative imports nearby. Never escape an alias root with `../` (for example `#tests/../vite`); fix module ownership instead.
+- Package aliases are `#core/*`, `#fig/*`, `#vue/*`, `#cli/*`, `#mcp/*`, `#cloud/*`, `#dom-css/*`, `#design-jsx/*`, `#emit/*`; a package's own tests use `#core-tests/*`, `#fig-tests/*`, `#dom-css-tests/*`, and `#cloud-tests/*`; the app uses `@/`. Prefer clear relative imports nearby. Never escape an alias root with `../` (for example `#tests/../vite`); fix module ownership instead.
- Never drill with `../../`: one `../` to a sibling folder is fine, two or more means an alias. This holds in tests as much as in source — a test reaches its package's source through `#<pkg>/*` and its own helpers through `#<pkg>-tests/*`. `open-pencil/no-deep-parent-relative-imports` enforces it for imports and `open-pencil/no-deep-parent-relative-paths` for paths built from `import.meta`; a new test directory must be added to `lint:structure` so the rules reach it.
- Reuse named types from `@open-pencil/scene-graph`; do not respell `Color`, `Vector`, `SceneNode`, `Effect`, `Fill`, or `Stroke`.
diff --git a/bun.lock b/bun.lock
index bf9a72ba9..017811b9c 100644
--- a/bun.lock
+++ b/bun.lock
@@ -13,7 +13,7 @@
"@ai-sdk/vue": "^4.0.127",
"@atlaskit/pragmatic-drag-and-drop": "^1.8.1",
"@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.2.0",
- "@aws-sdk/client-s3": "^3.1147.0",
+ "@aws-sdk/client-s3": "^3.1149.0",
"@chenglou/pretext": "^0.0.7",
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
@@ -198,6 +198,45 @@
"@types/bun": "^1.3.14",
},
},
+ "packages/cloud": {
+ "name": "@open-pencil/cloud",
+ "version": "0.15.1",
+ "dependencies": {
+ "@aws-sdk/client-s3": "^3.1149.0",
+ "@aws-sdk/s3-request-presigner": "^3.1149.0",
+ "@better-auth/passkey": "1.7.7",
+ "@better-auth/utils": "0.4.2",
+ "@hono/node-server": "^1.19.17",
+ "@noble/hashes": "^2.4.0",
+ "@open-pencil/feedback": "workspace:*",
+ "@open-pencil/scene-graph": "workspace:*",
+ "@openfeature/server-sdk": "^1.23.0",
+ "@vue-email/components": "^0.0.21",
+ "@vue-email/render": "^0.0.9",
+ "better-auth": "1.7.7",
+ "es-toolkit": "^1.52.0",
+ "hono": "^4.13.13",
+ "hono-rate-limiter": "^0.5.3",
+ "jose": "^6.2.8",
+ "kysely": "^0.29.6",
+ "nodemailer": "^9.0.5",
+ "smol-toml": "^1.8.0",
+ "valibot": "^1.5.0",
+ "vue": "^3.5.43",
+ },
+ "devDependencies": {
+ "@electric-sql/pglite": "0.4.1",
+ "@types/bun": "^1.3.14",
+ "@types/nodemailer": "^8.0.1",
+ "@types/pg": "^8.21.0",
+ "kysely-pglite-dialect": "1.3.1",
+ "tsdown": "^0.22.14",
+ "typescript": "~5.8.3",
+ },
+ "optionalDependencies": {
+ "pg": "^8.23.0",
+ },
+ },
"packages/core": {
"name": "@open-pencil/core",
"version": "0.16.0",
@@ -595,6 +634,15 @@
"valibot": "^1.5.0",
},
},
+ "tools/dev/cloud": {
+ "name": "@open-pencil/cloud-tools",
+ "dependencies": {
+ "@open-pencil/cloud": "workspace:*",
+ "@open-pencil/package-artifacts-tools": "workspace:*",
+ "@open-pencil/scene-graph": "workspace:*",
+ "smol-toml": "^1.8.0",
+ },
+ },
"tools/dev/dev-server": {
"name": "@open-pencil/dev-server-tools",
},
@@ -781,43 +829,45 @@
"@aws-crypto/util": ["@aws-crypto/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.222.0", "@smithy/util-utf8": "^2.0.0", "tslib": "^2.6.2" } }, "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ=="],
- "@aws-sdk/checksums": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-x12Q17KYlJAd3nKf8LV5LV0vt8sh8/6YfQLGPtrGnQf/tW4jqxPGq5GPpuVitpQYM3eUR4XB7CbxZf751NMbLw=="],
+ "@aws-sdk/checksums": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.3", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-CcAkVyEUKGngbEqJdVdSc53Iy52+XzVL5NIcTen2BlK8UByNC1DThVtf5VKSrNzyA+SqyTvs+3S+knVBbOUizQ=="],
"@aws-sdk/client-bedrock-runtime": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.977.8", "@aws-sdk/credential-provider-node": "^3.972.80", "@aws-sdk/eventstream-handler-node": "^3.972.33", "@aws-sdk/middleware-eventstream": "^3.972.28", "@aws-sdk/middleware-websocket": "^3.972.51", "@aws-sdk/token-providers": "3.1113.0", "@aws-sdk/types": "^3.974.4", "@smithy/core": "^3.31.1", "@smithy/fetch-http-handler": "^5.6.13", "@smithy/node-http-handler": "^4.9.13", "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-yksECclekh+RPC4t5oS4RnLBGArt8g9if5b/2QQJSr8InX4r3LutS3VPHeEFlEKkwJ+qckKkPZCF2Cmv6hT1wA=="],
- "@aws-sdk/client-s3": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/checksums": "^3.1001.1", "@aws-sdk/core": "^3.978.1", "@aws-sdk/credential-provider-node": "^3.972.84", "@aws-sdk/middleware-sdk-s3": "^3.972.77", "@aws-sdk/signature-v4-multi-region": "^3.996.47", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.12.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-uTrcJxnJKPr8bc1z7cMxopYSQyAm2dPfiMK+UiBr51L8MzimDxHbW/d9GR6X/LFbWDpMzfFPLhB4UohDrCSaPQ=="],
+ "@aws-sdk/client-s3": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/checksums": "^3.1001.3", "@aws-sdk/core": "^3.978.3", "@aws-sdk/credential-provider-node": "^3.972.86", "@aws-sdk/middleware-sdk-s3": "^3.972.79", "@aws-sdk/signature-v4-multi-region": "^3.996.48", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.2", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.12.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-Kg20OP7F+rrWMFjPv/aCsNUt/qDbvh1bLJFQM8k/8fnxowR/DA67qL5KHzWWN5gwJCYplS3KQde6P/knOB+lxg=="],
- "@aws-sdk/core": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.974.6", "@aws-sdk/xml-builder": "^3.972.41", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.35.0", "@smithy/signature-v4": "^5.7.3", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-LbY9aGsEiznDWmUc30Nwv3aIX/+dbwTx8KfS0yOC3NPYMO+O91e6jkT1azf34FwjOndq8/Q+RcVVZz5xnerwdg=="],
+ "@aws-sdk/core": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.974.6", "@aws-sdk/xml-builder": "^3.972.41", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.35.2", "@smithy/signature-v4": "^5.7.4", "@smithy/types": "^4.19.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-nslpzUCTI9b2IQMWSd6mSAXldBexPc8rr0d3dXUutXYFLFaTdsHa2GD7sJdsn3PhyjK0O5K8ypd6zi+RXXPVlg=="],
- "@aws-sdk/credential-provider-env": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-xTKO/FWJPozTIXbozVnVGoNBhaGba8TBcx+KyUjRVeOlXE+dUc7GTR1cLvu0uTdIdmemzaFbqqCshXeZA1fZew=="],
+ "@aws-sdk/credential-provider-env": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.3", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-rsRJcW2iFUhCgclyD6OSbMEaPl8Eu0qSeRZb2uuCK1ViZ66hl5wOe/p6Vr6MO3b+ydyKgFeqza2p6tZThvILlw=="],
- "@aws-sdk/credential-provider-http": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.12.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-u91E/hT8f4d1xy0Jl7VG4nVKJ3lxbrZkoBTeSVoJdWBiSEUMwMS/9+e0H/aJVQV//Lt5wuzP+E69v4aRSsNTmw=="],
+ "@aws-sdk/credential-provider-http": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.3", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.2", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.12.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-pnKdh0Br7OJPj+7qKjzgTfDTFW0RhEMKXNDR2jv9CAM4oHuG/4z3hRh8KtutLfpmItuRtDbKBmwWkDqHwwAWXw=="],
- "@aws-sdk/credential-provider-ini": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/credential-provider-env": "^3.972.72", "@aws-sdk/credential-provider-http": "^3.972.74", "@aws-sdk/credential-provider-login": "^3.972.79", "@aws-sdk/credential-provider-process": "^3.972.72", "@aws-sdk/credential-provider-sso": "^3.973.16", "@aws-sdk/credential-provider-web-identity": "^3.972.78", "@aws-sdk/nested-clients": "^3.997.46", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-ged4KXdBkvIC81bLvNHHuQKdKak/VXhQTR1NWYTTqW0474nlmsxy9O/vlgTIohDDWH3xpBdtVMZRyjb+DnocDA=="],
+ "@aws-sdk/credential-provider-ini": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.3", "@aws-sdk/credential-provider-env": "^3.972.74", "@aws-sdk/credential-provider-http": "^3.972.76", "@aws-sdk/credential-provider-login": "^3.972.81", "@aws-sdk/credential-provider-process": "^3.972.74", "@aws-sdk/credential-provider-sso": "^3.973.18", "@aws-sdk/credential-provider-web-identity": "^3.972.80", "@aws-sdk/nested-clients": "^3.997.48", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.2", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-kcjvAxqQEV8yuwkX58RelNn3ne65o7JgRWf3Z/gVvbi7Xuw1qSDLJlatrLD76+40cmRxmNkLxBoyp/vAQChQ5g=="],
- "@aws-sdk/credential-provider-login": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/nested-clients": "^3.997.46", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-L+Z85anONJd8MaiuraO4wRxATCdEejBZ3K3eymzWI5JPXa9sOS9CkIm72PBKqXKX+Z9p9NGMX5AIMXm0LEflgw=="],
+ "@aws-sdk/credential-provider-login": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.3", "@aws-sdk/nested-clients": "^3.997.48", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-CeQHSbE2CnVdaHIJ/NayRaCecIER+Pm9faUPkmRATO54rCoMTEPSbVieGHzEwvm1dZM2HIs6qQZCznhayNTWJQ=="],
- "@aws-sdk/credential-provider-node": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.72", "@aws-sdk/credential-provider-http": "^3.972.74", "@aws-sdk/credential-provider-ini": "^3.973.17", "@aws-sdk/credential-provider-process": "^3.972.72", "@aws-sdk/credential-provider-sso": "^3.973.16", "@aws-sdk/credential-provider-web-identity": "^3.972.78", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-oHt854odINVwzwsh+c5x69j0ajm4DbqqqVJ+O1ECsCIZeMDAbzFpXItaqP7UZstJj/ATdTk/KFSH0LaNAgV+kA=="],
+ "@aws-sdk/credential-provider-node": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.74", "@aws-sdk/credential-provider-http": "^3.972.76", "@aws-sdk/credential-provider-ini": "^3.973.19", "@aws-sdk/credential-provider-process": "^3.972.74", "@aws-sdk/credential-provider-sso": "^3.973.18", "@aws-sdk/credential-provider-web-identity": "^3.972.80", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.2", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-WNttSyr6e8innPtBSty//CdnqJcgZN6eAbtw3v/CR2IObz6MYZEo8eusdtuCHJ2ujwFqC2bSPHVyhXGHx8HruQ=="],
- "@aws-sdk/credential-provider-process": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-rLIp2xbMjX/k9/od7APpqq1ZgXXnV0pOL1Th3ZsL8Wu0TRtBsDTVS8iPqcfRFcHakFxPvR04OSTv2ka2qOb/2A=="],
+ "@aws-sdk/credential-provider-process": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.3", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-Yj6kZFJQdbR+PygTkqdVLPHHpdDpOS9GCYVcDCuweCRRig9LF24ELQBMfyUw1vspvrZJUfnOGVyMjhaL094ahw=="],
- "@aws-sdk/credential-provider-sso": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/nested-clients": "^3.997.46", "@aws-sdk/token-providers": "3.1138.0", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-IGihaJfFZYacJJr/odqILCoK7W/mvrZ7cuK7ECn3sAu4vLC6u0V8bS7mCGbdugJ8Aum2tnvqmx0F2MRFp2rn9g=="],
+ "@aws-sdk/credential-provider-sso": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.3", "@aws-sdk/nested-clients": "^3.997.48", "@aws-sdk/token-providers": "3.1150.0", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-FnpPhdY4qUGtX/8X6eKxh+uD+9Y19i9FYibgk4SBe0M935s9vocHkHzaxaMNk+YkHmvzgdu8cHA5SCoeU+kkew=="],
- "@aws-sdk/credential-provider-web-identity": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/nested-clients": "^3.997.46", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-/y9WvNtlcPBGLR0qc1a+9J/xtYZfVczvLUOuXaVWylzttH7ewsxwHtjmiJSolNrVSDorIxHGHMU61CbonRkmwA=="],
+ "@aws-sdk/credential-provider-web-identity": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.3", "@aws-sdk/nested-clients": "^3.997.48", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-TJF25Ndwy2HxcVj6oxMgp8qVlJAawlExHYBXqhuC6Zt2m+A7WpdkjBD6QglNbiArlteYljZHEY3R7KKmno6ISA=="],
"@aws-sdk/eventstream-handler-node": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.974.4", "@smithy/core": "^3.31.1", "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-1Dd5WyEE2Kb3HvY44u7Ob16ST2W6iutOqsQ8Y2hUmsL2mAH/STlGS1dS9h3IOE6L7Ld3AR2HzKJ6XeCMOw8Peg=="],
"@aws-sdk/middleware-eventstream": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.974.4", "@smithy/core": "^3.31.1", "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-Z1EDXnS01P7H5jVrUx+/dBqV0m7dta7bSxLclkOuDuS93pNNQm0IcT4YLUbuvWKPYNxbI8aTG0p5Br30GSKDgA=="],
- "@aws-sdk/middleware-sdk-s3": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/signature-v4-multi-region": "^3.996.47", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-E7W2UOeUoc+lg3uIfR/dM7ZwusHwhBQrKMnlkRv4EXRR+C0YtV1pg25xC7GdZIhXH+NAMgZPCbE7o5to2cjFiw=="],
+ "@aws-sdk/middleware-sdk-s3": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.3", "@aws-sdk/signature-v4-multi-region": "^3.996.48", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-UfgAQosf4IEXldMsyntVuHsJnaQzlH6pmkOr6dQy7CaOYSlGz3mWiW4Di7XfQ/kPJP6xE7oMshz1V0E8RqGdRg=="],
"@aws-sdk/middleware-websocket": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.977.8", "@aws-sdk/types": "^3.974.4", "@smithy/core": "^3.31.1", "@smithy/fetch-http-handler": "^5.6.13", "@smithy/signature-v4": "^5.6.12", "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-jdgP3jR5Q96j1jjZ98GGwpGg1CBNFIO2YE+vXg8cg8PvNY4NvgQNYJsqDaRX2PYv5gSUX/+C0D58Fhspj9ELMQ=="],
- "@aws-sdk/nested-clients": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/signature-v4-multi-region": "^3.996.47", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.12.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-oRxtBcka/JGHGs9l9p9IVajGoTP8vTPmoAzdHGy4Qcy9P5vPnDf6nhIeM/COQNY9k/OahImTRaLkHftoXvfcmQ=="],
+ "@aws-sdk/nested-clients": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.3", "@aws-sdk/signature-v4-multi-region": "^3.996.48", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.2", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.12.1", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-B01jdXJtAW/XOiUzGdI2mz67WyEHbGEc9X6Euzw3bjLAa+txTqdZDER4X2FsIEcXzV2ABqudVZ5thali8tCCzQ=="],
+
+ "@aws-sdk/s3-request-presigner": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.3", "@aws-sdk/signature-v4-multi-region": "^3.996.48", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-RukZentLCvhlhpqQxv1LfONz/SkDeNQ/SOie5RFLI9vFKNB89VNUuGo0YVM9XdzMZ0GPoqWaiHg4ZNxbMpAjtQ=="],
- "@aws-sdk/signature-v4-multi-region": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.974.6", "@smithy/signature-v4": "^5.7.3", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-Zk08macMvQTHzQJCLJVkOlviVoqwYMrpXv4lmLN7b7sAbiMoOK7Go0NYdR5UeF+MW8LIbRmwrNy9u/5VvX1U5g=="],
+ "@aws-sdk/signature-v4-multi-region": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.974.6", "@smithy/signature-v4": "^5.7.4", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-cFDXfEbXaGwbnpvR/DyqfxfjxpjXVRVthQLgkwvcfDS5u3+8G9WSj1X1Ag/pTRg/QOeOno1Tq3ycEdrKsCUcOA=="],
- "@aws-sdk/token-providers": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.1", "@aws-sdk/nested-clients": "^3.997.46", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-GpyAr0DD63YOEmYFM6Df+gJuIgC92MMTiBK4FTKfxii5MJ9ge20epR7LyroulscYlG89J+ZB2ivFDPjvfQhzdw=="],
+ "@aws-sdk/token-providers": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.978.3", "@aws-sdk/nested-clients": "^3.997.48", "@aws-sdk/types": "^3.974.6", "@smithy/core": "^3.35.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-wDU36ofhabZYu+d2KSriyDbwzxNoaOp+4dG0p3qkabk7HeALR5nIWyQbjoyJZLn3iqWkv/xNdyUfbfevDVDzzg=="],
"@aws-sdk/types": ["@aws-sdk/[email protected]", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-v/clNZzZnDxGyvpHMOGpJKVXFAExJzUNAAjaWGdcx8QAcXLGwTaOkw33p5SHAi0YAioK32xB3hWwOekRVfmfKg=="],
@@ -1009,6 +1059,26 @@
"@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg=="],
+ "@better-auth/core": ["@better-auth/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.41.1", "@standard-schema/spec": "^1.1.0", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2", "@opentelemetry/api": "^1.9.0", "better-call": "1.4.0", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-srgFzHEjB2WWlokFz1i4BfG41sNhsA105Pukgqu6RrEh5A+LSkzf1mCHydVipkjt9l5qswtBMi7IL6ouHbZL4Q=="],
+
+ "@better-auth/drizzle-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0" }, "optionalPeers": ["drizzle-orm"] }, "sha512-qon0U94PR5FQysuyGoAlGVQpIIiNg5dtDpwjE63sN/HjoRWZadZzHPcS9mn7JsJyQZK6iTNhd7LD0AaXt2f78w=="],
+
+ "@better-auth/kysely-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "kysely": "^0.28.17 || ^0.29.0" }, "optionalPeers": ["kysely"] }, "sha512-9FONOCgOcrQI9wJ5v1oDGIg9sT7pa9RjZZQ4fsCTudo8R87SrIGNUvUxDFTJhZvUblvFfGaIBR9Vb8LA+8bqLQ=="],
+
+ "@better-auth/memory-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2" } }, "sha512-FqKFEe+b5tXXV0gRbyirca+qXgMpLOeJ8Wk19yykb/scQKy0WJ4k22WzEV3TTPctQV9DZhwCXPlDtQhnlOv5Gg=="],
+
+ "@better-auth/mongo-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-ZnVDuRrXqbf0oHphrEN27oTImNH5NTO26dtWatq5cXyYAsH7goof9QIoTOmxTbBxUQahKBw9T6+9h6n+RtOE+g=="],
+
+ "@better-auth/passkey": ["@better-auth/[email protected]", "", { "dependencies": { "@simplewebauthn/browser": "^13.3.0", "@simplewebauthn/server": "^13.3.1", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2", "better-auth": "^1.7.7", "better-call": "1.4.0", "nanostores": "^1.0.1" } }, "sha512-FMhL3bspBxne8EcyPWx9LdWUCnmrNRoSxCnH9Q2FIWsSWXMYuPPcHOs07v4g0zUXmTlBSr4vwW3J6t2vdUIOlg=="],
+
+ "@better-auth/prisma-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-4YcnrcVdvWiAZw0sZl63tWUClPXg5r3QsLn7C2sG7kKEBY06zOng0ibecyxRBixKq1zE1ceHuEUqez5Rhi+nQA=="],
+
+ "@better-auth/telemetry": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2" } }, "sha512-PaRA6i+kAioVYmza2gHPcdrxP0hAotph4KV9hft2GeNJq+AZXDiBu3FuLM9HxvcmiZeUT74Vufqd9ypmB8veTA=="],
+
+ "@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-AUxrvu+HaaODsUyzDxFgwd/8RZ1yZaYo42LXKSrU2oGgR38pS1ij8nqQKNgtTWoYGpNevNXtCfgTy6loHveW9A=="],
+
+ "@better-fetch/fetch": ["@better-fetch/[email protected]", "", {}, "sha512-Gs7n99b5tqUC6cQAPbV0uED3IraHB6xQbHLQ/C3l7ZFafHScOx9pQ+DYmP5blbLFShVWLqxNUlI9wi4xU/X+ow=="],
+
"@borewit/text-codec": ["@borewit/[email protected]", "", {}, "sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ=="],
"@braidai/lang": ["@braidai/[email protected]", "", {}, "sha512-qBcknbBufNHlui137Hft8xauQMTZDKdophmLFv05r2eNmdIv/MlPuP4TdUknHG68UdWLgVZwgxVe735HzJNIwA=="],
@@ -1123,6 +1193,8 @@
"@earendil-works/pi-tui": ["@earendil-works/[email protected]", "", { "dependencies": { "get-east-asian-width": "1.6.0", "marked": "18.0.5" } }, "sha512-OIzw9efInmO4WOBnD4TxcTdBjmzvYJpzslkgoUro946nEGoYWg5rwv1p4fDt3/JvMx9QybryUCUwlm7j8Dreig=="],
+ "@electric-sql/pglite": ["@electric-sql/[email protected]", "", {}, "sha512-mZ9NzzUSYPOCnxHH1oAHPRzoMFJHY472raDKwXl/+6oPbpdJ7g8LsCN4FSaIIfkiCKHhb3iF/Zqo3NYxaIhU7Q=="],
+
"@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ=="],
"@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
@@ -1213,6 +1285,8 @@
"@google/genai": ["@google/[email protected]", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"] }, "sha512-gwSvbpiN/17O9TbsqSsE/OzZcpv5Fo4RQjdngGgogtuB9RsyJ8ZHhX5KjHj1bp5N9snN2eK8LDGXSaWW2hof8Q=="],
+ "@hexagon/base64": ["@hexagon/[email protected]", "", {}, "sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw=="],
+
"@hono/node-server": ["@hono/[email protected]", "", { "peerDependencies": { "hono": "^4" } }, "sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ=="],
"@humanfs/core": ["@humanfs/[email protected]", "", { "dependencies": { "@humanfs/types": "^0.15.0" } }, "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA=="],
@@ -1373,6 +1447,8 @@
"@jscpd/tokenizer": ["@jscpd/[email protected]", "", { "dependencies": { "@jscpd/core": "4.2.5", "spark-md5": "^3.0.2" } }, "sha512-/eyFjINWLs2mrBTU4H681bs855r5oRyl1O3mZxcd7TpL1JIG85a7pps0RkRPAe9c/2KcjVCc82HbhOz86M0n5g=="],
+ "@levischuck/tiny-cbor": ["@levischuck/[email protected]", "", {}, "sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow=="],
+
"@lezer/common": ["@lezer/[email protected]", "", {}, "sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ=="],
"@lezer/css": ["@lezer/[email protected]", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.0" } }, "sha512-YJE78Wcg+zX8f10hiHWQ4Az48Qr/c13eId0VtRQYLBpxHDmDeSrXIlkbl+fJGW42rWC/uoUco9mhBZeVWP/A1g=="],
@@ -1447,6 +1523,8 @@
"@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" } }, "sha512-UMduMbqO5s5zF2NkNacMT/yK5Y5QiKvWr2+50bzIIxFDwVJ2h49b+oyjaCGPhJxd2/gC2x39EHv/gHVuu36x2Q=="],
+ "@noble/ciphers": ["@noble/[email protected]", "", {}, "sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw=="],
+
"@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA=="],
"@nodable/entities": ["@nodable/[email protected]", "", {}, "sha512-8L9xFeTYKhm49xfIypoe2W5wV1m/3Z58kT+7kR9A8OyFxcPduI4VmxaUMQyKYrRjUoLLSXv6EKKID5Tvj9cUVw=="],
@@ -1471,6 +1549,10 @@
"@open-pencil/cli": ["@open-pencil/cli@workspace:packages/cli"],
+ "@open-pencil/cloud": ["@open-pencil/cloud@workspace:packages/cloud"],
+
+ "@open-pencil/cloud-tools": ["@open-pencil/cloud-tools@workspace:tools/dev/cloud"],
+
"@open-pencil/core": ["@open-pencil/core@workspace:packages/core"],
"@open-pencil/demo-tools": ["@open-pencil/demo-tools@workspace:tools/generate/demo"],
@@ -1535,6 +1617,10 @@
"@open-pencil/vue": ["@open-pencil/vue@workspace:packages/vue"],
+ "@openfeature/core": ["@openfeature/[email protected]", "", {}, "sha512-7PCPzyd1OC19begz30+CRknFB0ChtyaZUhk7YWrk+Bov1fpVw0HYkTXtoxxsvPfDZB9P9WsT7uixN+Z8f9+bcA=="],
+
+ "@openfeature/server-sdk": ["@openfeature/[email protected]", "", { "peerDependencies": { "@openfeature/core": "^1.12.0" } }, "sha512-JWeLvltJIV0AFgOfbw7hK9b9Rw/5wWq+RMhCIU9sJtAqarxr8hSPglG+JAGGhYdElAz3Qwe9W3ApWyPNkQEyqg=="],
+
"@openrouter/ai-sdk-provider": ["@openrouter/[email protected]", "", { "peerDependencies": { "ai": "^7.0.0", "zod": "^3.25.76 || ^4.1.8" } }, "sha512-BQy1TA9fKrh47s9ivsO6FY5QimN7GUF0i8Qon3pkxQclEgShso0dClpcWn8OIyPLEZZPFaFKgI8TW4S/O0p0Dw=="],
"@opentelemetry/semantic-conventions": ["@opentelemetry/[email protected]", "", {}, "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg=="],
@@ -1709,6 +1795,32 @@
"@oxlint/plugins": ["@oxlint/[email protected]", "", {}, "sha512-4mAGdfUZNQSZwUbHs0xoUcKjByrdBSJ9iaCI3STn/d1ZVRKhW/82oCA6rdfSzO4vxrWH3/l+qYWh/tyrwPSpag=="],
+ "@peculiar/asn1-android": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-llW/qjavL+tOxt5i9whUv4wsbsLpUwI6k/DrvKsdA/H7A/TB/6CosMFgvei28fcJ8ncD0c5lig1oBBlo4KGMCw=="],
+
+ "@peculiar/asn1-cms": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.0", "@peculiar/asn1-x509": "^2.11.0", "@peculiar/asn1-x509-attr": "^2.11.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-SlAiDoT/Cd8qaNmbTt78gqyaEvu2fQd6ML6KWJkdjXGrgDKnHHrusVkfQUelkfinL2p665IIADb0JBixtT8W1g=="],
+
+ "@peculiar/asn1-csr": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.0", "@peculiar/asn1-x509": "^2.11.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-M/ED0yJ05qMK+UADPKnIa8vhAeewOJALSxTAZB7RQ/batRHhIJZkwznCcWAbFO5saHJ1yEQ+m4lncEcG9RnQSg=="],
+
+ "@peculiar/asn1-ecc": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.0", "@peculiar/asn1-x509": "^2.11.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-jj1alGEKev7/un+cI+exyVK9m31lmP7cCBMCZuCb0wkFQH2zmKmJzNiG4wqXFNzlcP8timHLnzf3lV3OxBpb/Q=="],
+
+ "@peculiar/asn1-pfx": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-cms": "^2.11.0", "@peculiar/asn1-pkcs8": "^2.11.0", "@peculiar/asn1-rsa": "^2.11.0", "@peculiar/asn1-schema": "^2.11.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-ykSAWRu8KkmzU8LRpk9ZQC3zuLmBEtoSMjIv9XHVamD5W7amqreV5wttKqnvtjWOzzSJQxA/HVT8/tHwpEEGSQ=="],
+
+ "@peculiar/asn1-pkcs8": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.0", "@peculiar/asn1-x509": "^2.11.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-lragjkjQGnQ5luxC+sxoAfAO/jBiQ7hOEGlDKJUk7MC5zY3AzjB2DU0GyPUH1Sswdv10t7DurY0zylOYMLb88w=="],
+
+ "@peculiar/asn1-pkcs9": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-cms": "^2.11.0", "@peculiar/asn1-pfx": "^2.11.0", "@peculiar/asn1-pkcs8": "^2.11.0", "@peculiar/asn1-schema": "^2.11.0", "@peculiar/asn1-x509": "^2.11.0", "@peculiar/asn1-x509-attr": "^2.11.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-gDdFjpqV0weJjgNUvueUVf4D8uVbpq+VbG0TsxLAY2QGljAkJyL9qwQ7avol9j0jaYSJ7Ey7v7RZp0M3GTcQSA=="],
+
+ "@peculiar/asn1-rsa": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.0", "@peculiar/asn1-x509": "^2.11.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-S2sBJmbfI09Kzdt9cEhE6pDNjHpVTkURs+811+PxS8AvsTLxC4woMNRhxHYaIbClkkNfAVt0tZxJdINVfUmzuA=="],
+
+ "@peculiar/asn1-schema": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-8xh4avo53/vXO6UEv9yaoJ83hY581geaLTygf61NPIXP5AeIZCPjJhpTaYU23IZkG+NpLN/C9FYzWp7hphIT9A=="],
+
+ "@peculiar/asn1-x509": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.0", "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-J1sHAwGNlk+8J+FeR1eLVc6Gq0T9f9ITc3HWyPYgJraoW6U8AJuQiWVJ3SCEpltfTdpOY7fHdHT5oKAsbK/jww=="],
+
+ "@peculiar/asn1-x509-attr": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.0", "@peculiar/asn1-x509": "^2.11.0", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-Fgvnd9REmLxEj/4cbDP54dNUNUXkzUksXLqEHqs1mHBuSRjSTCUSPM/WQIZYSvrdG7ND9CX1AQtPoIBekhgQSA=="],
+
+ "@peculiar/utils": ["@peculiar/[email protected]", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ=="],
+
+ "@peculiar/x509": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-cms": "^2.6.0", "@peculiar/asn1-csr": "^2.6.0", "@peculiar/asn1-ecc": "^2.6.0", "@peculiar/asn1-pkcs9": "^2.6.0", "@peculiar/asn1-rsa": "^2.6.0", "@peculiar/asn1-schema": "^2.6.0", "@peculiar/asn1-x509": "^2.6.0", "pvtsutils": "^1.3.6", "reflect-metadata": "^0.2.2", "tslib": "^2.8.1", "tsyringe": "^4.10.0" } }, "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA=="],
+
"@pkgjs/parseargs": ["@pkgjs/[email protected]", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
"@pkgr/core": ["@pkgr/[email protected]", "", {}, "sha512-fdDH1LSGfZdTH2sxdpVMw31BanV28K/Gry0cVFxaNP77neJSkd82mM8ErPNYs9e+0O7SdHBLTDzDgwUuy18RnQ=="],
@@ -1997,13 +2109,17 @@
"@simple-libs/stream-utils": ["@simple-libs/[email protected]", "", {}, "sha512-fCTuZK4QBa+39Oz9l4OGfJfz+GpwCp3AqO7Zch3to99xHPgstVsRFpeQ8LNd2o1Gv8raL2mCFwiaHh7bFSp5DQ=="],
+ "@simplewebauthn/browser": ["@simplewebauthn/[email protected]", "", {}, "sha512-BE/UWv6FOToAdVk0EokzkqQQDOWtNydYlY6+OrmiZ5SCNmb41VehttboTetUM3T/fr6EAFYVXjz4My2wg230rQ=="],
+
+ "@simplewebauthn/server": ["@simplewebauthn/[email protected]", "", { "dependencies": { "@hexagon/base64": "^1.1.27", "@levischuck/tiny-cbor": "^0.2.2", "@peculiar/asn1-android": "^2.6.0", "@peculiar/asn1-ecc": "^2.6.1", "@peculiar/asn1-rsa": "^2.6.1", "@peculiar/asn1-schema": "^2.6.0", "@peculiar/asn1-x509": "^2.6.1", "@peculiar/x509": "^1.14.3" } }, "sha512-LelX/lcy5cjc15A86i/aNxHhB5eU7dd20QsbP0VLAf9e38+SLlsnqCCyecx3xqfGofhmX05h1J9fKRYWxw+luA=="],
+
"@sinclair/typebox": ["@sinclair/[email protected]", "", {}, "sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw=="],
"@sindresorhus/is": ["@sindresorhus/[email protected]", "", {}, "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw=="],
"@sindresorhus/merge-streams": ["@sindresorhus/[email protected]", "", {}, "sha512-LtoMMhxAlorcGhmFYI+LhPgbPZCkgP6ra1YL604EeF6U98pLlQ3iWIGMdWSC+vWmPBWBNgmDBAhnAobLROJmwg=="],
- "@smithy/core": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-i4YPS4B6ts7bjn7UwLnGjiZdprOvHvgGobFZsYK3GIY3E5hIqtj0rReU69BcTpGp+fvtraSNXeG1l+jtJvF55w=="],
+ "@smithy/core": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-3hJiwG1F5t1SoXqp/yOCmYXziyx7ZVqF63S5W6YU201e/qwVaHPex+E/3vvyY9a3ORq/b+BydeNZpP2saQ9X2g=="],
"@smithy/credential-provider-imds": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/core": "^3.33.2", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg=="],
@@ -2201,12 +2317,16 @@
"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-b4e2xxj/yMeT2hNlD6x7zNFiQK2Dlmkb9CQ6v3/1G2RezKN4YS2lcEv8lzGm1mhs4f2lM4yNAMI/zUDBZBBt7w=="],
+ "@types/nodemailer": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA=="],
+
"@types/normalize-package-data": ["@types/[email protected]", "", {}, "sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA=="],
"@types/opentype.js": ["@types/[email protected]", "", {}, "sha512-F67EFyk6j02okHz5JCgata3ZRAcZi9GLnzmkHw/rzJq3OCc8/ZVdoKrxMTYjcQP6IYHGBz2cav1cpzkOkPiPCQ=="],
"@types/pako": ["@types/[email protected]", "", {}, "sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw=="],
+ "@types/pg": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A=="],
+
"@types/proper-lockfile": ["@types/[email protected]", "", { "dependencies": { "@types/retry": "*" } }, "sha512-uo2ABllncSqg9F1D4nugVl9v93RmjxF6LJzQLMLDdPaXCUIDPeOJ21Gbqi43xNKzBi/WQ0Q0dICqufzQbMjipQ=="],
"@types/raf": ["@types/[email protected]", "", {}, "sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw=="],
@@ -2541,6 +2661,8 @@
"asap": ["[email protected]", "", {}, "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA=="],
+ "asn1js": ["[email protected]", "", { "dependencies": { "pvtsutils": "^1.3.6", "pvutils": "^1.1.5", "tslib": "^2.8.1" } }, "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg=="],
+
"assert-never": ["[email protected]", "", {}, "sha512-5oJg84os6NMQNl27T9LnZkvvqzvAnHu03ShCnoj6bsJwS7L8AO4lf+C/XjK/nvzEqQB744moC6V128RucQd1jA=="],
"assertion-error": ["[email protected]", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="],
@@ -2601,6 +2723,10 @@
"basic-ftp": ["[email protected]", "", {}, "sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw=="],
+ "better-auth": ["[email protected]", "", { "dependencies": { "@better-auth/core": "1.7.7", "@better-auth/drizzle-adapter": "1.7.7", "@better-auth/kysely-adapter": "1.7.7", "@better-auth/memory-adapter": "1.7.7", "@better-auth/mongo-adapter": "1.7.7", "@better-auth/prisma-adapter": "1.7.7", "@better-auth/telemetry": "1.7.7", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2", "@noble/ciphers": "^2.2.0", "@noble/hashes": "^2.2.0", "better-call": "1.4.0", "defu": "^6.1.4", "jose": "^6.2.3", "kysely": "^0.28.17 || ^0.29.0", "nanostores": "^1.3.0", "zod": "^4.5.4" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "drizzle-kit": ">=0.31.4 || >=1.0.0-beta.1", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-Zhgxi/c5ylmfB/sX+nwnBbsFf/j6k0L8DvL6CJXZSrXgxc5pPMC/e7j812zNd4L4B4ELmdURCPw3X8nAOUdcjw=="],
+
+ "better-call": ["[email protected]", "", { "dependencies": { "@better-auth/utils": "^0.5.0", "@better-fetch/fetch": "^1.3.1", "rou3": "^0.9.1", "set-cookie-parser": "^3.1.2" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-bBKOT4vv1kZLDgxVePdilk/Jwkn+dtRRsmi3DzHcDP+WnswyVl6dR59l2HEeP/0cB+bDoopASAesWDPIdd/zZA=="],
+
"bignumber.js": ["[email protected]", "", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="],
"binary-extensions": ["[email protected]", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="],
@@ -3245,6 +3371,8 @@
"hono": ["[email protected]", "", {}, "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA=="],
+ "hono-rate-limiter": ["[email protected]", "", { "peerDependencies": { "hono": "^4.10.8", "unstorage": "^1.17.3" }, "optionalPeers": ["unstorage"] }, "sha512-P3/cscAmz1hA+MuM+Hn9gP/EyO2zWv2aXIFkVYuLZkPzrPa4oaWdVCS94vyDlsNBgeMnE/Hr2+LznIKQxrF0ng=="],
+
"hookable": ["[email protected]", "", {}, "sha512-U9LYDy1CwhMCnprUfeAZWZGByVbhd54hwepegYTK7Pi5NvqEj63ifz5z+xukznehT7i6NIZRu89Ay1AZmRsLEQ=="],
"hosted-git-info": ["[email protected]", "", { "dependencies": { "lru-cache": "^11.1.0" } }, "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg=="],
@@ -3491,6 +3619,8 @@
"kysely-d1": ["[email protected]", "", { "peerDependencies": { "kysely": "*" } }, "sha512-wUcVvQNtm30OTfuo7Ad5vYJ1qHqPXOCZc+zWchVKNyuvqY3u8OuGw4gmUx1Ypdx2wRVFLHVQC9I7v0pTmF7Nkw=="],
+ "kysely-pglite-dialect": ["[email protected]", "", { "peerDependencies": { "@electric-sql/pglite": "^0.2.0 || ^0.3.0 || ^0.4.0", "kysely": ">=0.23.0" } }, "sha512-QwB87FWSM63JsHouhTil3MNLcP9ajguDv+fFUokVEXEBdjxbtoXZd4iJEZtmdmyGshCFWrE565Ua6fdAfNRxJw=="],
+
"lazystream": ["[email protected]", "", { "dependencies": { "readable-stream": "^2.0.5" } }, "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw=="],
"leac": ["[email protected]", "", {}, "sha512-y+SqErxb8h7nE/fiEX07jsbuhrpO9lL8eca7/Y1nuWV2moNlXhyd59iDGcRf6moVyDMbmTNzL40SUyrFU/yDpg=="],
@@ -3775,6 +3905,8 @@
"node-source-walk": ["[email protected]", "", { "dependencies": { "@babel/parser": "^7.29.0" } }, "sha512-71kFFjYaSshDTA8/a2HiTYPLdASWjLJxUyJxGE+ffxU+KhxSBtM9kiLUX+R2yooFdSFKMFpi4n3PFtDy6qXv8A=="],
+ "nodemailer": ["[email protected]", "", {}, "sha512-izw9mVKFix6YSnC9eLgV6g1opl9DUlRio9ZNcq+Wu9Ujn2UwF+8Nl0B8nz22kEC+CTZCvinkxwJ0DeFbb6NwcQ=="],
+
"nopt": ["[email protected]", "", { "dependencies": { "abbrev": "^2.0.0" }, "bin": { "nopt": "bin/nopt.js" } }, "sha512-taM24ViiimT/XntxbPyJQzCG+p4EKOpgD3mxFwW38mGjVUrfERQOeY4EDHjdnptttfHuHQXFx+lTP08Q+mLa/w=="],
"normalize-package-data": ["[email protected]", "", { "dependencies": { "hosted-git-info": "^8.0.0", "semver": "^7.3.5", "validate-npm-package-license": "^3.0.4" } }, "sha512-linxNAT6M0ebEYZOx2tO6vBEFsVgnPpv+AVjk0wJHfaUIbq31Jm3T6vvZaarnOeWDh8ShnwXuaAyM7WT3RzErA=="],
@@ -3897,6 +4029,22 @@
"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],
+ "pg": ["[email protected]", "", { "dependencies": { "pg-connection-string": "^2.14.1", "pg-pool": "^3.14.0", "pg-protocol": "^1.16.1", "pg-types": "2.2.0", "pgpass": "1.0.5" }, "optionalDependencies": { "pg-cloudflare": "^1.4.1" }, "peerDependencies": { "pg-native": ">=3.0.1" }, "optionalPeers": ["pg-native"] }, "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ=="],
+
+ "pg-cloudflare": ["[email protected]", "", {}, "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ=="],
+
+ "pg-connection-string": ["[email protected]", "", {}, "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA=="],
+
+ "pg-int8": ["[email protected]", "", {}, "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw=="],
+
+ "pg-pool": ["[email protected]", "", { "peerDependencies": { "pg": ">=8.0" } }, "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw=="],
+
+ "pg-protocol": ["[email protected]", "", {}, "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg=="],
+
+ "pg-types": ["[email protected]", "", { "dependencies": { "pg-int8": "1.0.1", "postgres-array": "~2.0.0", "postgres-bytea": "~1.0.0", "postgres-date": "~1.0.4", "postgres-interval": "^1.1.0" } }, "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA=="],
+
+ "pgpass": ["[email protected]", "", { "dependencies": { "split2": "^4.1.0" } }, "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug=="],
+
"pi-mcp-adapter": ["[email protected]", "", { "dependencies": { "@modelcontextprotocol/client": "2.0.0-beta.5", "@modelcontextprotocol/ext-apps": "^1.2.2", "@modelcontextprotocol/sdk": "^1.29.0", "cross-spawn": "^7.0.6", "open": "^10.2.0", "recheck": "^4.5.0", "smol-toml": "^1.6.1", "zod": "^3.25.0 || ^4.0.0" }, "peerDependencies": { "@earendil-works/pi-ai": "*", "@earendil-works/pi-tui": "*", "typebox": "*" }, "optionalPeers": ["@earendil-works/pi-ai", "@earendil-works/pi-tui", "typebox"], "bin": { "pi-mcp-adapter": "cli.js" } }, "sha512-lB0ANetzF0ld+l8ibgF6KcT7bj1LKvhgKig9LHMvr1DEBark6xZ36Jeb+JLib49/M03sBaCH5s3Jcmcy/OO5wg=="],
"picocolors": ["[email protected]", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
@@ -3929,6 +4077,14 @@
"postcss-values-parser": ["[email protected]", "", { "dependencies": { "color-name": "^1.1.4", "is-url-superb": "^4.0.0", "quote-unquote": "^1.0.0" }, "peerDependencies": { "postcss": "^8.2.9" } }, "sha512-YLJpK0N1brcNJrs9WatuJFtHaV9q5aAOj+S4DI5S7jgHlRfm0PIbDCAFRYMQD5SHq7Fy6xsDhyutgS0QOAs0qw=="],
+ "postgres-array": ["[email protected]", "", {}, "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA=="],
+
+ "postgres-bytea": ["[email protected]", "", {}, "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ=="],
+
+ "postgres-date": ["[email protected]", "", {}, "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q=="],
+
+ "postgres-interval": ["[email protected]", "", { "dependencies": { "xtend": "^4.0.0" } }, "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ=="],
+
"pptxgenjs": ["[email protected]", "", { "dependencies": { "@types/node": "^22.8.1", "https": "^1.0.0", "image-size": "^1.2.1", "jszip": "^3.10.1" } }, "sha512-TeJISr8wouAuXw4C1F/mC33xbZs/FuEG6nH9FG1Zj+nuPcGMP5YRHl6X+j3HSUnS1f3at6k75ZZXPMZlA5Lj9A=="],
"prebuild-install": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
@@ -4001,6 +4157,10 @@
"punycode.js": ["[email protected]", "", {}, "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA=="],
+ "pvtsutils": ["[email protected]", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg=="],
+
+ "pvutils": ["[email protected]", "", {}, "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg=="],
+
"qs": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA=="],
"quansync": ["[email protected]", "", {}, "sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA=="],
@@ -4081,6 +4241,8 @@
"redent": ["[email protected]", "", { "dependencies": { "indent-string": "^4.0.0", "strip-indent": "^3.0.0" } }, "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg=="],
+ "reflect-metadata": ["[email protected]", "", {}, "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q=="],
+
"reflect.getprototypeof": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.9", "es-errors": "^1.3.0", "es-object-atoms": "^1.0.0", "get-intrinsic": "^1.2.7", "get-proto": "^1.0.1", "which-builtin-type": "^1.2.1" } }, "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw=="],
"regenerate": ["[email protected]", "", {}, "sha512-zrceR/XhGYU/d/opr2EKO7aRHUeiBI8qjtfHqADTwZd6Szfy16la6kqD0MIUs5z5hx6AaKa+PixpPrR289+I0A=="],
@@ -4149,6 +4311,8 @@
"rollup": ["[email protected]", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@napi-rs/lzma-linux-x64-gnu": "1.5.1", "@rollup/rollup-android-arm-eabi": "4.62.4", "@rollup/rollup-android-arm64": "4.62.4", "@rollup/rollup-darwin-arm64": "4.62.4", "@rollup/rollup-darwin-x64": "4.62.4", "@rollup/rollup-freebsd-arm64": "4.62.4", "@rollup/rollup-freebsd-x64": "4.62.4", "@rollup/rollup-linux-arm-gnueabihf": "4.62.4", "@rollup/rollup-linux-arm-musleabihf": "4.62.4", "@rollup/rollup-linux-arm64-gnu": "4.62.4", "@rollup/rollup-linux-arm64-musl": "4.62.4", "@rollup/rollup-linux-loong64-gnu": "4.62.4", "@rollup/rollup-linux-loong64-musl": "4.62.4", "@rollup/rollup-linux-ppc64-gnu": "4.62.4", "@rollup/rollup-linux-ppc64-musl": "4.62.4", "@rollup/rollup-linux-riscv64-gnu": "4.62.4", "@rollup/rollup-linux-riscv64-musl": "4.62.4", "@rollup/rollup-linux-s390x-gnu": "4.62.4", "@rollup/rollup-linux-x64-gnu": "4.62.4", "@rollup/rollup-linux-x64-musl": "4.62.4", "@rollup/rollup-openbsd-x64": "4.62.4", "@rollup/rollup-openharmony-arm64": "4.62.4", "@rollup/rollup-win32-arm64-msvc": "4.62.4", "@rollup/rollup-win32-ia32-msvc": "4.62.4", "@rollup/rollup-win32-x64-gnu": "4.62.4", "@rollup/rollup-win32-x64-msvc": "4.62.4", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-RXOqwaPsBGjMNMa4sQjDjHieHEZDFoj/Rdr46l2MU5DfEs16wHJPC2RPTPHWhNl+M3aI472LLqFkFKut4SblOg=="],
+ "rou3": ["[email protected]", "", {}, "sha512-3SOzvaAg8rkHrXtRjpCvCvbyO5to9oOO27Z/XqHEYXfMRVSw/qMIVdmaOk9W2lcRLtR6dlqTjo9hDeJk70QBYQ=="],
+
"router": ["[email protected]", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
"run-applescript": ["[email protected]", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="],
@@ -4197,6 +4361,8 @@
"serve-static": ["[email protected]", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],
+ "set-cookie-parser": ["[email protected]", "", {}, "sha512-xletSdAI5efyVJjsatBbzDkXl3M/Zmad3xfnQe7ZXuBB0yNwW7C2WFsNGjdRNfZunmNHQuX79xs/ACMTLCdcew=="],
+
"set-function-length": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", "function-bind": "^1.1.2", "get-intrinsic": "^1.2.4", "gopd": "^1.0.1", "has-property-descriptors": "^1.0.2" } }, "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg=="],
"set-function-name": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", "functions-have-names": "^1.2.3", "has-property-descriptors": "^1.0.2" } }, "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ=="],
@@ -4463,6 +4629,8 @@
"tsx": ["[email protected]", "", { "dependencies": { "esbuild": "~0.28.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-FDf4L4sYzKtzWYhU/Xm0AQFdTjdIxNo9ElTf2mxXM6k8YMHXzYUe4yODVaXP4V9uMFbVg8c0qyBccK2OOxb45Q=="],
+ "tsyringe": ["[email protected]", "", { "dependencies": { "tslib": "^1.9.3" } }, "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw=="],
+
"tunnel-agent": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w=="],
"turndown": ["[email protected]", "", { "dependencies": { "@mixmark-io/domino": "^2.2.0" } }, "sha512-I8yFsfRzmzK0WV1pNNOA4A7y4RDfFxPRxb3t+e3ui14qSGOxGtiSP6GjeX+Y6CHb7HYaFj7ECUD7VE5kQMZWGQ=="],
@@ -4739,6 +4907,8 @@
"xspattern": ["[email protected]", "", { "dependencies": { "whynot": "^5.0.0" } }, "sha512-rxtOX8ORJizRqswIdZ72G3thKrHd0Q+TvyUCMByc5VdjDz1nkuZKfPXM3xGdrGi0fwEy+DDJN7DqtAZ06Re4bA=="],
+ "xtend": ["[email protected]", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="],
+
"y-indexeddb": ["[email protected]", "", { "dependencies": { "lib0": "^0.2.74" }, "peerDependencies": { "yjs": "^13.0.0" } }, "sha512-9oCFRSPPzBK7/w5vOkJBaVCQZKHXB/v6SIT+WYhnJxlEC61juqG0hBrAf+y3gmSMLFLwICNH9nQ53uscuse6Hg=="],
"y-protocols": ["[email protected]", "", { "dependencies": { "lib0": "^0.2.85" }, "peerDependencies": { "yjs": "^13.0.0" } }, "sha512-YSVsLoXxO67J6eE/nV4AtFtT3QEotZf5sK5BHxFBXso7VDUT3Tx07IfA6hsu5Q5OmBdMkQVmFZ9QOA7fikWvnw=="],
@@ -4919,6 +5089,12 @@
"@smithy/credential-provider-imds/@smithy/types": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-FOKpVZob9MPTn2znRzGrnsMHv7BOsKVw3XiP/cOyYLDVZ9qKp4nifIiSCuUU/fIj5Vu0UOAxCFr+qRAtG0NUkA=="],
+ "@smithy/fetch-http-handler/@smithy/core": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-i4YPS4B6ts7bjn7UwLnGjiZdprOvHvgGobFZsYK3GIY3E5hIqtj0rReU69BcTpGp+fvtraSNXeG1l+jtJvF55w=="],
+
+ "@smithy/node-http-handler/@smithy/core": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-i4YPS4B6ts7bjn7UwLnGjiZdprOvHvgGobFZsYK3GIY3E5hIqtj0rReU69BcTpGp+fvtraSNXeG1l+jtJvF55w=="],
+
+ "@smithy/signature-v4/@smithy/core": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-i4YPS4B6ts7bjn7UwLnGjiZdprOvHvgGobFZsYK3GIY3E5hIqtj0rReU69BcTpGp+fvtraSNXeG1l+jtJvF55w=="],
+
"@storybook/addon-docs/react": ["[email protected]", "", {}, "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw=="],
"@storybook/addon-docs/react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.8" } }, "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ=="],
@@ -5037,6 +5213,10 @@
"babel-plugin-polyfill-corejs2/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+ "better-call/@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-BL8W4EfIZFwlu0r54m3v1ztjDhu6dDe/amLTm0xybmbZaNgYUqhD3SjpAsnq0q8YD6/ki4iwIgxJNLP/N3TxiA=="],
+
+ "better-call/@better-fetch/fetch": ["@better-fetch/[email protected]", "", {}, "sha512-ABkD1WhyfPZprKRQI3bhATjeiFuNWC9PXhfGWqL+sg/gKrM977oFrYkdb4msM3hgUGonr7KlOsOFT5TU2rht9g=="],
+
"blamer/execa": ["[email protected]", "", { "dependencies": { "cross-spawn": "^7.0.0", "get-stream": "^5.0.0", "human-signals": "^1.1.1", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.0", "onetime": "^5.1.0", "signal-exit": "^3.0.2", "strip-final-newline": "^2.0.0" } }, "sha512-j5W0//W7f8UxAn8hXVnwG8tLwdiUy4FJLcSupCg6maBYZDpyBvTApK7KyuI4bKj8KOh1r2YH+6ucuYtJv1bTZA=="],
"body-parser/content-type": ["[email protected]", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="],
@@ -5285,6 +5465,8 @@
"tsx/esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="],
+ "tsyringe/tslib": ["[email protected]", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="],
+
"tunnel-agent/safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"twoslash-vue/@vue/language-core": ["@vue/[email protected]", "", { "dependencies": { "@volar/language-core": "2.4.28", "@vue/compiler-dom": "^3.5.0", "@vue/shared": "^3.5.0", "alien-signals": "^3.2.1", "muggle-string": "^0.4.1", "path-browserify": "^1.0.1", "picomatch": "^4.0.4" } }, "sha512-CR7ByBbgPHqhxrioKPOcZBqttaozzLNwtkCzXQ+uF8gLPHnUe03srPnGpdtHD3zp+bq5iyVkZ1WNx7W564RPwg=="],
diff --git a/oxlint.json b/oxlint.json
index 99a3dd9c3..2941bb3a3 100644
--- a/oxlint.json
+++ b/oxlint.json
@@ -435,6 +435,20 @@
"open-pencil/no-app-imports-in-packages": "off"
}
},
+ {
+ "files": [
+ "packages/cloud/src/**/*.ts"
+ ],
+ "rules": {
+ "typescript/no-unsafe-assignment": "error",
+ "typescript/no-unsafe-argument": "error",
+ "typescript/no-unsafe-call": "error",
+ "typescript/no-unsafe-member-access": "error",
+ "typescript/no-unsafe-return": "error",
+ "typescript/switch-exhaustiveness-check": "error",
+ "typescript/no-deprecated": "error"
+ }
+ },
{
"files": ["tools/ci/policy/src/**/*.ts"],
"rules": {
@@ -476,7 +490,8 @@
{
"files": [
"src/**/*.{ts,vue}",
- "packages/{scene-graph,pen,kiwi,fig,core,dom-css,vue}/src/**/*.{ts,vue}"
+ "packages/{scene-graph,pen,kiwi,fig,core,dom-css,vue}/src/**/*.{ts,vue}",
+ "packages/cloud/src/{client,contract}/**/*.ts"
],
"rules": {
"compat/compat": "error"
@@ -505,7 +520,9 @@
{
"files": [
"packages/cli/src/**",
- "packages/mcp/src/**"
+ "packages/mcp/src/**",
+ "packages/cloud/src/runtime/node/**",
+ "packages/cloud/tests/e2e/**"
],
"rules": {
"no-console": "off"
diff --git a/package.json b/package.json
index 25035378f..da47ae3f0 100644
--- a/package.json
+++ b/package.json
@@ -17,6 +17,7 @@
"packages/mcp",
"packages/harness",
"packages/feedback",
+ "packages/cloud",
"packages/docs",
"vite",
"tools",
@@ -31,6 +32,7 @@
"tools/ci/images",
"tools/ci/policy",
"tools/ci/pr-review-guidance",
+ "tools/dev/cloud",
"tools/dev/dev-server",
"tools/dev/navigation-benchmark",
"tools/dev/unit-tests",
@@ -47,6 +49,8 @@
"scripts": {
"dev": "vite",
"dev:portless": "portless run vite",
+ "cloud:dev": "bun tools/dev/cloud/src/index.ts up",
+ "cloud:dev:down": "bun tools/dev/cloud/src/index.ts down",
"build": "bun run build:packages && bun run lint && vite build",
"preview": "vite preview",
"storybook": "storybook dev -p 6006",
@@ -55,9 +59,9 @@
"build:native-test": "bun run generate:icons --target desktop && bun run build:packages && bun tauri build --debug --no-bundle --features native-test --config desktop/tauri.native-test.conf.json",
"benchmark:navigation": "bun tools/dev/navigation-benchmark/src/cli.ts run",
"test:native": "bun run build:native-test && wdio run wdio.conf.ts",
- "lint": "bun run lint:structure && oxlint -c oxlint.json --type-aware --type-check src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/feedback/src/ packages/dom-css/src/ packages/pen/src/ packages/design-jsx/src/ packages/emit/src/ packages/kiwi/src/ packages/fig/src/ packages/docs/.vitepress/theme/landing/",
- "lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/emit/src/ packages/emit/tests/ packages/emit/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ packages/core/tests/ packages/cli/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/ packages/docs/.vitepress/theme/landing/",
- "format": "oxfmt --write .oxfmtrc.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/emit/src/ packages/emit/tests/ packages/emit/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ tests scripts/ tools/ packages/docs/.vitepress/theme/landing/",
+ "lint": "bun run lint:structure && oxlint -c oxlint.json --type-aware --type-check src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/feedback/src/ packages/cloud/src/ packages/dom-css/src/ packages/pen/src/ packages/design-jsx/src/ packages/emit/src/ packages/kiwi/src/ packages/fig/src/ packages/docs/.vitepress/theme/landing/",
+ "lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/emit/src/ packages/emit/tests/ packages/emit/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ packages/core/tests/ packages/cli/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/ packages/docs/.vitepress/theme/landing/",
+ "format": "oxfmt --write .oxfmtrc.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/cloud/tsdown.config.ts packages/cloud/tsdown.standalone.config.ts packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/emit/src/ packages/emit/tests/ packages/emit/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ tests scripts/ tools/ packages/docs/.vitepress/theme/landing/",
"format:check": "bun run format && status=$(git status --porcelain -uall) && test -z \"$status\" || (echo \"$status\" && exit 1)",
"check": "bun run check:icons && bun run build:packages && bun run lint && tsgo --noEmit && bun run check:vue && bun run check:native-test && bun run check:i18n && bun run check:docs && bun run check:changelog && bun run check:packages && bun run check:deps && bun run check:audit && bun run check:secrets && bun run check:monorepo && bun run check:arch && bun run check:test-homes && bun run check:test-types && bun run test:type-shapes && bun run check:tools && bun run test:tools && bun run test:dupes",
"check:commits": "commitlint",
@@ -92,7 +96,8 @@
"test:type-shapes": "bun tools/checks/type-shapes/src/index.ts",
"test:tools": "bun --filter '@open-pencil/*-tools' test && bun --filter @open-pencil/harness test",
"test:feedback": "bun --filter @open-pencil/feedback typecheck && bun --filter @open-pencil/feedback check:types && bun --filter @open-pencil/feedback test",
- "test:dupes": "jscpd packages/scene-graph/src packages/pen/src packages/design-jsx/src packages/emit/src packages/core/src packages/cli/src packages/feedback/src packages/dom-css/src packages/fig/src src --min-lines 5 --min-tokens 50 --format typescript --threshold 0",
+ "test:cloud": "bun --filter @open-pencil/cloud typecheck && bun --filter @open-pencil/cloud test",
+ "test:dupes": "jscpd packages/scene-graph/src packages/pen/src packages/design-jsx/src packages/emit/src packages/core/src packages/cli/src packages/feedback/src packages/cloud/src packages/dom-css/src packages/fig/src src --min-lines 5 --min-tokens 50 --format typescript --threshold 0",
"test:packages": "bun tools/checks/package-quality/src/cli.ts verify",
"build:packages": "bun tools/release/package-artifacts/src/build.ts",
"open-pencil": "bun packages/cli/src/index.ts",
@@ -116,7 +121,7 @@
"@ai-sdk/vue": "^4.0.127",
"@atlaskit/pragmatic-drag-and-drop": "^1.8.1",
"@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.2.0",
- "@aws-sdk/client-s3": "^3.1147.0",
+ "@aws-sdk/client-s3": "^3.1149.0",
"@chenglou/pretext": "^0.0.7",
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
diff --git a/packages/cloud/AGENTS.md b/packages/cloud/AGENTS.md
new file mode 100644
index 000000000..3c81e986a
--- /dev/null
+++ b/packages/cloud/AGENTS.md
@@ -0,0 +1,28 @@
+# Cloud
+
+Optional, self-hostable backend; the design is in `packages/docs/development/cloud.md`. The editor must keep opening, editing, and saving local documents without this package or a network.
+
+## Boundaries
+
+- Consumers import the `contract`, `client`, `email`, `server`, and `runtime/node` subpaths; browser code imports only `contract` and `client`, which stay on the browser baseline (`tests/app/shell/support/baseline.test.ts`, `compat/compat` in `oxlint.json`).
+- `src/server` receives its database, object store, auth adapter, and delivery through injection and never imports `pg`, opens listeners, runs migrations, or starts timers; runtimes under `src/runtime/` own those (`src/runtime/node/server.ts`).
+- Runtime code runs on Node 22 and Bun alike: serve HTTP through `@hono/node-server`, not `Bun.serve` or other `Bun.*` APIs (`tsdown.standalone.config.ts` targets `node22`).
+
+## Data and security
+
+- Database rows use `crypto.randomUUID()`; secrets that leave the server use `randomHex` from `@open-pencil/scene-graph/random`, are stored as SHA-256 digests (a single-use OAuth continuation keeps a JWE copy), and travel in URL fragments (`src/server/sharing/capabilities/service.ts`).
+- Every HTTP body goes through `validatedJSON` with a contract schema, and every response the client reads is parsed with Valibot (`src/server/validation.ts`, `src/client/api.ts`).
+- Add schema changes as a new numbered migration in `src/server/db/migrations/` registered in `src/server/db/migrate.ts`; never edit a migration that has shipped. Better Auth's tables have their own versioned migration (`016_auth_schema.ts`).
+- Prefer typed Kysely queries; raw SQL goes through the reviewed helpers in `src/server/db/expressions.ts`.
+
+## Configuration
+
+- Deployment settings live in the schema-versioned TOML parsed by `src/server/config/deployment.ts`; environment variables only resolve `{ from_env }` secret references and never override the file (`tests/runtime/node/config.test.ts`).
+- Technical limits are ceilings that policy can tighten but never raise (`src/server/config/limits.ts`, `src/server/policy/`).
+- Feature and limit decisions go through the OpenFeature policy keys in `src/server/policy/keys.ts`; never branch on a plan name.
+
+## Tests
+
+- Unit tests mirror `src` under `tests/{client,contract,runtime,server}`; integration tests mirror `src` under `tests/integration` and run on PGlite through `tests/helpers/database.ts`; `tests/e2e` holds Docker Compose runners that `test` never starts.
+- Tests import source through `#cloud/*` and helpers through `#cloud-tests/*`, and read responses with `responseJSON` from `tests/helpers/response.ts`.
+- `bun run test:cloud` type-checks the package and runs unit and integration suites.
diff --git a/packages/cloud/README.md b/packages/cloud/README.md
new file mode 100644
index 000000000..f1402bbb7
--- /dev/null
+++ b/packages/cloud/README.md
@@ -0,0 +1,36 @@
+# @open-pencil/cloud
+
+Optional, self-hostable OpenPencil Cloud: accounts, workspaces, immutable document revisions in
+S3-compatible storage, sharing, enrollment, quotas, and transactional email. The editor stays
+local-first and works without it.
+
+## Subpaths
+
+- `@open-pencil/cloud/contract` — Valibot network contracts and public types.
+- `@open-pencil/cloud/client` — discovery, authentication, device authorization, and the typed client.
+- `@open-pencil/cloud/email` — Vue Email rendering.
+- `@open-pencil/cloud/server` — runtime-neutral Hono routes and services with injected dependencies.
+- `@open-pencil/cloud/runtime/node` — PostgreSQL, S3, SMTP, the HTTP listener, and workers.
+
+## Running
+
+The Node runtime reads one deployment TOML file named by `OPENPENCIL_CLOUD_CONFIG` and resolves
+secrets from the environment. Start from
+[`deploy/openpencil-cloud.example.toml`](./deploy/openpencil-cloud.example.toml), then build and run
+the self-contained server on Node 22 or later:
+
+```sh
+bun --filter @open-pencil/cloud build:standalone
+bun --filter @open-pencil/cloud start
+```
+
+The server migrates the database before it accepts requests. [`deploy/README.md`](./deploy/README.md)
+covers self-hosting, local development, and operator commands, and
+[`deploy/security.md`](./deploy/security.md) covers hardening. The design is described in
+[Cloud Architecture](https://openpencil.dev/development/cloud).
+
+## Tests
+
+`bun run test:cloud` from the repository root type-checks the package and runs unit and PGlite
+integration tests. `bun --filter @open-pencil/cloud test:e2e` runs the Docker Compose end-to-end
+suite against PostgreSQL and SeaweedFS.
diff --git a/packages/cloud/deploy/.env.example b/packages/cloud/deploy/.env.example
new file mode 100644
index 000000000..6d5aa9cc2
--- /dev/null
+++ b/packages/cloud/deploy/.env.example
@@ -0,0 +1,25 @@
+# The Node runtime reads durable settings from this TOML file.
+OPENPENCIL_CLOUD_CONFIG=./openpencil-cloud.toml
+PORT=8787
+
+# Required secrets. The conventional names below are the TOML defaults.
+DATABASE_URL=postgresql://openpencil:openpencil-development-password@localhost:54329/openpencil
+BETTER_AUTH_SECRET=replace-with-at-least-32-random-characters
+S3_ACCESS_KEY_ID=openpencil
+S3_SECRET_ACCESS_KEY=openpencil-development-secret
+
+# Optional secrets are required only when their corresponding TOML section is enabled.
+# GOOGLE_CLIENT_ID=
+# GOOGLE_CLIENT_SECRET=
+# APPLE_PRIVATE_KEY=
+# S3_SESSION_TOKEN=
+# OPENPENCIL_CLOUD_SMTP_USER=
+# OPENPENCIL_CLOUD_SMTP_PASSWORD=
+
+# Compose infrastructure settings, not Cloud application configuration.
+POSTGRES_PASSWORD=openpencil-development-password
+S3_REGION=us-east-1
+S3_BUCKET=openpencil
+
+# After approving and signing in the first operator, grant the deployment admin role with:
+# bun --filter @open-pencil/cloud admin grant [email protected]
diff --git a/packages/cloud/deploy/README.md b/packages/cloud/deploy/README.md
new file mode 100644
index 000000000..874cdca88
--- /dev/null
+++ b/packages/cloud/deploy/README.md
@@ -0,0 +1,115 @@
+# 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.
+
+## Local development
+
+From the repository root, with Docker running:
+
+```sh
+bun run cloud:dev
+# OpenPencil Cloud: https://<branch>.cloud.open-pencil.localhost
+# Captured email: https://<branch>.mail.open-pencil.localhost
+```
+
+The command starts PostgreSQL, SeaweedFS, and Mailpit from [`compose.yml`](./compose.yml) as a
+Compose project named after the branch, publishes them on free loopback ports, writes an ignored
+TOML file with the branch's Portless URLs under `generated/`, and runs the Cloud server on the host
+with `bun --watch` behind Portless. Email and password sign-up is enabled, and every message lands
+in Mailpit.
+
+`bun run cloud:dev:down` stops the services and removes the Mailpit route; their volumes are kept.
+
+## Self-hosting
+
+1. Provision PostgreSQL 15 or later and an S3-compatible bucket.
+2. Copy [`openpencil-cloud.example.toml`](./openpencil-cloud.example.toml) and set at least
+ `deployment.public_url`, `deployment.app_url`, `deployment.trusted_origins`, and
+ `[object_storage]`.
+3. Copy [`.env.example`](./.env.example), point `OPENPENCIL_CLOUD_CONFIG` at the TOML file, and set
+ the secrets.
+4. Build and start the server from the repository root:
+
+ ```sh
+ bun --filter @open-pencil/cloud build:standalone
+ node packages/cloud/dist-standalone/server.mjs
+ ```
+
+The server migrates the database before it accepts requests and listens on `PORT` (default `8787`)
+and `HOST` (default `0.0.0.0`). `GET /ready` reports readiness. `dist-standalone/server.mjs`
+bundles its dependencies, so it can be copied to a host without `node_modules`.
+
+### Configuration
+
+The TOML file owns URLs, enrollment, authentication providers, storage, email, worker schedules,
+retention, entitlements, and technical limits. Environment variables only supply secrets, through
+these default references: `DATABASE_URL`, `BETTER_AUTH_SECRET`, `GOOGLE_CLIENT_ID`,
+`GOOGLE_CLIENT_SECRET`, `APPLE_PRIVATE_KEY`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`,
+`S3_SESSION_TOKEN`, `OPENPENCIL_CLOUD_SMTP_USER`, and `OPENPENCIL_CLOUD_SMTP_PASSWORD`. Use
+`{ from_env = "CUSTOM_NAME" }` to read a different variable. A missing required secret stops startup
+and names the variable without printing any value.
+
+### Enrollment and the first administrator
+
+Set `authentication.enrollment_mode = "approval"` for a controlled deployment: a verified identity
+then creates a pending request that an administrator reviews. Bootstrap the first operator with the
+operator commands below; startup never grants roles or changes enrollment state.
+
+```sh
+bun --filter @open-pencil/cloud admin approve [email protected]
+# after that person signs in once
+bun --filter @open-pencil/cloud admin grant [email protected]
+```
+
+Deployment administrators are separate from workspace administrators.
+`authentication.admin_user_ids` is an optional bootstrap list of immutable user IDs.
+
+### Operator commands
+
+Each command reads the same `OPENPENCIL_CLOUD_CONFIG` and secrets as the server:
+
+| Command | Purpose |
+| ------------------------------------------------- | ----------------------------------------------- |
+| `bun --filter @open-pencil/cloud migrate` | Apply database migrations |
+| `bun --filter @open-pencil/cloud cleanup` | Run one cleanup pass outside the server worker |
+| `bun --filter @open-pencil/cloud quota:reconcile` | Recompute stored usage from committed revisions |
+| `bun --filter @open-pencil/cloud entitlements` | Inspect or set a workspace's entitlements |
+| `bun --filter @open-pencil/cloud admin` | Approve enrollment and grant deployment admin |
+
+### Transactional email
+
+Set `email.transport = "smtp"` with an `[email.smtp]` table, or `"none"` to disable delivery; with
+`"none"`, invitations still work through their links but no email is queued. `deployment.app_url`
+is the editor origin used in invitation links and must also be in `deployment.trusted_origins`.
+Messages go through an encrypted PostgreSQL outbox, tuned under `[workers.email]`; delivery records
+that the relay accepted a message, not that it reached the inbox.
+
+### Production notes
+
+- Put the API and the object store behind TLS on stable hostnames.
+- Replace every development credential, including those in `seaweedfs/s3.json` if you use it.
+- Keep `object_storage.checksum_verification = "metadata"` for stores without native SHA-256
+ checksums; OpenPencil stores the document digest as object metadata and verifies it before
+ committing a revision.
+- Size `[workers.cleanup]` for your upload volume and retention, or set `enabled = false` and run
+ `cleanup` from a scheduler.
+- Back up PostgreSQL and the bucket. Immutable revision keys remove the need for bucket versioning
+ but are not a backup.
+
+## End-to-end tests
+
+```sh
+bun --filter @open-pencil/cloud test:e2e # PostgreSQL and SeaweedFS
+bun --filter @open-pencil/cloud test:e2e:garage # Garage S3 compatibility
+```
+
+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
+real PostgreSQL: migrations, idempotent commits, stale-base conflicts, multipart cleanup, usage, and
+soft deletion.
+
+The Garage profile ([`compose.garage.yml`](./compose.garage.yml)) pins Garage `v2.3.0` as a single
+node. Configure Cloud for it with `region = "garage"`, `force_path_style = true`, and
+`checksum_verification = "metadata"`, and leave server-side encryption unset.
diff --git a/packages/cloud/deploy/compose.garage.yml b/packages/cloud/deploy/compose.garage.yml
new file mode 100644
index 000000000..a5fe7561e
--- /dev/null
+++ b/packages/cloud/deploy/compose.garage.yml
@@ -0,0 +1,24 @@
+services:
+ garage:
+ image: dxflrs/garage:v2.3.0
+ command: ['/garage', 'server', '--single-node', '--default-bucket']
+ environment:
+ GARAGE_DEFAULT_ACCESS_KEY: ${GARAGE_ACCESS_KEY_ID:-GKopenpencildevelopment0000000000}
+ GARAGE_DEFAULT_SECRET_KEY: ${GARAGE_SECRET_ACCESS_KEY:-openpencil-garage-development-secret-key}
+ GARAGE_DEFAULT_BUCKET: ${GARAGE_BUCKET:-openpencil}
+ ports:
+ - '127.0.0.1:3900:3900'
+ - '127.0.0.1:3903:3903'
+ volumes:
+ - garage-meta:/var/lib/garage/meta
+ - garage-data:/var/lib/garage/data
+ - ./garage/garage.toml:/etc/garage.toml:ro
+ healthcheck:
+ test: ['CMD', '/garage', '-c', '/etc/garage.toml', 'status']
+ interval: 2s
+ timeout: 5s
+ retries: 30
+
+volumes:
+ garage-meta:
+ garage-data:
diff --git a/packages/cloud/deploy/compose.yml b/packages/cloud/deploy/compose.yml
new file mode 100644
index 000000000..d731eb023
--- /dev/null
+++ b/packages/cloud/deploy/compose.yml
@@ -0,0 +1,71 @@
+services:
+ mailpit:
+ image: axllent/mailpit:v1.31.0
+ environment:
+ MP_DATABASE: /data/mailpit.db
+ MP_DISABLE_VERSION_CHECK: 'true'
+ MP_MAX_AGE: 7d
+ MP_MAX_MESSAGES: 500
+ MP_SMTP_DISABLE_RDNS: 'true'
+ ports:
+ - '127.0.0.1:${MAILPIT_UI_PORT:-8025}:8025'
+ - '127.0.0.1:${MAILPIT_SMTP_PORT:-1025}:1025'
+ volumes:
+ - cloud-mailpit:/data
+
+ postgres:
+ image: postgres:17-alpine
+ environment:
+ POSTGRES_DB: openpencil
+ POSTGRES_USER: openpencil
+ POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-openpencil-development-password}
+ ports:
+ - '127.0.0.1:${POSTGRES_PORT:-54329}:5432'
+ healthcheck:
+ test: ['CMD-SHELL', 'pg_isready -U openpencil -d openpencil']
+ interval: 2s
+ timeout: 3s
+ retries: 30
+ volumes:
+ - cloud-postgres:/var/lib/postgresql/data
+
+ seaweedfs:
+ image: chrislusf/seaweedfs:4.41
+ command:
+ - server
+ - -dir=/data
+ - -s3
+ - -s3.port=8333
+ - -s3.config=/etc/seaweedfs/s3.json
+ ports:
+ - '127.0.0.1:${SEAWEEDFS_S3_PORT:-8333}:8333'
+ - '127.0.0.1:${SEAWEEDFS_MASTER_PORT:-9333}:9333'
+ volumes:
+ - cloud-seaweedfs:/data
+ - ./seaweedfs/s3.json:/etc/seaweedfs/s3.json:ro
+ healthcheck:
+ test: ['CMD', 'nc', '-z', '127.0.0.1', '8333']
+ interval: 2s
+ timeout: 3s
+ retries: 30
+
+ seaweedfs-init:
+ image: amazon/aws-cli:2.27.49
+ depends_on:
+ seaweedfs:
+ condition: service_healthy
+ environment:
+ AWS_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-openpencil}
+ AWS_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-openpencil-development-secret}
+ AWS_DEFAULT_REGION: ${S3_REGION:-us-east-1}
+ S3_BUCKET: ${S3_BUCKET:-openpencil}
+ entrypoint: ['/bin/sh', '-c']
+ command:
+ - >-
+ aws --endpoint-url http://seaweedfs:8333 s3api head-bucket --bucket $${S3_BUCKET}
+ || aws --endpoint-url http://seaweedfs:8333 s3api create-bucket --bucket $${S3_BUCKET}
+
+volumes:
+ cloud-mailpit:
+ cloud-postgres:
+ cloud-seaweedfs:
diff --git a/packages/cloud/deploy/garage/garage.toml b/packages/cloud/deploy/garage/garage.toml
new file mode 100644
index 000000000..e68334575
--- /dev/null
+++ b/packages/cloud/deploy/garage/garage.toml
@@ -0,0 +1,21 @@
+metadata_dir = "/var/lib/garage/meta"
+data_dir = "/var/lib/garage/data"
+db_engine = "sqlite"
+metadata_auto_snapshot_interval = "6h"
+
+replication_factor = 1
+compression_level = 2
+
+rpc_bind_addr = "[::]:3901"
+rpc_public_addr = "garage:3901"
+rpc_secret = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+
+[s3_api]
+s3_region = "garage"
+api_bind_addr = "[::]:3900"
+root_domain = ".s3.garage.localhost"
+
+[admin]
+api_bind_addr = "[::]:3903"
+admin_token = "openpencil-garage-admin-development-token"
+metrics_token = "openpencil-garage-metrics-development-token"
diff --git a/packages/cloud/deploy/openpencil-cloud.example.toml b/packages/cloud/deploy/openpencil-cloud.example.toml
new file mode 100644
index 000000000..9c0781d1c
--- /dev/null
+++ b/packages/cloud/deploy/openpencil-cloud.example.toml
@@ -0,0 +1,113 @@
+schema_version = 2
+
+[deployment]
+mode = "self-hosted"
+public_url = "http://localhost:8787"
+app_url = "http://localhost:5173"
+indexing = "deny"
+trusted_origins = ["http://localhost:5173"]
+# Editors read this only from the official OpenPencil Cloud: it shows Cloud in editors from this
+# version on. Self-hosted servers leave it out.
+# listing = { minimum_editor_version = "0.14.0" }
+
+# Defaults to DATABASE_URL.
+[database]
+
+[authentication]
+enrollment_mode = "open"
+admin_notification_emails = []
+# The signing secret defaults to BETTER_AUTH_SECRET.
+
+[authentication.mfa]
+deployment_admin_required = false
+totp_enabled = false
+passkeys_enabled = false
+recovery_codes_enabled = false
+trusted_device_days = 14
+
+# Required when passkeys are enabled.
+# [authentication.passkeys]
+# rp_id = "localhost"
+# rp_name = "OpenPencil Cloud"
+# origin = "http://localhost:8787"
+
+[authentication.email_password]
+enabled = false
+sign_up = true
+minimum_password_length = 8
+maximum_password_length = 128
+verification_link_expires_minutes = 60
+password_reset_link_expires_minutes = 60
+compromised_password_check = false
+
+# Recommended when enabling public sign-up. TURNSTILE_SECRET_KEY remains external.
+# [authentication.captcha]
+# provider = "cloudflare-turnstile"
+# site_key = "replace-with-public-site-key"
+# allowed_hostnames = ["cloud.example.com"]
+
+[authentication.trusted_proxies]
+headers = []
+addresses = []
+
+# Add this table to enable Google. The client secret defaults to
+# GOOGLE_CLIENT_SECRET. The client ID may instead use
+# client_id = { from_env = "GOOGLE_CLIENT_ID" }.
+# [authentication.providers.google]
+# client_id = "your-public-google-client-id"
+
+# Add this table to enable Apple. The private key defaults to APPLE_PRIVATE_KEY.
+# [authentication.providers.apple]
+# client_id = "dev.openpencil.cloud"
+# team_id = "TEAM_ID"
+# key_id = "KEY_ID"
+# app_bundle_identifier = "dev.openpencil"
+
+[object_storage]
+endpoint = "http://localhost:8333"
+region = "us-east-1"
+bucket = "openpencil"
+force_path_style = true
+checksum_verification = "metadata"
+# Credentials default to S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY.
+
+[email]
+transport = "none"
+
+[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 = 1_099_511_627_776
+
+[entitlements.sharing]
+capability_links = true
+anonymous_view = true
+anonymous_edit = true
+guest_presence = true
+
+[entitlements.collaboration]
+enabled = true
+maximum_participants = 100
+
+[technical_limits]
+maximum_upload_bytes = 1073741824
+maximum_collaboration_message_bytes = 1048576
+maximum_connections_per_room = 1000
diff --git a/packages/cloud/deploy/seaweedfs/s3.json b/packages/cloud/deploy/seaweedfs/s3.json
new file mode 100644
index 000000000..36af03304
--- /dev/null
+++ b/packages/cloud/deploy/seaweedfs/s3.json
@@ -0,0 +1,14 @@
+{
+ "identities": [
+ {
+ "name": "openpencil-cloud",
+ "credentials": [
+ {
+ "accessKey": "openpencil",
+ "secretKey": "openpencil-development-secret"
+ }
+ ],
+ "actions": ["Admin", "Read", "List", "Write"]
+ }
+ ]
+}
diff --git a/packages/cloud/deploy/security.md b/packages/cloud/deploy/security.md
new file mode 100644
index 000000000..12218f00d
--- /dev/null
+++ b/packages/cloud/deploy/security.md
@@ -0,0 +1,31 @@
+# Backend security checks
+
+OpenPencil Cloud handles authentication, bearer capabilities, database writes, and object-storage
+credentials, so it is held to stricter checks than the rest of the repository. They complement code
+review; they do not replace authorization and abuse-case testing.
+
+## Local checks
+
+```sh
+bun run test:cloud # type-check, unit, and PGlite integration tests
+bun --filter @open-pencil/cloud test:e2e # Docker Compose end-to-end suite
+bun run check:audit # fails on critical dependency advisories
+bun run check:secrets # Gitleaks over the working tree
+```
+
+## Stricter lint and types
+
+`oxlint.json` turns on type-aware rules for `packages/cloud/src`: no unsafe assignment, argument,
+call, member access, or return of `any`, exhaustive switches, and no deprecated APIs. The package
+`tsconfig.json` adds `noUncheckedIndexedAccess`, `noImplicitOverride`,
+`useUnknownInCatchVariables`, and `noFallthroughCasesInSwitch`.
+
+## Properties the code relies on
+
+- Lookups of private resources do not reveal whether the resource exists.
+- Every request body and every response the client reads is validated with Valibot.
+- Capability secrets and invitation tokens are stored as SHA-256 digests and compared in constant
+ time; they travel in URL fragments, never in paths or query strings.
+- OAuth continuations for invitations are single-use compact JWE.
+- Technical limits stay in force even if entitlement or policy data is wrong.
+- Presigned object transfers are separate from authenticated API requests.
diff --git a/packages/cloud/package.json b/packages/cloud/package.json
new file mode 100644
index 000000000..32241b2c4
--- /dev/null
+++ b/packages/cloud/package.json
@@ -0,0 +1,106 @@
+{
+ "name": "@open-pencil/cloud",
+ "version": "0.15.1",
+ "private": true,
+ "license": "MIT",
+ "type": "module",
+ "imports": {
+ "#cloud/*": {
+ "types": "./src/*",
+ "bun": "./src/*",
+ "default": "./dist/*"
+ },
+ "#cloud-tests/*": "./tests/*.ts"
+ },
+ "exports": {
+ "./contract": {
+ "types": "./dist/contract.d.ts",
+ "openpencil-source": "./src/contract/index.ts",
+ "bun": "./src/contract/index.ts",
+ "import": "./dist/contract.js",
+ "default": "./dist/contract.js"
+ },
+ "./client": {
+ "types": "./dist/client.d.ts",
+ "openpencil-source": "./src/client/index.ts",
+ "bun": "./src/client/index.ts",
+ "import": "./dist/client.js",
+ "default": "./dist/client.js"
+ },
+ "./email": {
+ "types": "./dist/email.d.ts",
+ "bun": "./src/email/index.ts",
+ "import": "./dist/email.js",
+ "default": "./dist/email.js"
+ },
+ "./runtime/node": {
+ "types": "./dist/runtime-node.d.mts",
+ "bun": "./src/runtime/node/index.ts",
+ "import": "./dist/runtime-node.mjs",
+ "default": "./dist/runtime-node.mjs"
+ },
+ "./server": {
+ "types": "./dist/server.d.ts",
+ "bun": "./src/server/index.ts",
+ "import": "./dist/server.js",
+ "default": "./dist/server.js"
+ }
+ },
+ "sideEffects": false,
+ "files": [
+ "dist"
+ ],
+ "scripts": {
+ "build": "bunx tsdown --config tsdown.config.ts",
+ "build:standalone": "bunx tsdown --config tsdown.standalone.config.ts",
+ "start": "node dist-standalone/server.mjs",
+ "dev": "bun --watch src/runtime/node/main.ts",
+ "check": "bun run typecheck && bun run test && bun run build",
+ "test": "bun run test:unit && bun run test:integration",
+ "test:unit": "bun test tests/client tests/contract tests/runtime tests/server",
+ "test:integration": "bun test --max-concurrency 8 tests/integration",
+ "test:e2e": "bun tests/e2e/run.ts",
+ "test:e2e:garage": "bun tests/e2e/garage.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.ts",
+ "admin": "bun src/runtime/node/admin.ts",
+ "typecheck": "bunx tsc --noEmit -p tsconfig.json"
+ },
+ "dependencies": {
+ "@aws-sdk/client-s3": "^3.1149.0",
+ "@aws-sdk/s3-request-presigner": "^3.1149.0",
+ "@better-auth/passkey": "1.7.7",
+ "@better-auth/utils": "0.4.2",
+ "@hono/node-server": "^1.19.17",
+ "@noble/hashes": "^2.4.0",
+ "@open-pencil/feedback": "workspace:*",
+ "@open-pencil/scene-graph": "workspace:*",
+ "@openfeature/server-sdk": "^1.23.0",
+ "@vue-email/components": "^0.0.21",
+ "@vue-email/render": "^0.0.9",
+ "better-auth": "1.7.7",
+ "es-toolkit": "^1.52.0",
+ "hono": "^4.13.13",
+ "hono-rate-limiter": "^0.5.3",
+ "jose": "^6.2.8",
+ "kysely": "^0.29.6",
+ "nodemailer": "^9.0.5",
+ "smol-toml": "^1.8.0",
+ "valibot": "^1.5.0",
+ "vue": "^3.5.43"
+ },
+ "optionalDependencies": {
+ "pg": "^8.23.0"
+ },
+ "devDependencies": {
+ "@electric-sql/pglite": "0.4.1",
+ "@types/bun": "^1.3.14",
+ "@types/nodemailer": "^8.0.1",
+ "@types/pg": "^8.21.0",
+ "kysely-pglite-dialect": "1.3.1",
+ "tsdown": "^0.22.14",
+ "typescript": "~5.8.3"
+ }
+}
diff --git a/packages/cloud/src/admin/api/routes.ts b/packages/cloud/src/admin/api/routes.ts
new file mode 100644
index 000000000..1ecd19b24
--- /dev/null
+++ b/packages/cloud/src/admin/api/routes.ts
@@ -0,0 +1,183 @@
+import { requireTrustedMutationOrigin } from '#cloud/admin/api/security'
+import type { AdminAuditService } from '#cloud/admin/audit/service'
+import {
+ enrollmentStatusSchema,
+ parseEnrollmentReview,
+ parseUserMutation,
+ parseUserRoleMutation
+} from '#cloud/admin/contracts'
+import type { AdminEmailService } from '#cloud/admin/email/service'
+import type { EnrollmentService } from '#cloud/admin/enrollment/service'
+import { adminErrorStatus, AdminDomainError } from '#cloud/admin/errors'
+import type { AdminOperationsService } from '#cloud/admin/operations/service'
+import type { AdminUserService } from '#cloud/admin/users/service'
+import type { CloudAPIEnvironment } from '#cloud/server/api'
+import type { CloudAuthAdapter } from '#cloud/server/auth'
+import type { CloudDatabase } from '#cloud/server/db'
+import { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'
+import { validatedJSON } from '#cloud/server/validation'
+import { Hono } from 'hono'
+import { NoResultError, type Kysely } from 'kysely'
+import * as v from 'valibot'
+
+const countSchema = v.pipe(v.string(), v.digits(), v.toNumber())
+
+/** A count from the query string; anything but digits is a bad request, not a NaN query. */
+function queryCount(value: string | undefined, fallback: number): number {
+ return value === undefined ? fallback : v.parse(countSchema, value)
+}
+
+export type CloudAdminServices = {
+ email: AdminEmailService
+ enrollment: EnrollmentService
+ users: AdminUserService
+ audit: AdminAuditService
+ operations: AdminOperationsService
+}
+
+export function createCloudAdminRoutes(
+ services: CloudAdminServices,
+ trustedOrigins: ReadonlySet<string>,
+ security: {
+ auth: CloudAuthAdapter
+ database: Kysely<CloudDatabase>
+ requireMFA: boolean
+ secret: string
+ }
+) {
+ const adminRead = createActorRateLimiter(
+ security.database,
+ security.secret,
+ CLOUD_RATE_LIMITS.adminRead,
+ (context) => context.req.method !== 'GET'
+ )
+ const adminMutation = createActorRateLimiter(
+ security.database,
+ security.secret,
+ CLOUD_RATE_LIMITS.adminMutation,
+ (context) => context.req.method === 'GET'
+ )
+ return new Hono<CloudAPIEnvironment>()
+ .use('*', requireTrustedMutationOrigin(trustedOrigins))
+ .use('*', async (context, next) => {
+ const actor = context.get('actor')
+ if (actor.deploymentRole !== 'admin') {
+ return context.json({ error: { code: 'forbidden' as const } }, 403)
+ }
+ if (security.requireMFA) {
+ const status = await security.auth.mfaStatus(context.req.raw.headers)
+ if (!status?.assured) {
+ return context.json({ error: { code: 'mfa_required' as const } }, 403)
+ }
+ }
+ return next()
+ })
+ .use('*', adminRead)
+ .use('*', adminMutation)
+ .onError((error, context) => {
+ if (error instanceof AdminDomainError) {
+ return context.json({ error: { code: error.code } }, adminErrorStatus(error))
+ }
+ if (error instanceof v.ValiError) {
+ return context.json({ error: { code: 'invalid_request' as const } }, 400)
+ }
+ // An enrollment or message ID that names nothing.
+ if (error instanceof NoResultError) {
+ return context.json({ error: { code: 'not_found' as const } }, 404)
+ }
+ throw error
+ })
+ .get('/enrollments', async (context) => {
+ const statusValue = context.req.query('status')
+ const status = statusValue ? v.parse(enrollmentStatusSchema, statusValue) : undefined
+ return context.json({ enrollments: await services.enrollment.list(status) })
+ })
+ .post('/enrollments/:id/approve', validatedJSON(parseEnrollmentReview), async (context) =>
+ context.json({
+ enrollment: await services.enrollment.review(
+ context.get('actor').userId,
+ context.req.param('id'),
+ 'approved',
+ context.req.valid('json')
+ )
+ })
+ )
+ .post('/enrollments/:id/reject', validatedJSON(parseEnrollmentReview), async (context) =>
+ context.json({
+ enrollment: await services.enrollment.review(
+ context.get('actor').userId,
+ context.req.param('id'),
+ 'rejected',
+ context.req.valid('json')
+ )
+ })
+ )
+ .post('/enrollments/:id/revoke', validatedJSON(parseEnrollmentReview), async (context) =>
+ context.json({
+ enrollment: await services.enrollment.review(
+ context.get('actor').userId,
+ context.req.param('id'),
+ 'revoked',
+ context.req.valid('json')
+ )
+ })
+ )
+ .get('/users', async (context) =>
+ context.json(
+ await services.users.list(context.req.raw.headers, {
+ searchValue: context.req.query('search'),
+ limit: queryCount(context.req.query('limit'), 100),
+ offset: queryCount(context.req.query('offset'), 0)
+ })
+ )
+ )
+ .post('/users/ban', validatedJSON(parseUserMutation), async (context) => {
+ const input = context.req.valid('json')
+ await services.users.ban(
+ context.req.raw.headers,
+ context.get('actor').userId,
+ input.userId,
+ input.reason
+ )
+ return context.json({ ok: true as const })
+ })
+ .post('/users/unban', validatedJSON(parseUserMutation), async (context) => {
+ const input = context.req.valid('json')
+ await services.users.unban(context.req.raw.headers, context.get('actor').userId, input.userId)
+ return context.json({ ok: true as const })
+ })
+ .post('/users/revoke-sessions', validatedJSON(parseUserMutation), async (context) => {
+ const input = context.req.valid('json')
+ await services.users.revokeSessions(
+ context.req.raw.headers,
+ context.get('actor').userId,
+ input.userId
+ )
+ return context.json({ ok: true as const })
+ })
+ .post('/users/set-admin', validatedJSON(parseUserRoleMutation), async (context) => {
+ const input = context.req.valid('json')
+ await services.users.setAdmin(
+ context.req.raw.headers,
+ context.get('actor').userId,
+ input.userId,
+ input.enabled
+ )
+ return context.json({ ok: true as const })
+ })
+ .get('/email', async (context) =>
+ context.json({
+ messages: await services.email.list(queryCount(context.req.query('limit'), 100))
+ })
+ )
+ .post('/email/:id/regenerate', async (context) => {
+ await services.email.regenerate(context.get('actor').userId, context.req.param('id'))
+ return context.json({ ok: true as const })
+ })
+ .get('/audit', async (context) =>
+ context.json({
+ events: await services.audit.list(queryCount(context.req.query('limit'), 100))
+ })
+ )
+ .get('/operations', async (context) => context.json(await services.operations.summary()))
+}
diff --git a/packages/cloud/src/admin/api/security.ts b/packages/cloud/src/admin/api/security.ts
new file mode 100644
index 000000000..8892179d3
--- /dev/null
+++ b/packages/cloud/src/admin/api/security.ts
@@ -0,0 +1,12 @@
+import type { Context, Next } from 'hono'
+
+export function requireTrustedMutationOrigin(trustedOrigins: ReadonlySet<string>) {
+ return async (context: Context, next: Next) => {
+ if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(context.req.method)) return next()
+ const origin = context.req.header('origin')
+ if (!origin || !trustedOrigins.has(origin)) {
+ return context.json({ error: { code: 'forbidden' as const } }, 403)
+ }
+ return next()
+ }
+}
diff --git a/packages/cloud/src/admin/audit/service.ts b/packages/cloud/src/admin/audit/service.ts
new file mode 100644
index 000000000..4b6e8a7b7
--- /dev/null
+++ b/packages/cloud/src/admin/audit/service.ts
@@ -0,0 +1,19 @@
+import { ADMIN_LIST_MAXIMUM } from '#cloud/admin/contracts'
+import type { CloudDatabase } from '#cloud/server/db'
+import { clamp } from 'es-toolkit'
+import type { Kysely } from 'kysely'
+
+export function createAdminAuditService(database: Kysely<CloudDatabase>) {
+ return {
+ async list(limit = 100) {
+ return database
+ .selectFrom('cloudAdminAuditEvent')
+ .selectAll()
+ .orderBy('createdAt', 'desc')
+ .limit(clamp(limit, 1, ADMIN_LIST_MAXIMUM))
+ .execute()
+ }
+ }
+}
+
+export type AdminAuditService = ReturnType<typeof createAdminAuditService>
diff --git a/packages/cloud/src/admin/contracts.ts b/packages/cloud/src/admin/contracts.ts
new file mode 100644
index 000000000..ee1481101
--- /dev/null
+++ b/packages/cloud/src/admin/contracts.ts
@@ -0,0 +1,24 @@
+import * as v from 'valibot'
+
+/** The most rows one admin list request returns. */
+export const ADMIN_LIST_MAXIMUM = 500
+
+export const enrollmentStatusSchema = v.picklist(['pending', 'approved', 'rejected', 'revoked'])
+export const enrollmentReviewSchema = v.object({
+ note: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(1000)))
+})
+export const userRoleMutationSchema = v.object({
+ userId: v.pipe(v.string(), v.trim(), v.minLength(1)),
+ enabled: v.boolean()
+})
+
+export const userMutationSchema = v.object({
+ userId: v.pipe(v.string(), v.trim(), v.minLength(1)),
+ reason: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(500)))
+})
+
+export type EnrollmentReview = v.InferOutput<typeof enrollmentReviewSchema>
+
+export const parseEnrollmentReview = (input: unknown) => v.parse(enrollmentReviewSchema, input)
+export const parseUserMutation = (input: unknown) => v.parse(userMutationSchema, input)
+export const parseUserRoleMutation = (input: unknown) => v.parse(userRoleMutationSchema, input)
diff --git a/packages/cloud/src/admin/email/service.ts b/packages/cloud/src/admin/email/service.ts
new file mode 100644
index 000000000..6b268803a
--- /dev/null
+++ b/packages/cloud/src/admin/email/service.ts
@@ -0,0 +1,104 @@
+import { ADMIN_LIST_MAXIMUM } from '#cloud/admin/contracts'
+import type { EnrollmentStatus } from '#cloud/admin/enrollment/service'
+import { AdminDomainError } from '#cloud/admin/errors'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { TransactionalEmailService } from '#cloud/server/email'
+import { clamp } from 'es-toolkit'
+import type { Kysely } from 'kysely'
+
+/** The enrollment status each message describes; a message is resent only while it still holds. */
+const ENROLLMENT_MESSAGE_STATUS: Partial<Record<string, EnrollmentStatus>> = {
+ 'enrollment-requested': 'pending',
+ 'enrollment-approved': 'approved',
+ 'enrollment-rejected': 'rejected',
+ 'enrollment-revoked': 'revoked'
+}
+
+export function createAdminEmailService(
+ database: Kysely<CloudDatabase>,
+ email?: TransactionalEmailService,
+ appURL = ''
+) {
+ return {
+ async list(limit = 100) {
+ const rows = await database
+ .selectFrom('transactionalEmail')
+ .select([
+ 'id',
+ 'kind',
+ 'recipientEmailNormalized',
+ 'status',
+ 'attemptCount',
+ 'nextAttemptAt',
+ 'transport',
+ 'transportMessageId',
+ 'lastErrorCode',
+ 'createdAt',
+ 'acceptedAt'
+ ])
+ .orderBy('createdAt', 'desc')
+ .limit(clamp(limit, 1, ADMIN_LIST_MAXIMUM))
+ .execute()
+ return rows.map((row) => ({ ...row, regeneratable: row.kind.startsWith('enrollment-') }))
+ },
+ async regenerate(actorId: string, messageId: string): Promise<void> {
+ if (!email)
+ throw new AdminDomainError('email_regeneration_unavailable', 'Email delivery is disabled')
+ await database.transaction().execute(async (transaction) => {
+ const original = await transaction
+ .selectFrom('transactionalEmail')
+ .select(['id', 'kind', 'recipientEmailNormalized'])
+ .where('id', '=', messageId)
+ .executeTakeFirstOrThrow()
+ if (
+ !original.kind.startsWith('enrollment-') ||
+ original.kind === 'admin-enrollment-notification'
+ ) {
+ throw new AdminDomainError(
+ 'email_regeneration_unavailable',
+ 'This message cannot be regenerated'
+ )
+ }
+ const kind = original.kind
+ const enrollment = await transaction
+ .selectFrom('cloudEnrollment')
+ .selectAll()
+ .where('emailNormalized', '=', original.recipientEmailNormalized)
+ .executeTakeFirst()
+ if (!enrollment)
+ throw new AdminDomainError('email_regeneration_unavailable', 'Enrollment is unavailable')
+ if (ENROLLMENT_MESSAGE_STATUS[kind] !== enrollment.status) {
+ throw new AdminDomainError(
+ 'email_regeneration_unavailable',
+ 'The enrollment no longer matches this message'
+ )
+ }
+ await email.enqueue(
+ {
+ idempotencyKey: `admin-regeneration/${messageId}/${crypto.randomUUID()}`,
+ kind,
+ recipientEmail: enrollment.emailNormalized,
+ payload: {
+ name: enrollment.name ?? 'there',
+ actionURL: kind === 'enrollment-approved' ? appURL : `${appURL}/auth/sign-in`
+ }
+ },
+ transaction
+ )
+ await transaction
+ .insertInto('cloudAdminAuditEvent')
+ .values({
+ id: crypto.randomUUID(),
+ actorUserId: actorId,
+ action: 'email.regenerated',
+ subjectType: 'transactional-email',
+ subjectId: messageId,
+ metadata: { replacementKind: kind }
+ })
+ .execute()
+ })
+ }
+ }
+}
+
+export type AdminEmailService = ReturnType<typeof createAdminEmailService>
diff --git a/packages/cloud/src/admin/enrollment/email.ts b/packages/cloud/src/admin/enrollment/email.ts
new file mode 100644
index 000000000..6be9b2ffc
--- /dev/null
+++ b/packages/cloud/src/admin/enrollment/email.ts
@@ -0,0 +1,70 @@
+import type { CloudDatabase } from '#cloud/server/db'
+import type { TransactionalEmailService } from '#cloud/server/email'
+import type { Transaction } from 'kysely'
+
+import type { EnrollmentStatus } from './service'
+
+export type EnrollmentEmailOptions = {
+ appURL: string
+ adminRecipients: string[]
+ email?: TransactionalEmailService
+}
+
+export async function enqueueEnrollmentRequested(
+ transaction: Transaction<CloudDatabase>,
+ options: EnrollmentEmailOptions,
+ input: { enrollmentId: string; email: string; name: string; reason: string; revision: number }
+): Promise<void> {
+ if (!options.email) return
+ await options.email.enqueue(
+ {
+ idempotencyKey: `enrollment-requested/${input.enrollmentId}/${input.revision}`,
+ kind: 'enrollment-requested',
+ recipientEmail: input.email,
+ payload: { name: input.name, actionURL: `${options.appURL}/auth/sign-in` }
+ },
+ transaction
+ )
+ for (const recipientEmail of options.adminRecipients) {
+ await options.email.enqueue(
+ {
+ idempotencyKey: `admin-enrollment-notification/${input.enrollmentId}/${input.revision}/${recipientEmail}`,
+ kind: 'admin-enrollment-notification',
+ recipientEmail,
+ payload: {
+ requesterEmail: input.email,
+ requesterName: input.name,
+ reason: input.reason,
+ actionURL: `${options.appURL}/admin/enrollment`
+ }
+ },
+ transaction
+ )
+ }
+}
+
+export async function enqueueEnrollmentReview(
+ transaction: Transaction<CloudDatabase>,
+ options: EnrollmentEmailOptions,
+ input: {
+ enrollmentId: string
+ recipientEmail: string
+ name: string
+ status: Exclude<EnrollmentStatus, 'pending'>
+ reviewedAt: Date
+ }
+): Promise<void> {
+ if (!options.email) return
+ await options.email.enqueue(
+ {
+ idempotencyKey: `enrollment-${input.status}/${input.enrollmentId}/${input.reviewedAt.toISOString()}`,
+ kind: `enrollment-${input.status}`,
+ recipientEmail: input.recipientEmail,
+ payload: {
+ name: input.name,
+ actionURL: input.status === 'approved' ? options.appURL : `${options.appURL}/auth/sign-in`
+ }
+ },
+ transaction
+ )
+}
diff --git a/packages/cloud/src/admin/enrollment/service.ts b/packages/cloud/src/admin/enrollment/service.ts
new file mode 100644
index 000000000..74f3e1a60
--- /dev/null
+++ b/packages/cloud/src/admin/enrollment/service.ts
@@ -0,0 +1,225 @@
+import { AdminDomainError } from '#cloud/admin/errors'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { Kysely } from 'kysely'
+
+import {
+ enqueueEnrollmentRequested,
+ enqueueEnrollmentReview,
+ type EnrollmentEmailOptions
+} from './email'
+
+export type EnrollmentStatus = 'pending' | 'approved' | 'rejected' | 'revoked'
+export type EnrollmentMode = 'open' | 'approval' | 'closed'
+
+export type EnrollmentRequestInput = { email: string; name?: string; reason?: string }
+export type EnrollmentReviewInput = { note?: string }
+export type EnrollmentRecord = {
+ id: string
+ email: string
+ name: string | null
+ reason: string | null
+ status: EnrollmentStatus
+ requestedAt: string
+ reviewedAt: string | null
+ reviewedBy: string | null
+ reviewNote: string | null
+ approvedUserId: string | null
+ requestRevision: number
+}
+
+type EnrollmentRow = {
+ id: string
+ emailNormalized: string
+ name: string | null
+ reason: string | null
+ status: EnrollmentStatus
+ requestedAt: Date | string
+ reviewedAt: Date | string | null
+ reviewedBy: string | null
+ reviewNote: string | null
+ approvedUserId: string | null
+ requestRevision: number
+}
+
+const ALLOWED_TRANSITIONS: Record<EnrollmentStatus, ReadonlySet<EnrollmentStatus>> = {
+ pending: new Set(['approved', 'rejected']),
+ approved: new Set(['revoked']),
+ rejected: new Set(['pending', 'approved']),
+ revoked: new Set(['pending', 'approved'])
+}
+
+function dateString(value: Date | string | null): string | null {
+ return value ? new Date(value).toISOString() : null
+}
+function enrollmentRecord(row: EnrollmentRow): EnrollmentRecord {
+ return {
+ id: row.id,
+ email: row.emailNormalized,
+ name: row.name,
+ reason: row.reason,
+ status: row.status,
+ requestedAt: dateString(row.requestedAt) ?? '',
+ reviewedAt: dateString(row.reviewedAt),
+ reviewedBy: row.reviewedBy,
+ reviewNote: row.reviewNote,
+ approvedUserId: row.approvedUserId,
+ requestRevision: row.requestRevision
+ }
+}
+export function normalizeEnrollmentEmail(value: string): string {
+ return value.trim().toLowerCase()
+}
+
+export function createEnrollmentService(
+ database: Kysely<CloudDatabase>,
+ emailOptions: EnrollmentEmailOptions = { appURL: '', adminRecipients: [] }
+) {
+ const statusForEmail = async (email: string): Promise<EnrollmentStatus | null> => {
+ const row = await database
+ .selectFrom('cloudEnrollment')
+ .select('status')
+ .where('emailNormalized', '=', normalizeEnrollmentEmail(email))
+ .executeTakeFirst()
+ return row?.status ?? null
+ }
+ return {
+ async request(input: EnrollmentRequestInput): Promise<void> {
+ const emailNormalized = normalizeEnrollmentEmail(input.email)
+ await database.transaction().execute(async (transaction) => {
+ const existing = await transaction
+ .selectFrom('cloudEnrollment')
+ .selectAll()
+ .where('emailNormalized', '=', emailNormalized)
+ .forUpdate()
+ .executeTakeFirst()
+ if (existing?.status === 'approved' || existing?.status === 'pending') return
+ const revision = (existing?.requestRevision ?? 0) + 1
+ const values = {
+ name: input.name?.trim() || existing?.name || null,
+ reason: input.reason?.trim() || null,
+ status: 'pending' as const,
+ reviewedAt: null,
+ reviewedBy: null,
+ reviewNote: null,
+ requestRevision: revision
+ }
+ let row: EnrollmentRow
+ if (existing) {
+ row = await transaction
+ .updateTable('cloudEnrollment')
+ .set(values)
+ .where('id', '=', existing.id)
+ .returningAll()
+ .executeTakeFirstOrThrow()
+ } else {
+ row = await transaction
+ .insertInto('cloudEnrollment')
+ .values({
+ id: crypto.randomUUID(),
+ emailNormalized,
+ ...values,
+ approvedUserId: null
+ })
+ .returningAll()
+ .executeTakeFirstOrThrow()
+ }
+ await enqueueEnrollmentRequested(transaction, emailOptions, {
+ enrollmentId: row.id,
+ email: row.emailNormalized,
+ name: row.name ?? 'there',
+ reason: row.reason ?? 'No reason provided.',
+ revision
+ })
+ })
+ },
+ statusForEmail,
+ async isApproved(email: string): Promise<boolean> {
+ return (await statusForEmail(email)) === 'approved'
+ },
+ async list(status?: EnrollmentStatus): Promise<EnrollmentRecord[]> {
+ let query = database.selectFrom('cloudEnrollment').selectAll()
+ if (status) query = query.where('status', '=', status)
+ return (await query.orderBy('requestedAt', 'desc').execute()).map(enrollmentRecord)
+ },
+ async review(
+ actorId: string,
+ enrollmentId: string,
+ status: Exclude<EnrollmentStatus, 'pending'>,
+ input: EnrollmentReviewInput
+ ): Promise<EnrollmentRecord> {
+ return database.transaction().execute(async (transaction) => {
+ const current = await transaction
+ .selectFrom('cloudEnrollment')
+ .selectAll()
+ .where('id', '=', enrollmentId)
+ .forUpdate()
+ .executeTakeFirstOrThrow()
+ if (!ALLOWED_TRANSITIONS[current.status].has(status)) {
+ throw new AdminDomainError(
+ 'invalid_enrollment_transition',
+ `Enrollment cannot transition from ${current.status} to ${status}`
+ )
+ }
+ const now = new Date()
+ const approvedUser =
+ status === 'approved'
+ ? await transaction
+ .selectFrom('user')
+ .select('id')
+ .where('email', '=', current.emailNormalized)
+ .executeTakeFirst()
+ : undefined
+ const row = await transaction
+ .updateTable('cloudEnrollment')
+ .set({
+ status,
+ reviewedAt: now,
+ reviewedBy: actorId,
+ reviewNote: input.note?.trim() || null,
+ approvedUserId: approvedUser?.id ?? current.approvedUserId
+ })
+ .where('id', '=', enrollmentId)
+ .where('status', '=', current.status)
+ .returningAll()
+ .executeTakeFirstOrThrow()
+ await transaction
+ .insertInto('cloudAdminAuditEvent')
+ .values({
+ id: crypto.randomUUID(),
+ actorUserId: actorId,
+ action: `enrollment.${status}`,
+ subjectType: 'enrollment',
+ subjectId: enrollmentId,
+ metadata: { email: row.emailNormalized },
+ createdAt: now
+ })
+ .execute()
+ await enqueueEnrollmentReview(transaction, emailOptions, {
+ enrollmentId,
+ recipientEmail: row.emailNormalized,
+ name: row.name ?? 'there',
+ status,
+ reviewedAt: now
+ })
+ return enrollmentRecord(row)
+ })
+ },
+ async bindApprovedUser(email: string, userId: string): Promise<void> {
+ await database
+ .updateTable('cloudEnrollment')
+ .set({ approvedUserId: userId })
+ .where('emailNormalized', '=', normalizeEnrollmentEmail(email))
+ .where('status', '=', 'approved')
+ .execute()
+ },
+ async pendingCount(): Promise<number> {
+ const row = await database
+ .selectFrom('cloudEnrollment')
+ .select(({ fn }) => fn.countAll<number>().as('count'))
+ .where('status', '=', 'pending')
+ .executeTakeFirstOrThrow()
+ return Number(row.count)
+ }
+ }
+}
+export type EnrollmentService = ReturnType<typeof createEnrollmentService>
diff --git a/packages/cloud/src/admin/errors.ts b/packages/cloud/src/admin/errors.ts
new file mode 100644
index 000000000..12b92181b
--- /dev/null
+++ b/packages/cloud/src/admin/errors.ts
@@ -0,0 +1,20 @@
+export type AdminErrorCode =
+ | 'invalid_enrollment_transition'
+ | 'last_admin_required'
+ | 'self_admin_action_forbidden'
+ | 'email_regeneration_unavailable'
+ | 'mfa_required'
+
+export class AdminDomainError extends Error {
+ override readonly name = 'AdminDomainError'
+ constructor(
+ readonly code: AdminErrorCode,
+ message: string
+ ) {
+ super(message)
+ }
+}
+
+export function adminErrorStatus(error: AdminDomainError): 400 | 409 {
+ return error.code === 'invalid_enrollment_transition' ? 409 : 400
+}
diff --git a/packages/cloud/src/admin/index.ts b/packages/cloud/src/admin/index.ts
new file mode 100644
index 000000000..18b4f695d
--- /dev/null
+++ b/packages/cloud/src/admin/index.ts
@@ -0,0 +1,15 @@
+export { adminErrorStatus, AdminDomainError, type AdminErrorCode } from './errors'
+export { createCloudAdminRoutes, type CloudAdminServices } from './api/routes'
+export { createAdminAuditService, type AdminAuditService } from './audit/service'
+export { createAdminEmailService, type AdminEmailService } from './email/service'
+export { PostgresRateLimitStore } from '#cloud/server/rate-limit'
+export {
+ createEnrollmentService,
+ normalizeEnrollmentEmail,
+ type EnrollmentMode,
+ type EnrollmentRecord,
+ type EnrollmentService,
+ type EnrollmentStatus
+} from './enrollment/service'
+export { createAdminOperationsService, type AdminOperationsService } from './operations/service'
+export { createAdminUserService, type AdminUserService } from './users/service'
diff --git a/packages/cloud/src/admin/operations/service.ts b/packages/cloud/src/admin/operations/service.ts
new file mode 100644
index 000000000..c9db49cf0
--- /dev/null
+++ b/packages/cloud/src/admin/operations/service.ts
@@ -0,0 +1,41 @@
+import type { CloudServerConfig } from '#cloud/server/config'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { Kysely } from 'kysely'
+
+export function createAdminOperationsService(
+ database: Kysely<CloudDatabase>,
+ config: CloudServerConfig
+) {
+ async function emailCount(status: 'pending' | 'failed'): Promise<number> {
+ const row = await database
+ .selectFrom('transactionalEmail')
+ .select(({ fn }) => fn.countAll<number>().as('count'))
+ .where('status', '=', status)
+ .executeTakeFirstOrThrow()
+ return Number(row.count)
+ }
+
+ return {
+ async summary() {
+ const [pendingEnrollment, pendingEmail, failedEmail] = await Promise.all([
+ database
+ .selectFrom('cloudEnrollment')
+ .select(({ fn }) => fn.countAll<number>().as('count'))
+ .where('status', '=', 'pending')
+ .executeTakeFirstOrThrow(),
+ emailCount('pending'),
+ emailCount('failed')
+ ])
+ return {
+ deployment: config.deployment,
+ enrollmentMode: config.enrollmentMode,
+ emailTransport: config.emailTransport,
+ pendingEnrollment: Number(pendingEnrollment.count),
+ pendingEmail,
+ failedEmail
+ }
+ }
+ }
+}
+
+export type AdminOperationsService = ReturnType<typeof createAdminOperationsService>
diff --git a/packages/cloud/src/admin/users/service.ts b/packages/cloud/src/admin/users/service.ts
new file mode 100644
index 000000000..fd587773f
--- /dev/null
+++ b/packages/cloud/src/admin/users/service.ts
@@ -0,0 +1,111 @@
+import { ADMIN_LIST_MAXIMUM } from '#cloud/admin/contracts'
+import { AdminDomainError } from '#cloud/admin/errors'
+import type { CloudAuthAdapter } from '#cloud/server/auth'
+import type { CloudDatabase } from '#cloud/server/db'
+import { clamp } from 'es-toolkit'
+import type { Kysely } from 'kysely'
+
+export function createAdminUserService(
+ database: Kysely<CloudDatabase>,
+ auth: CloudAuthAdapter,
+ options: { requireMFA?: boolean } = {}
+) {
+ async function audit(actorId: string, action: string, userId: string): Promise<void> {
+ await database
+ .insertInto('cloudAdminAuditEvent')
+ .values({
+ id: crypto.randomUUID(),
+ actorUserId: actorId,
+ action,
+ subjectType: 'user',
+ subjectId: userId,
+ metadata: {}
+ })
+ .execute()
+ }
+
+ async function requireSafeTarget(
+ actorId: string,
+ userId: string,
+ action: 'ban' | 'demote'
+ ): Promise<void> {
+ if (actorId === userId) {
+ throw new AdminDomainError(
+ 'self_admin_action_forbidden',
+ `Administrators cannot ${action} themselves`
+ )
+ }
+ const target = await database
+ .selectFrom('user')
+ .select('role')
+ .where('id', '=', userId)
+ .executeTakeFirst()
+ if (target?.role !== 'admin') return
+ const count = await database
+ .selectFrom('user')
+ .select(({ fn }) => fn.countAll<number>().as('count'))
+ .where('role', '=', 'admin')
+ .where((expression) =>
+ expression.or([expression('banned', '=', false), expression('banned', 'is', null)])
+ )
+ .executeTakeFirstOrThrow()
+ if (Number(count.count) <= 1) {
+ throw new AdminDomainError(
+ 'last_admin_required',
+ 'Cannot remove the last deployment administrator'
+ )
+ }
+ }
+
+ return {
+ list(headers: Headers, query?: { searchValue?: string; limit?: number; offset?: number }) {
+ return auth.listUsers(headers, {
+ ...query,
+ limit: clamp(query?.limit ?? 100, 1, ADMIN_LIST_MAXIMUM)
+ })
+ },
+ async ban(headers: Headers, actorId: string, userId: string, reason?: string): Promise<void> {
+ await requireSafeTarget(actorId, userId, 'ban')
+ await auth.banUser(headers, userId, reason)
+ await audit(actorId, 'user.banned', userId)
+ },
+ async unban(headers: Headers, actorId: string, userId: string): Promise<void> {
+ await auth.unbanUser(headers, userId)
+ await audit(actorId, 'user.unbanned', userId)
+ },
+ async revokeSessions(headers: Headers, actorId: string, userId: string): Promise<void> {
+ await auth.revokeUserSessions(headers, userId)
+ await audit(actorId, 'user.sessions-revoked', userId)
+ },
+ async setAdmin(
+ headers: Headers,
+ actorId: string,
+ userId: string,
+ enabled: boolean
+ ): Promise<void> {
+ if (!enabled) await requireSafeTarget(actorId, userId, 'demote')
+ if (enabled && options.requireMFA) {
+ const user = await database
+ .selectFrom('user')
+ .select('twoFactorEnabled')
+ .where('id', '=', userId)
+ .executeTakeFirst()
+ const passkey = await database
+ .selectFrom('passkey')
+ .select('id')
+ .where('userId', '=', userId)
+ .executeTakeFirst()
+ if (!user?.twoFactorEnabled && !passkey) {
+ throw new AdminDomainError(
+ 'mfa_required',
+ 'Users must enroll MFA before becoming deployment administrators'
+ )
+ }
+ }
+ await auth.setRole(headers, userId, enabled ? 'admin' : 'user')
+ await audit(actorId, enabled ? 'user.admin-granted' : 'user.admin-revoked', userId)
+ }
+ }
+}
+
+export type AdminUserService = ReturnType<typeof createAdminUserService>
diff --git a/packages/cloud/src/client/api.ts b/packages/cloud/src/client/api.ts
new file mode 100644
index 000000000..144669f94
--- /dev/null
+++ b/packages/cloud/src/client/api.ts
@@ -0,0 +1,450 @@
+import type { CloudFetch } from '#cloud/client/discovery'
+import {
+ acceptedInvitationSchema,
+ cloudSessionSchema,
+ cloudUserProfileSchema,
+ collaborationTicketSchema,
+ createInvitationContinuationSchema,
+ documentAccessSchema,
+ documentDownloadSchema,
+ documentGrantSchema,
+ documentInvitationSchema,
+ documentShareSchema,
+ documentSummarySchema,
+ sharedDocumentSchema,
+ invitationContinuationSchema,
+ invitationPreviewSchema,
+ resolvedDocumentShareSchema,
+ type AcceptDocumentInvitationInput,
+ type CloudSession,
+ type CloudUserProfile,
+ type CollaborationTicket,
+ type CreateInvitationContinuationInput,
+ type InvitationContinuation,
+ type CommitUploadInput,
+ type CreateDocumentInput,
+ type CreateDocumentInvitationInput,
+ type CreateDocumentShareInput,
+ type CreateUploadInput,
+ type DocumentAccess,
+ type DocumentDownload,
+ type DocumentGrant,
+ type DocumentInvitation,
+ type DocumentShare,
+ type DocumentSummary,
+ type SharedDocument,
+ type InvitationPreview,
+ type LookupCloudUserInput,
+ type PutDocumentGrantInput,
+ type ResolveDocumentShareInput,
+ type UpdateDocumentShareInput,
+ type AcceptedInvitation
+} from '#cloud/contract'
+import type { CloudAPI, PublicCloudAPI } from '#cloud/server/api'
+import { hc } from 'hono/client'
+import * as v from 'valibot'
+
+import { CloudAPIError, parseResponse, responseBody, type CloudClientDiagnostic } from './response'
+import { createWorkspaceRequests } from './workspaces'
+
+export { CloudAPIError, type CloudClientDiagnostic } from './response'
+
+const documentsResponseSchema = v.object({ documents: v.array(documentSummarySchema) })
+const sharedDocumentsResponseSchema = v.object({ documents: v.array(sharedDocumentSchema) })
+const documentResponseSchema = v.object({ document: documentSummarySchema })
+const downloadResponseSchema = v.object({ document: documentDownloadSchema })
+const accessResponseSchema = v.object({ access: documentAccessSchema })
+const sharesResponseSchema = v.object({ shares: v.array(documentShareSchema) })
+const shareResponseSchema = v.object({ share: documentShareSchema })
+const shareCapabilityResponseSchema = v.object({
+ share: documentShareSchema,
+ secret: v.string(),
+ path: v.string()
+})
+const grantsResponseSchema = v.object({ grants: v.array(documentGrantSchema) })
+const grantResponseSchema = v.object({ grant: documentGrantSchema })
+const acceptedResponseSchema = v.object({ accepted: acceptedInvitationSchema })
+const invitationPreviewResponseSchema = v.object({ invitation: invitationPreviewSchema })
+const invitationsResponseSchema = v.object({ invitations: v.array(documentInvitationSchema) })
+const invitationCapabilityResponseSchema = v.object({
+ invitation: documentInvitationSchema,
+ token: v.string()
+})
+const collaborationTicketResponseSchema = v.object({ ticket: collaborationTicketSchema })
+const resolvedShareResponseSchema = v.object({ resolution: resolvedDocumentShareSchema })
+const sharedDocumentResponseSchema = v.object({
+ resolution: resolvedDocumentShareSchema,
+ document: documentDownloadSchema
+})
+const userLookupResponseSchema = v.object({ user: v.nullable(cloudUserProfileSchema) })
+const uploadResponseSchema = v.object({
+ id: v.pipe(v.string(), v.uuid()),
+ upload: v.variant('kind', [
+ v.object({
+ kind: v.literal('single'),
+ url: v.pipe(v.string(), v.url()),
+ method: v.literal('PUT'),
+ headers: v.record(v.string(), v.string()),
+ expiresAt: v.string()
+ }),
+ v.object({
+ kind: v.literal('multipart'),
+ uploadId: v.string(),
+ partSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
+ parts: v.array(
+ v.object({
+ partNumber: v.pipe(v.number(), v.integer(), v.minValue(1)),
+ url: v.pipe(v.string(), v.url()),
+ method: v.literal('PUT'),
+ headers: v.record(v.string(), v.string())
+ })
+ ),
+ expiresAt: v.string()
+ })
+ ])
+})
+
+export type CloudRequestOptions = {
+ fetch?: CloudFetch
+ signal?: AbortSignal
+ accessToken?: string
+ onDiagnostic?: CloudClientDiagnostic
+}
+
+export type CloudUpload = v.InferOutput<typeof uploadResponseSchema>
+
+function apiURL(baseURL: string): string {
+ const url = new URL(baseURL)
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
+ throw new CloudAPIError('OpenPencil Cloud API URL must use HTTP or HTTPS', 0)
+ }
+ url.pathname = url.pathname.replace(/\/$/, '')
+ url.search = ''
+ url.hash = ''
+ return url.href
+}
+
+export function createCloudAPIClient(baseURL: string, options: CloudRequestOptions = {}) {
+ const headers = {
+ 'Content-Type': 'application/json',
+ ...(options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {})
+ }
+ const client = hc<CloudAPI>(apiURL(baseURL), {
+ fetch: options.fetch,
+ init: { credentials: 'include', signal: options.signal, headers }
+ })
+ const publicClient = hc<PublicCloudAPI>(apiURL(baseURL), {
+ fetch: options.fetch,
+ init: { credentials: 'include', signal: options.signal, headers }
+ })
+
+ return {
+ async getSession(): Promise<CloudSession | null> {
+ const response = await client.session.$get()
+ if (response.status === 401) return null
+ return v.parse(cloudSessionSchema, await responseBody(response, options.onDiagnostic))
+ },
+ async lookupUser(
+ documentId: string,
+ input: LookupCloudUserInput
+ ): Promise<CloudUserProfile | null> {
+ const response = await parseResponse(
+ client.documents[':documentId'].users.lookup.$post({
+ param: { documentId },
+ json: input
+ }),
+ userLookupResponseSchema,
+ options.onDiagnostic
+ )
+ return response.user
+ },
+ async getUserProfile(documentId: string, userId: string): Promise<CloudUserProfile | null> {
+ const response = await parseResponse(
+ client.documents[':documentId'].users[':userId'].$get({
+ param: { documentId, userId }
+ }),
+ userLookupResponseSchema,
+ options.onDiagnostic
+ )
+ return response.user
+ },
+ ...createWorkspaceRequests(client, options.onDiagnostic),
+ /** Documents shared with the person directly, outside their workspaces. */
+ async listSharedDocuments(): Promise<SharedDocument[]> {
+ const response = await parseResponse(
+ client['shared-documents'].$get(),
+ sharedDocumentsResponseSchema,
+ options.onDiagnostic
+ )
+ return response.documents
+ },
+ async listDocuments(workspaceId: string): Promise<DocumentSummary[]> {
+ const response = await parseResponse(
+ client.workspaces[':workspaceId'].documents.$get({
+ param: { workspaceId }
+ }),
+ documentsResponseSchema,
+ options.onDiagnostic
+ )
+ return response.documents
+ },
+ async createDocument(
+ workspaceId: string,
+ input: CreateDocumentInput
+ ): Promise<DocumentSummary> {
+ const response = await parseResponse(
+ client.workspaces[':workspaceId'].documents.$post({
+ param: { workspaceId },
+ json: input
+ }),
+ documentResponseSchema,
+ options.onDiagnostic
+ )
+ return response.document
+ },
+ async deleteDocument(documentId: string): Promise<void> {
+ await responseBody(
+ await client.documents[':documentId'].$delete({ param: { documentId } }),
+ options.onDiagnostic
+ )
+ },
+ async getDocument(documentId: string): Promise<DocumentDownload> {
+ const response = await parseResponse(
+ client.documents[':documentId'].$get({ param: { documentId } }),
+ downloadResponseSchema,
+ options.onDiagnostic
+ )
+ return response.document
+ },
+ async getDocumentAccess(documentId: string): Promise<DocumentAccess> {
+ const response = await parseResponse(
+ client.documents[':documentId'].access.$get({ param: { documentId } }),
+ accessResponseSchema,
+ options.onDiagnostic
+ )
+ return response.access
+ },
+ async listDocumentShares(documentId: string): Promise<DocumentShare[]> {
+ const response = await parseResponse(
+ client.documents[':documentId'].shares.$get({ param: { documentId } }),
+ sharesResponseSchema,
+ options.onDiagnostic
+ )
+ return response.shares
+ },
+ async createDocumentShare(documentId: string, input: CreateDocumentShareInput) {
+ return parseResponse(
+ client.documents[':documentId'].shares.$post({
+ param: { documentId },
+ json: input
+ }),
+ shareCapabilityResponseSchema,
+ options.onDiagnostic
+ )
+ },
+ async updateDocumentShare(
+ documentId: string,
+ shareId: string,
+ input: UpdateDocumentShareInput
+ ): Promise<DocumentShare> {
+ const response = await parseResponse(
+ client.documents[':documentId'].shares[':shareId'].$patch({
+ param: { documentId, shareId },
+ json: input
+ }),
+ shareResponseSchema,
+ options.onDiagnostic
+ )
+ return response.share
+ },
+ async rotateDocumentShare(documentId: string, shareId: string) {
+ return parseResponse(
+ client.documents[':documentId'].shares[':shareId'].rotate.$post({
+ param: { documentId, shareId }
+ }),
+ shareCapabilityResponseSchema,
+ options.onDiagnostic
+ )
+ },
+ async revokeDocumentShare(documentId: string, shareId: string): Promise<void> {
+ await responseBody(
+ await client.documents[':documentId'].shares[':shareId'].$delete({
+ param: { documentId, shareId }
+ }),
+ options.onDiagnostic
+ )
+ },
+ async listDocumentGrants(documentId: string): Promise<DocumentGrant[]> {
+ const response = await parseResponse(
+ client.documents[':documentId'].grants.$get({ param: { documentId } }),
+ grantsResponseSchema,
+ options.onDiagnostic
+ )
+ return response.grants
+ },
+ async putDocumentGrant(
+ documentId: string,
+ userId: string,
+ input: PutDocumentGrantInput
+ ): Promise<DocumentGrant> {
+ const response = await parseResponse(
+ client.documents[':documentId'].grants[':userId'].$put({
+ param: { documentId, userId },
+ json: input
+ }),
+ grantResponseSchema,
+ options.onDiagnostic
+ )
+ return response.grant
+ },
+ async revokeDocumentGrant(documentId: string, userId: string): Promise<void> {
+ await responseBody(
+ await client.documents[':documentId'].grants[':userId'].$delete({
+ param: { documentId, userId }
+ }),
+ options.onDiagnostic
+ )
+ },
+ async listDocumentInvitations(documentId: string): Promise<DocumentInvitation[]> {
+ const response = await parseResponse(
+ client.documents[':documentId'].invitations.$get({ param: { documentId } }),
+ invitationsResponseSchema,
+ options.onDiagnostic
+ )
+ return response.invitations
+ },
+ async createDocumentInvitation(documentId: string, input: CreateDocumentInvitationInput) {
+ return parseResponse(
+ client.documents[':documentId'].invitations.$post({
+ param: { documentId },
+ json: input
+ }),
+ invitationCapabilityResponseSchema,
+ options.onDiagnostic
+ )
+ },
+ async createInvitationContinuation(
+ input: CreateInvitationContinuationInput
+ ): Promise<InvitationContinuation> {
+ return parseResponse(
+ publicClient.invitations.continuations.$post({ json: input }),
+ invitationContinuationSchema,
+ options.onDiagnostic
+ )
+ },
+ async consumeInvitationContinuation(id: string): Promise<CreateInvitationContinuationInput> {
+ return parseResponse(
+ publicClient.invitations.continuations[':continuationId'].consume.$post({
+ param: { continuationId: id }
+ }),
+ createInvitationContinuationSchema,
+ options.onDiagnostic
+ )
+ },
+ async previewInvitation(
+ invitationId: string,
+ input: AcceptDocumentInvitationInput
+ ): Promise<InvitationPreview> {
+ const response = await parseResponse(
+ publicClient.invitations[':invitationId'].preview.$post({
+ param: { invitationId },
+ json: input
+ }),
+ invitationPreviewResponseSchema,
+ options.onDiagnostic
+ )
+ return response.invitation
+ },
+ /** Accepts a document or workspace invitation, and says which it was. */
+ async acceptInvitation(
+ invitationId: string,
+ input: AcceptDocumentInvitationInput
+ ): Promise<AcceptedInvitation> {
+ const response = await parseResponse(
+ client.invitations[':invitationId'].accept.$post({
+ param: { invitationId },
+ json: input
+ }),
+ acceptedResponseSchema,
+ options.onDiagnostic
+ )
+ return response.accepted
+ },
+ async revokeDocumentInvitation(documentId: string, invitationId: string): Promise<void> {
+ await responseBody(
+ await client.documents[':documentId'].invitations[':invitationId'].$delete({
+ param: { documentId, invitationId }
+ }),
+ options.onDiagnostic
+ )
+ },
+ async resolveDocumentShare(shareId: string, input: ResolveDocumentShareInput) {
+ const response = await parseResponse(
+ publicClient.shares[':shareId'].resolve.$post({
+ param: { shareId },
+ json: input
+ }),
+ resolvedShareResponseSchema,
+ options.onDiagnostic
+ )
+ return response.resolution
+ },
+ async getSharedDocument(shareId: string, input: ResolveDocumentShareInput) {
+ return parseResponse(
+ publicClient.shares[':shareId'].document.$post({
+ param: { shareId },
+ json: input
+ }),
+ sharedDocumentResponseSchema,
+ options.onDiagnostic
+ )
+ },
+ async getSharedCollaborationTicket(
+ shareId: string,
+ input: ResolveDocumentShareInput
+ ): Promise<CollaborationTicket> {
+ const response = await parseResponse(
+ publicClient.shares[':shareId']['collaboration-ticket'].$post({
+ param: { shareId },
+ json: input
+ }),
+ collaborationTicketResponseSchema,
+ options.onDiagnostic
+ )
+ return response.ticket
+ },
+ async getCollaborationTicket(documentId: string): Promise<CollaborationTicket> {
+ const response = await parseResponse(
+ client.documents[':documentId']['collaboration-ticket'].$post({
+ param: { documentId }
+ }),
+ collaborationTicketResponseSchema,
+ options.onDiagnostic
+ )
+ return response.ticket
+ },
+ async createUpload(documentId: string, input: CreateUploadInput): Promise<CloudUpload> {
+ return parseResponse(
+ client.documents[':documentId'].uploads.$post({
+ param: { documentId },
+ json: input
+ }),
+ uploadResponseSchema,
+ options.onDiagnostic
+ )
+ },
+ async commitUpload(uploadId: string, input: CommitUploadInput): Promise<DocumentSummary> {
+ const response = await parseResponse(
+ client.uploads[':uploadId'].commit.$post({
+ param: { uploadId },
+ json: input
+ }),
+ documentResponseSchema,
+ options.onDiagnostic
+ )
+ return response.document
+ }
+ }
+}
+
+export type CloudAPIClient = ReturnType<typeof createCloudAPIClient>
diff --git a/packages/cloud/src/client/auth-failure.ts b/packages/cloud/src/client/auth-failure.ts
new file mode 100644
index 000000000..e54c6d63c
--- /dev/null
+++ b/packages/cloud/src/client/auth-failure.ts
@@ -0,0 +1,54 @@
+/** Why a sign-in step did not go through, in terms a page or dialog can explain. */
+export type CloudAuthFailure =
+ | 'invalid-credentials'
+ | 'email-not-verified'
+ | 'password-too-short'
+ | 'password-too-long'
+ | 'invalid-link'
+ | 'invalid-code'
+ | 'passkey-cancelled'
+ | 'passkey-exists'
+ | 'passkey-unavailable'
+ | 'session-not-fresh'
+ | 'rate-limited'
+ | 'unavailable'
+
+export type CloudAuthResult<T = undefined> =
+ | { ok: true; value: T }
+ | { ok: false; failure: CloudAuthFailure }
+
+type BetterAuthError = { code?: string; status?: number } | null | undefined
+
+/** The failure a Better Auth error stands for; anything unknown can only be retried later. */
+export function cloudAuthFailure(error: BetterAuthError): { ok: false; failure: CloudAuthFailure } {
+ if (error?.status === 429) return { ok: false, failure: 'rate-limited' }
+ switch (error?.code ?? '') {
+ case 'INVALID_EMAIL_OR_PASSWORD':
+ return { ok: false, failure: 'invalid-credentials' }
+ case 'EMAIL_NOT_VERIFIED':
+ return { ok: false, failure: 'email-not-verified' }
+ case 'PASSWORD_TOO_SHORT':
+ return { ok: false, failure: 'password-too-short' }
+ case 'PASSWORD_TOO_LONG':
+ return { ok: false, failure: 'password-too-long' }
+ case 'INVALID_TOKEN':
+ return { ok: false, failure: 'invalid-link' }
+ case 'SESSION_NOT_FRESH':
+ return { ok: false, failure: 'session-not-fresh' }
+ case 'AUTH_CANCELLED':
+ case 'ERROR_CEREMONY_ABORTED':
+ return { ok: false, failure: 'passkey-cancelled' }
+ case 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED':
+ return { ok: false, failure: 'passkey-exists' }
+ case 'INVALID_CODE':
+ case 'INVALID_TWO_FACTOR_CODE':
+ case 'INVALID_BACKUP_CODE':
+ return { ok: false, failure: 'invalid-code' }
+ default:
+ // The browser's own WebAuthn refusals, such as an address it won't make passkeys for.
+ return {
+ ok: false,
+ failure: error?.code?.startsWith('ERROR_') ? 'passkey-unavailable' : 'unavailable'
+ }
+ }
+}
diff --git a/packages/cloud/src/client/auth-navigation.ts b/packages/cloud/src/client/auth-navigation.ts
new file mode 100644
index 000000000..0b386eb43
--- /dev/null
+++ b/packages/cloud/src/client/auth-navigation.ts
@@ -0,0 +1,27 @@
+import type { CloudDiscovery } from '#cloud/contract'
+
+/** The instance owns authentication; only its configured editor may receive the return. */
+export function cloudEditorReturnURL(discovery: CloudDiscovery, value: string): string {
+ if (!discovery.appURL) throw new Error('This instance does not advertise a public editor URL')
+ const editor = new URL(discovery.appURL)
+ const destination = new URL(value)
+ if (
+ !['https:', 'http:'].includes(editor.protocol) ||
+ destination.origin !== editor.origin ||
+ destination.username ||
+ destination.password
+ ) {
+ throw new Error('Authentication return URL must belong to this instance editor')
+ }
+ destination.hash = ''
+ return destination.href
+}
+
+export function cloudSignInURL(discovery: CloudDiscovery, returnURL: string): string {
+ const destination = cloudEditorReturnURL(discovery, returnURL)
+ const continuation = new URL('/auth/return', discovery.authURL)
+ continuation.searchParams.set('editor', destination)
+ const signIn = new URL('/auth/sign-in', discovery.authURL)
+ signIn.searchParams.set('redirect', `${continuation.pathname}${continuation.search}`)
+ return signIn.href
+}
diff --git a/packages/cloud/src/client/auth.ts b/packages/cloud/src/client/auth.ts
new file mode 100644
index 000000000..45abf3f22
--- /dev/null
+++ b/packages/cloud/src/client/auth.ts
@@ -0,0 +1,189 @@
+import type { CloudDiscovery } from '#cloud/contract'
+import { passkeyClient } from '@better-auth/passkey/client'
+import { createAuthClient } from 'better-auth/client'
+import { deviceAuthorizationClient, twoFactorClient } from 'better-auth/client/plugins'
+
+import { cloudAuthFailure, type CloudAuthResult } from './auth-failure'
+import type { CloudFetch } from './discovery'
+
+export type CloudSocialProvider = CloudDiscovery['authentication']['socialProviders'][number]
+
+function returnURL(): string {
+ const url = new URL(globalThis.location.href)
+ url.hash = ''
+ return url.href
+}
+
+type DeviceActionResult = Promise<{
+ data?: { success: boolean }
+ error?: { error_description: string }
+}>
+
+export type CloudAuthClient = Pick<
+ ReturnType<typeof createAuthClient>,
+ | 'getSession'
+ | 'signIn'
+ | 'signOut'
+ | 'signUp'
+ | 'sendVerificationEmail'
+ | 'requestPasswordReset'
+ | 'resetPassword'
+> & {
+ signIn: ReturnType<typeof createAuthClient>['signIn'] & {
+ passkey(): Promise<{
+ data: unknown
+ error: { message?: string; code?: string; status: number } | null
+ }>
+ }
+ twoFactor: {
+ verifyTotp(input: { code: string; trustDevice?: boolean }): Promise<{
+ data: unknown
+ error: { message?: string; code?: string; status: number } | null
+ }>
+ verifyBackupCode(input: { code: string; trustDevice?: boolean }): Promise<{
+ data: unknown
+ error: { message?: string; code?: string; status: number } | null
+ }>
+ }
+ passkey: {
+ addPasskey(input?: { name?: string }): Promise<{
+ data: unknown
+ error: { message?: string; code?: string; status: number } | null
+ }>
+ }
+ device: {
+ (input: { query: { user_code: string } }): Promise<{
+ data?: { user_code: string; status: string }
+ error?: { error_description: string }
+ }>
+ approve(input: { userCode: string }): DeviceActionResult
+ deny(input: { userCode: string }): DeviceActionResult
+ }
+}
+
+export type CloudAuthClientOptions = {
+ accessToken?: string
+ captchaResponse?: string
+ fetch?: CloudFetch
+}
+
+function authHeaders(options: CloudAuthClientOptions): HeadersInit | undefined {
+ const headers: Record<string, string> = {}
+ if (options.accessToken) headers.Authorization = `Bearer ${options.accessToken}`
+ if (options.captchaResponse) headers['x-captcha-response'] = options.captchaResponse
+ return Object.keys(headers).length > 0 ? headers : undefined
+}
+
+export function createCloudAuthClient(
+ discovery: CloudDiscovery,
+ options: CloudAuthClientOptions = {}
+): CloudAuthClient {
+ return createAuthClient({
+ baseURL: discovery.authURL,
+ plugins: [
+ deviceAuthorizationClient(),
+ twoFactorClient({ twoFactorPage: '/auth/two-factor' }),
+ passkeyClient()
+ ],
+ fetchOptions: {
+ credentials: 'include',
+ customFetchImpl: options.fetch,
+ headers: authHeaders(options)
+ }
+ }) as CloudAuthClient
+}
+
+export type CloudSignInOptions = {
+ callbackURL?: string
+ fetch?: CloudFetch
+ navigate?: (url: string) => void
+}
+
+export async function signInToCloud(
+ discovery: CloudDiscovery,
+ provider: CloudSocialProvider,
+ options: CloudSignInOptions = {}
+): Promise<void> {
+ const callbackURL = options.callbackURL ?? returnURL()
+ if (!discovery.authentication.socialProviders.includes(provider)) {
+ throw new Error(`Cloud sign-in provider is unavailable: ${provider}`)
+ }
+ const result = await createCloudAuthClient(discovery, { fetch: options.fetch }).signIn.social({
+ provider,
+ callbackURL,
+ errorCallbackURL: callbackURL,
+ disableRedirect: true
+ })
+ if (result.error) throw new Error(result.error.message ?? 'Cloud sign-in failed')
+ if (typeof result.data.url !== 'string') {
+ throw new TypeError('Cloud sign-in response did not include a URL')
+ }
+ const navigate = options.navigate ?? ((url: string) => globalThis.location.assign(url))
+ navigate(result.data.url)
+}
+
+export async function signOutFromCloud(
+ discovery: CloudDiscovery,
+ options: Pick<CloudAuthClientOptions, 'fetch' | 'accessToken'> = {}
+): Promise<void> {
+ const result = await createCloudAuthClient(discovery, options).signOut()
+ if (result.error) throw new Error(result.error.message ?? 'Cloud sign-out failed')
+}
+
+/** An email sign-in that went through: the session's bearer token, or a second step to take. */
+export type CloudEmailSignIn = { status: 'signed-in'; token: string } | { status: 'two-step' }
+
+type CloudEmailAuthOptions = Pick<CloudAuthClientOptions, 'fetch' | 'captchaResponse'>
+
+/**
+ * Signs in with an email and password without leaving the app. The token goes on every later
+ * request, so no cookie has to cross from the server to the editor.
+ */
+export async function signInToCloudWithEmail(
+ discovery: CloudDiscovery,
+ input: { email: string; password: string },
+ options: CloudEmailAuthOptions = {}
+): Promise<CloudAuthResult<CloudEmailSignIn>> {
+ const result = await createCloudAuthClient(discovery, options)
+ .signIn.email({ ...input, rememberMe: true })
+ .catch(() => null)
+ if (!result) return cloudAuthFailure(null)
+ if (result.error) return cloudAuthFailure(result.error)
+ if ('twoFactorRedirect' in result.data && result.data.twoFactorRedirect === true) {
+ return { ok: true, value: { status: 'two-step' } }
+ }
+ if (!('token' in result.data) || typeof result.data.token !== 'string') {
+ return cloudAuthFailure(null)
+ }
+ return { ok: true, value: { status: 'signed-in', token: result.data.token } }
+}
+
+/** Creates an account; the server emails a link that opens `verifiedURL` once it is confirmed. */
+export async function signUpToCloudWithEmail(
+ discovery: CloudDiscovery,
+ input: { name: string; email: string; password: string; verifiedURL: string },
+ options: CloudEmailAuthOptions = {}
+): Promise<CloudAuthResult> {
+ const result = await createCloudAuthClient(discovery, options)
+ .signUp.email({
+ name: input.name,
+ email: input.email,
+ password: input.password,
+ callbackURL: input.verifiedURL
+ })
+ .catch(() => null)
+ if (!result) return cloudAuthFailure(null)
+ return result.error ? cloudAuthFailure(result.error) : { ok: true, value: undefined }
+}
+
+export async function resendCloudVerification(
+ discovery: CloudDiscovery,
+ input: { email: string; verifiedURL: string },
+ options: CloudEmailAuthOptions = {}
+): Promise<CloudAuthResult> {
+ const result = await createCloudAuthClient(discovery, options)
+ .sendVerificationEmail({ email: input.email, callbackURL: input.verifiedURL })
+ .catch(() => null)
+ if (!result) return cloudAuthFailure(null)
+ return result.error ? cloudAuthFailure(result.error) : { ok: true, value: undefined }
+}
diff --git a/packages/cloud/src/client/device-authorization.ts b/packages/cloud/src/client/device-authorization.ts
new file mode 100644
index 000000000..9f02d14d4
--- /dev/null
+++ b/packages/cloud/src/client/device-authorization.ts
@@ -0,0 +1,133 @@
+import type { CloudDiscovery } from '#cloud/contract'
+import * as v from 'valibot'
+
+import type { CloudFetch } from './discovery'
+
+const deviceCodeSchema = v.object({
+ device_code: v.string(),
+ user_code: v.string(),
+ verification_uri: v.pipe(v.string(), v.url()),
+ verification_uri_complete: v.pipe(v.string(), v.url()),
+ expires_in: v.pipe(v.number(), v.integer(), v.minValue(1)),
+ interval: v.pipe(v.number(), v.integer(), v.minValue(1))
+})
+const deviceTokenSchema = v.object({
+ access_token: v.string(),
+ token_type: v.literal('Bearer'),
+ expires_in: v.pipe(v.number(), v.integer(), v.minValue(1)),
+ scope: v.string()
+})
+const deviceErrorSchema = v.object({ error: v.string(), error_description: v.optional(v.string()) })
+/** RFC 8628: each `slow_down` adds five seconds to the polling interval. */
+const SLOW_DOWN_MS = 5000
+
+export type CloudDeviceErrorCode = 'denied' | 'expired' | 'unavailable'
+
+export class CloudDeviceAuthorizationError extends Error {
+ override readonly name = 'CloudDeviceAuthorizationError'
+ constructor(readonly code: CloudDeviceErrorCode) {
+ super(`Cloud device authorization ${code}`)
+ }
+}
+
+export type CloudDeviceAuthorization = v.InferOutput<typeof deviceCodeSchema>
+export type CloudDeviceToken = v.InferOutput<typeof deviceTokenSchema>
+
+export type CloudDevicePollingOptions = {
+ signal?: AbortSignal
+ fetch?: CloudFetch
+ now?: () => number
+ sleep?: (milliseconds: number, signal?: AbortSignal) => Promise<void>
+}
+
+function abortableSleep(milliseconds: number, signal?: AbortSignal): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ const timeout = setTimeout(resolve, milliseconds)
+ signal?.addEventListener(
+ 'abort',
+ () => {
+ clearTimeout(timeout)
+ reject(
+ signal.reason instanceof Error
+ ? signal.reason
+ : new DOMException('Authorization cancelled', 'AbortError')
+ )
+ },
+ { once: true }
+ )
+ })
+}
+
+function authEndpoint(discovery: CloudDiscovery, path: string): string {
+ return new URL(path, `${discovery.authURL.replace(/\/$/, '')}/`).href
+}
+
+export type CloudDeviceAuthorizationOptions = {
+ fetch?: CloudFetch
+}
+
+export async function requestCloudDeviceAuthorization(
+ discovery: CloudDiscovery,
+ connectionId: string,
+ options: CloudDeviceAuthorizationOptions = {}
+): Promise<CloudDeviceAuthorization> {
+ const request = options.fetch ?? globalThis.fetch
+ const response = await request(authEndpoint(discovery, 'device/code'), {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ client_id: `openpencil-desktop:${connectionId}`,
+ scope: 'openid profile'
+ })
+ })
+ if (!response.ok) throw new CloudDeviceAuthorizationError('unavailable')
+ return v.parse(deviceCodeSchema, await response.json())
+}
+
+export async function pollCloudDeviceToken(
+ discovery: CloudDiscovery,
+ connectionId: string,
+ authorization: CloudDeviceAuthorization,
+ options: CloudDevicePollingOptions = {}
+): Promise<CloudDeviceToken> {
+ const request = options.fetch ?? globalThis.fetch
+ const now = options.now ?? Date.now
+ const sleep = options.sleep ?? abortableSleep
+ const expiresAt = now() + authorization.expires_in * 1000
+ let interval = authorization.interval * 1000
+ while (now() < expiresAt) {
+ options.signal?.throwIfAborted()
+ await sleep(interval, options.signal)
+ if (now() >= expiresAt) break
+ const response = await request(authEndpoint(discovery, 'device/token'), {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
+ device_code: authorization.device_code,
+ client_id: `openpencil-desktop:${connectionId}`
+ }),
+ signal: options.signal
+ })
+ const body = await response.text()
+ if (response.ok) return v.parse(v.pipe(v.string(), v.parseJson(), deviceTokenSchema), body)
+ // A rate limit asks for the same as `slow_down`, whatever its body says.
+ if (response.status === 429) {
+ interval += SLOW_DOWN_MS
+ continue
+ }
+ const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), deviceErrorSchema), body)
+ if (!parsed.success) throw new CloudDeviceAuthorizationError('unavailable')
+ const error = parsed.output
+ if (error.error === 'authorization_pending') continue
+ if (error.error === 'slow_down') {
+ interval += SLOW_DOWN_MS
+ continue
+ }
+ let code: CloudDeviceErrorCode = 'unavailable'
+ if (error.error === 'access_denied') code = 'denied'
+ else if (error.error === 'expired_token') code = 'expired'
+ throw new CloudDeviceAuthorizationError(code)
+ }
+ throw new CloudDeviceAuthorizationError('expired')
+}
diff --git a/packages/cloud/src/client/discovery.ts b/packages/cloud/src/client/discovery.ts
new file mode 100644
index 000000000..49c98513e
--- /dev/null
+++ b/packages/cloud/src/client/discovery.ts
@@ -0,0 +1,63 @@
+import { CLOUD_DISCOVERY_PATH, parseCloudDiscovery, type CloudDiscovery } from '#cloud/contract'
+
+const DISCOVERY_TIMEOUT_MS = 10_000
+
+export type CloudFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
+
+export type DiscoverCloudOptions = {
+ fetch?: CloudFetch
+ signal?: AbortSignal
+}
+
+export class CloudClientError extends Error {
+ constructor(
+ message: string,
+ override readonly cause?: unknown
+ ) {
+ super(message)
+ this.name = 'CloudClientError'
+ }
+}
+
+function discoveryURL(serverURL: string): URL {
+ let url: URL
+ try {
+ url = new URL(serverURL)
+ } catch (error) {
+ throw new CloudClientError('OpenPencil server URL is invalid', error)
+ }
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
+ throw new CloudClientError('OpenPencil server URL must use HTTP or HTTPS')
+ }
+ url.pathname = CLOUD_DISCOVERY_PATH
+ url.search = ''
+ url.hash = ''
+ return url
+}
+
+export async function discoverCloud(
+ serverURL: string,
+ options: DiscoverCloudOptions = {}
+): Promise<CloudDiscovery> {
+ const fetchImplementation = options.fetch ?? globalThis.fetch
+ const timeoutSignal = AbortSignal.timeout(DISCOVERY_TIMEOUT_MS)
+ const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal
+
+ try {
+ const response = await fetchImplementation(discoveryURL(serverURL), {
+ headers: { Accept: 'application/json' },
+ redirect: 'follow',
+ signal
+ })
+ if (!response.ok) {
+ throw new CloudClientError(`OpenPencil server discovery failed with HTTP ${response.status}`)
+ }
+ return parseCloudDiscovery(await response.json())
+ } catch (error) {
+ if (error instanceof CloudClientError) throw error
+ if (signal.aborted) {
+ throw new CloudClientError('OpenPencil server discovery was cancelled or timed out', error)
+ }
+ throw new CloudClientError('OpenPencil server discovery failed', error)
+ }
+}
diff --git a/packages/cloud/src/client/index.ts b/packages/cloud/src/client/index.ts
new file mode 100644
index 000000000..74d25542a
--- /dev/null
+++ b/packages/cloud/src/client/index.ts
@@ -0,0 +1,38 @@
+export { cloudEditorReturnURL, cloudSignInURL } from './auth-navigation'
+export { cloudRedirectPath, cloudShareURL } from './links'
+export {
+ CloudAPIError,
+ createCloudAPIClient,
+ type CloudAPIClient,
+ type CloudRequestOptions,
+ type CloudUpload
+} from './api'
+export { cloudAuthFailure, type CloudAuthFailure, type CloudAuthResult } from './auth-failure'
+export {
+ createCloudAuthClient,
+ resendCloudVerification,
+ signInToCloudWithEmail,
+ signUpToCloudWithEmail,
+ type CloudEmailSignIn,
+ signInToCloud,
+ signOutFromCloud,
+ type CloudAuthClient,
+ type CloudAuthClientOptions,
+ type CloudSignInOptions,
+ type CloudSocialProvider
+} from './auth'
+export {
+ CloudDeviceAuthorizationError,
+ type CloudDeviceErrorCode,
+ pollCloudDeviceToken,
+ requestCloudDeviceAuthorization,
+ type CloudDeviceAuthorization,
+ type CloudDeviceAuthorizationOptions,
+ type CloudDeviceToken
+} from './device-authorization'
+export {
+ CloudClientError,
+ discoverCloud,
+ type CloudFetch,
+ type DiscoverCloudOptions
+} from './discovery'
diff --git a/packages/cloud/src/client/links.ts b/packages/cloud/src/client/links.ts
new file mode 100644
index 000000000..b1a0c5f52
--- /dev/null
+++ b/packages/cloud/src/client/links.ts
@@ -0,0 +1,29 @@
+import type { CloudDiscovery } from '#cloud/contract'
+
+/** Canonical web links come from the owning instance, never the caller's window. */
+export function cloudShareURL(
+ discovery: CloudDiscovery,
+ serverURL: string,
+ shareId: string,
+ secret: string
+): string {
+ if (!discovery.appURL) throw new Error('This instance does not advertise a public editor URL')
+ const url = new URL(discovery.appURL)
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
+ throw new Error('The public editor URL must use HTTP or HTTPS')
+ }
+ url.pathname = `/cloud/share/${encodeURIComponent(shareId)}`
+ url.search = ''
+ url.searchParams.set('server', serverURL)
+ url.hash = secret
+ return url.href
+}
+
+/** Accept only same-origin application paths for post-authentication navigation. */
+export function cloudRedirectPath(value: unknown, fallback = '/app'): string {
+ if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//')) return fallback
+ const origin = 'https://redirect.invalid'
+ const url = new URL(value, origin)
+ if (url.origin !== origin) return fallback
+ return `${url.pathname}${url.search}${url.hash}`
+}
diff --git a/packages/cloud/src/client/response.ts b/packages/cloud/src/client/response.ts
new file mode 100644
index 000000000..d1a3ead13
--- /dev/null
+++ b/packages/cloud/src/client/response.ts
@@ -0,0 +1,51 @@
+import * as v from 'valibot'
+
+const cloudErrorResponseSchema = v.object({
+ error: v.object({ code: v.string() })
+})
+
+/** The part of a fetch or Hono client response the client reads. */
+export type CloudResponse = Pick<Response, 'ok' | 'status' | 'json'>
+
+export type CloudClientDiagnostic = (message: string, error: unknown) => void
+
+export class CloudAPIError extends Error {
+ override readonly name = 'CloudAPIError'
+
+ constructor(
+ message: string,
+ readonly status: number,
+ readonly code?: string
+ ) {
+ super(message)
+ }
+}
+
+export async function responseBody(
+ response: CloudResponse,
+ onDiagnostic?: CloudClientDiagnostic
+): Promise<unknown> {
+ if (response.ok) return response.status === 204 ? null : response.json()
+ let code: string | undefined
+ try {
+ const body = v.safeParse(cloudErrorResponseSchema, await response.json())
+ if (body.success) code = body.output.error.code
+ } catch (error) {
+ onDiagnostic?.('Cloud API error response was not JSON', error)
+ }
+ throw new CloudAPIError(
+ `OpenPencil Cloud request failed with HTTP ${response.status}`,
+ response.status,
+ code
+ )
+}
+
+export async function parseResponse<
+ TSchema extends v.BaseSchema<unknown, unknown, v.BaseIssue<unknown>>
+>(
+ request: Promise<CloudResponse>,
+ schema: TSchema,
+ onDiagnostic?: CloudClientDiagnostic
+): Promise<v.InferOutput<TSchema>> {
+ return v.parse(schema, await responseBody(await request, onDiagnostic))
+}
diff --git a/packages/cloud/src/client/workspaces.ts b/packages/cloud/src/client/workspaces.ts
new file mode 100644
index 000000000..c4342c41a
--- /dev/null
+++ b/packages/cloud/src/client/workspaces.ts
@@ -0,0 +1,129 @@
+import {
+ createdWorkspaceInvitationSchema,
+ workspaceEntitlementsSchema,
+ workspaceListSchema,
+ workspaceMembersSchema,
+ workspaceSummarySchema,
+ workspaceUsageSchema,
+ type CreatedWorkspaceInvitation,
+ type CreateWorkspaceInvitationInput,
+ type WorkspaceEntitlements,
+ type WorkspaceList,
+ type WorkspaceMembers,
+ type WorkspaceRole,
+ type WorkspaceSummary,
+ type WorkspaceUsage
+} from '#cloud/contract'
+import type { CloudAPI } from '#cloud/server/api'
+import type { hc } from 'hono/client'
+import * as v from 'valibot'
+
+import { parseResponse, responseBody, type CloudClientDiagnostic } from './response'
+
+const workspaceResponseSchema = v.object({ workspace: workspaceSummarySchema })
+const usageResponseSchema = v.object({ usage: workspaceUsageSchema })
+const entitlementResponseSchema = v.object({ entitlements: workspaceEntitlementsSchema })
+
+/** Workspaces, their members, invitations, entitlements, and storage use. */
+export function createWorkspaceRequests(
+ client: ReturnType<typeof hc<CloudAPI>>,
+ onDiagnostic?: CloudClientDiagnostic
+) {
+ return {
+ async listWorkspaces(): Promise<WorkspaceList> {
+ return parseResponse(client.workspaces.$get(), workspaceListSchema, onDiagnostic)
+ },
+ async createWorkspace(name: string): Promise<WorkspaceSummary> {
+ const response = await parseResponse(
+ client.workspaces.$post({ json: { name } }),
+ workspaceResponseSchema,
+ onDiagnostic
+ )
+ return response.workspace
+ },
+ async renameWorkspace(workspaceId: string, name: string): Promise<WorkspaceSummary> {
+ const response = await parseResponse(
+ client.workspaces[':workspaceId'].$patch({ param: { workspaceId }, json: { name } }),
+ workspaceResponseSchema,
+ onDiagnostic
+ )
+ return response.workspace
+ },
+ /** Deletes an empty workspace; the server refuses one that still holds documents. */
+ async deleteWorkspace(workspaceId: string): Promise<void> {
+ await responseBody(
+ await client.workspaces[':workspaceId'].$delete({ param: { workspaceId } }),
+ onDiagnostic
+ )
+ },
+ /** The workspace's members, and for administrators its pending invitations. */
+ async listWorkspaceMembers(workspaceId: string): Promise<WorkspaceMembers> {
+ return parseResponse(
+ client.workspaces[':workspaceId'].members.$get({ param: { workspaceId } }),
+ workspaceMembersSchema,
+ onDiagnostic
+ )
+ },
+ async inviteToWorkspace(
+ workspaceId: string,
+ input: CreateWorkspaceInvitationInput
+ ): Promise<CreatedWorkspaceInvitation> {
+ return parseResponse(
+ client.workspaces[':workspaceId'].invitations.$post({
+ param: { workspaceId },
+ json: input
+ }),
+ createdWorkspaceInvitationSchema,
+ onDiagnostic
+ )
+ },
+ async revokeWorkspaceInvitation(workspaceId: string, invitationId: string): Promise<void> {
+ await responseBody(
+ await client.workspaces[':workspaceId'].invitations[':invitationId'].$delete({
+ param: { workspaceId, invitationId }
+ }),
+ onDiagnostic
+ )
+ },
+ async updateWorkspaceMember(
+ workspaceId: string,
+ userId: string,
+ role: WorkspaceRole
+ ): Promise<void> {
+ await responseBody(
+ await client.workspaces[':workspaceId'].members[':userId'].$patch({
+ param: { workspaceId, userId },
+ json: { role }
+ }),
+ onDiagnostic
+ )
+ },
+ /** Removes someone from the workspace; with the person's own id, leaves it. */
+ async removeWorkspaceMember(workspaceId: string, userId: string): Promise<void> {
+ await responseBody(
+ await client.workspaces[':workspaceId'].members[':userId'].$delete({
+ param: { workspaceId, userId }
+ }),
+ onDiagnostic
+ )
+ },
+ async getWorkspaceEntitlements(workspaceId: string): Promise<WorkspaceEntitlements> {
+ const response = await parseResponse(
+ client.workspaces[':workspaceId'].entitlements.$get({ param: { workspaceId } }),
+ entitlementResponseSchema,
+ onDiagnostic
+ )
+ return response.entitlements
+ },
+ async getUsage(workspaceId: string): Promise<WorkspaceUsage> {
+ const response = await parseResponse(
+ client.workspaces[':workspaceId'].usage.$get({
+ param: { workspaceId }
+ }),
+ usageResponseSchema,
+ onDiagnostic
+ )
+ return response.usage
+ }
+ }
+}
diff --git a/packages/cloud/src/contract/account.ts b/packages/cloud/src/contract/account.ts
new file mode 100644
index 000000000..fb173bd82
--- /dev/null
+++ b/packages/cloud/src/contract/account.ts
@@ -0,0 +1,103 @@
+import * as v from 'valibot'
+
+export const cloudAccountStateSchema = v.picklist(['active', 'pending', 'rejected', 'revoked'])
+export const cloudIdentitySchema = v.object({
+ userId: v.string(),
+ email: v.pipe(v.string(), v.email()),
+ name: v.string(),
+ deploymentRole: v.optional(v.picklist(['user', 'admin']))
+})
+
+export const cloudAccountStatusResponseSchema = v.object({
+ user: cloudIdentitySchema,
+ state: cloudAccountStateSchema
+})
+
+export const cloudAuthenticationProviderSchema = v.picklist(['credential', 'google', 'apple'])
+export const cloudAuthenticationMethodSchema = v.object({
+ id: v.string(),
+ provider: cloudAuthenticationProviderSchema,
+ createdAt: v.string(),
+ canUnlink: v.boolean()
+})
+export const cloudAuthenticationMethodsResponseSchema = v.object({
+ methods: v.array(cloudAuthenticationMethodSchema),
+ availableSocialProviders: v.array(v.picklist(['google', 'apple']))
+})
+export const cloudPasswordChangeSchema = v.object({
+ currentPassword: v.string(),
+ newPassword: v.string()
+})
+export const cloudSocialLinkSchema = v.object({
+ provider: v.picklist(['google', 'apple']),
+ callbackURL: v.pipe(v.string(), v.url())
+})
+export const cloudSocialLinkResponseSchema = v.object({ url: v.pipe(v.string(), v.url()) })
+export const cloudUnlinkAuthenticationMethodSchema = v.object({ methodId: v.string() })
+export const accountSecurityErrorCodeSchema = v.picklist([
+ 'current_password_invalid',
+ 'password_too_short',
+ 'password_too_long',
+ 'last_authentication_method',
+ 'session_not_fresh',
+ 'authentication_method_failed'
+])
+export const accountSecurityErrorResponseSchema = v.object({
+ error: v.object({ code: accountSecurityErrorCodeSchema })
+})
+
+export const cloudMFAStatusSchema = v.object({
+ required: v.boolean(),
+ enabled: v.boolean(),
+ totpEnabled: v.boolean(),
+ assured: v.boolean(),
+ totpAvailable: v.boolean(),
+ passkeysAvailable: v.boolean(),
+ recoveryCodesAvailable: v.boolean()
+})
+export const cloudMFAStatusResponseSchema = v.object({ mfa: cloudMFAStatusSchema })
+export const cloudMFAEnableSchema = v.object({ password: v.optional(v.string()) })
+export const cloudMFAEnableResponseSchema = v.object({
+ totpURI: v.string(),
+ backupCodes: v.array(v.string())
+})
+export const cloudMFAVerifySchema = v.object({ code: v.pipe(v.string(), v.trim(), v.minLength(1)) })
+export const cloudMFAVerifyResponseSchema = v.object({ ok: v.literal(true) })
+export const cloudMFARecoveryCodesResponseSchema = v.object({ backupCodes: v.array(v.string()) })
+export const cloudPasskeySchema = v.object({
+ id: v.string(),
+ name: v.nullish(v.string()),
+ createdAt: v.string()
+})
+export const cloudPasskeysResponseSchema = v.object({ passkeys: v.array(cloudPasskeySchema) })
+export const cloudPasskeyDeleteSchema = v.object({ id: v.string() })
+
+export function parseCloudMFAEnable(input: unknown) {
+ return v.parse(cloudMFAEnableSchema, input)
+}
+export function parseCloudMFAVerify(input: unknown) {
+ return v.parse(cloudMFAVerifySchema, input)
+}
+export function parseCloudPasskeyDelete(input: unknown) {
+ return v.parse(cloudPasskeyDeleteSchema, input)
+}
+export function parseCloudPasswordChange(input: unknown) {
+ return v.parse(cloudPasswordChangeSchema, input)
+}
+export function parseCloudSocialLink(input: unknown) {
+ return v.parse(cloudSocialLinkSchema, input)
+}
+export function parseCloudUnlinkAuthenticationMethod(input: unknown) {
+ return v.parse(cloudUnlinkAuthenticationMethodSchema, input)
+}
+
+export const cloudAccountMutationResponseSchema = v.object({ ok: v.literal(true) })
+
+export type AccountSecurityErrorCode = v.InferOutput<typeof accountSecurityErrorCodeSchema>
+export type CloudAuthenticationProvider = v.InferOutput<typeof cloudAuthenticationProviderSchema>
+export type CloudAuthenticationMethod = v.InferOutput<typeof cloudAuthenticationMethodSchema>
+export type CloudAuthenticationMethods = v.InferOutput<
+ typeof cloudAuthenticationMethodsResponseSchema
+>
+
+export type CloudAccountStatus = v.InferOutput<typeof cloudAccountStatusResponseSchema>
diff --git a/packages/cloud/src/contract/admin/index.ts b/packages/cloud/src/contract/admin/index.ts
new file mode 100644
index 000000000..11d200674
--- /dev/null
+++ b/packages/cloud/src/contract/admin/index.ts
@@ -0,0 +1,105 @@
+import * as v from 'valibot'
+
+import { cloudIdentitySchema } from '../account'
+
+const timestampSchema = v.pipe(v.string(), v.isoTimestamp())
+const nullableTimestampSchema = v.nullable(timestampSchema)
+
+export const adminErrorCodeSchema = v.picklist([
+ 'bad_request',
+ 'unauthorized',
+ 'forbidden',
+ 'not_found',
+ 'rate_limited',
+ 'invalid_enrollment_transition',
+ 'last_admin_required',
+ 'self_admin_action_forbidden',
+ 'email_regeneration_unavailable',
+ 'mfa_required'
+])
+
+export const adminErrorResponseSchema = v.object({
+ error: v.object({ code: adminErrorCodeSchema })
+})
+
+export const enrollmentStatusSchema = v.picklist(['pending', 'approved', 'rejected', 'revoked'])
+export const enrollmentSchema = v.object({
+ id: v.string(),
+ email: v.pipe(v.string(), v.email()),
+ name: v.nullable(v.string()),
+ reason: v.nullable(v.string()),
+ status: enrollmentStatusSchema,
+ requestedAt: timestampSchema,
+ reviewedAt: nullableTimestampSchema,
+ reviewedBy: v.nullable(v.string()),
+ reviewNote: v.nullable(v.string()),
+ approvedUserId: v.nullable(v.string()),
+ requestRevision: v.pipe(v.number(), v.integer(), v.minValue(1))
+})
+
+export const enrollmentsResponseSchema = v.object({ enrollments: v.array(enrollmentSchema) })
+export const enrollmentReviewResponseSchema = v.object({ enrollment: enrollmentSchema })
+
+export const cloudAdminSessionResponseSchema = v.object({ user: cloudIdentitySchema })
+
+export const cloudAdminUserSchema = v.object({
+ id: v.string(),
+ name: v.string(),
+ email: v.pipe(v.string(), v.email()),
+ role: v.optional(v.string()),
+ banned: v.nullable(v.boolean()),
+ banReason: v.optional(v.nullable(v.string())),
+ createdAt: timestampSchema
+})
+export const cloudAdminUsersResponseSchema = v.object({
+ users: v.array(cloudAdminUserSchema),
+ total: v.pipe(v.number(), v.integer(), v.minValue(0))
+})
+
+export const adminMutationResponseSchema = v.object({ ok: v.literal(true) })
+
+export const transactionalEmailAdminSchema = v.object({
+ id: v.string(),
+ kind: v.string(),
+ recipientEmailNormalized: v.pipe(v.string(), v.email()),
+ status: v.string(),
+ attemptCount: v.pipe(v.number(), v.integer(), v.minValue(0)),
+ nextAttemptAt: timestampSchema,
+ transport: v.nullable(v.string()),
+ transportMessageId: v.nullable(v.string()),
+ lastErrorCode: v.nullable(v.string()),
+ createdAt: timestampSchema,
+ acceptedAt: nullableTimestampSchema,
+ regeneratable: v.boolean()
+})
+export const adminEmailResponseSchema = v.object({
+ messages: v.array(transactionalEmailAdminSchema)
+})
+
+export const adminAuditEventSchema = v.object({
+ id: v.string(),
+ actorUserId: v.string(),
+ action: v.string(),
+ subjectType: v.string(),
+ subjectId: v.string(),
+ metadata: v.unknown(),
+ createdAt: timestampSchema
+})
+export const adminAuditResponseSchema = v.object({ events: v.array(adminAuditEventSchema) })
+
+export const adminOperationsResponseSchema = v.object({
+ deployment: v.picklist(['official', 'self-hosted']),
+ enrollmentMode: v.picklist(['open', 'approval', 'closed']),
+ emailTransport: v.picklist(['none', 'smtp', 'cloudflare']),
+ pendingEnrollment: v.pipe(v.number(), v.integer(), v.minValue(0)),
+ pendingEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),
+ failedEmail: v.pipe(v.number(), v.integer(), v.minValue(0))
+})
+
+export type AdminErrorCode = v.InferOutput<typeof adminErrorCodeSchema>
+export type Enrollment = v.InferOutput<typeof enrollmentSchema>
+export type CloudAdminSessionResponse = v.InferOutput<typeof cloudAdminSessionResponseSchema>
+export type CloudAdminUser = v.InferOutput<typeof cloudAdminUserSchema>
+export type TransactionalEmailAdmin = v.InferOutput<typeof transactionalEmailAdminSchema>
+export type AdminAuditEvent = v.InferOutput<typeof adminAuditEventSchema>
+export type AdminOperations = v.InferOutput<typeof adminOperationsResponseSchema>
diff --git a/packages/cloud/src/contract/collaboration.ts b/packages/cloud/src/contract/collaboration.ts
new file mode 100644
index 000000000..9bff04121
--- /dev/null
+++ b/packages/cloud/src/contract/collaboration.ts
@@ -0,0 +1,33 @@
+import * as v from 'valibot'
+
+import { documentPermissionSchema } from './documents'
+
+export const collaborationPrincipalSchema = v.variant('kind', [
+ v.object({
+ kind: v.literal('user'),
+ userId: v.string(),
+ name: v.string(),
+ email: v.pipe(v.string(), v.email())
+ }),
+ v.object({
+ kind: v.literal('guest'),
+ guestId: v.string(),
+ name: v.string()
+ })
+])
+export type CollaborationPrincipal = v.InferOutput<typeof collaborationPrincipalSchema>
+
+export const collaborationTicketSchema = v.object({
+ token: v.string(),
+ provider: v.optional(v.picklist(['trystero', 'hocuspocus'])),
+ serverURL: v.optional(v.pipe(v.string(), v.url())),
+ documentId: v.pipe(v.string(), v.uuid()),
+ roomId: v.string(),
+ roomKey: v.pipe(v.string(), v.minLength(43), v.maxLength(128)),
+ principal: collaborationPrincipalSchema,
+ permission: documentPermissionSchema,
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
+ expiresAt: v.string(),
+ serverEnforcedWrites: v.boolean()
+})
+export type CollaborationTicket = v.InferOutput<typeof collaborationTicketSchema>
diff --git a/packages/cloud/src/contract/discovery.ts b/packages/cloud/src/contract/discovery.ts
new file mode 100644
index 000000000..171298f69
--- /dev/null
+++ b/packages/cloud/src/contract/discovery.ts
@@ -0,0 +1,69 @@
+import * as v from 'valibot'
+
+export const CLOUD_PROTOCOL_VERSION = '1' as const
+export const CLOUD_DISCOVERY_PATH = '/.well-known/openpencil' as const
+
+export const cloudDeploymentSchema = v.picklist(['official', 'self-hosted'])
+export type CloudDeployment = v.InferOutput<typeof cloudDeploymentSchema>
+
+export const cloudAuthenticationSchema = v.object({
+ emailPassword: v.optional(
+ v.object({
+ signIn: v.boolean(),
+ signUp: v.boolean(),
+ minimumPasswordLength: v.pipe(v.number(), v.integer(), v.minValue(8)),
+ captcha: v.optional(
+ v.object({
+ provider: v.literal('cloudflare-turnstile'),
+ siteKey: v.pipe(v.string(), v.trim(), v.minLength(1))
+ })
+ )
+ })
+ ),
+ socialProviders: v.array(v.picklist(['apple', 'google'])),
+ enterpriseSSO: v.boolean(),
+ enrollmentMode: v.optional(v.picklist(['open', 'approval', 'closed']), 'open'),
+ mfa: v.optional(
+ v.object({
+ deploymentAdminRequired: v.boolean(),
+ totp: v.boolean(),
+ passkeys: v.boolean(),
+ recoveryCodes: v.boolean()
+ })
+ )
+})
+export type CloudAuthentication = v.InferOutput<typeof cloudAuthenticationSchema>
+
+export const cloudCapabilitiesSchema = v.object({
+ documents: v.boolean(),
+ workspaces: v.boolean(),
+ collaboration: v.boolean()
+})
+export type CloudCapabilities = v.InferOutput<typeof cloudCapabilitiesSchema>
+
+/** A released editor version, `major.minor.patch`. */
+export const cloudEditorVersionSchema = v.pipe(v.string(), v.regex(/^\d+\.\d+\.\d+$/))
+
+/**
+ * Whether editors offer this server to everyone, and from which editor version on. Only the
+ * official server's listing is read: it turns the Cloud entry points on without an editor release,
+ * and an editor older than the minimum keeps them hidden.
+ */
+export const cloudListingSchema = v.object({ minimumEditorVersion: cloudEditorVersionSchema })
+export type CloudListing = v.InferOutput<typeof cloudListingSchema>
+
+export const cloudDiscoverySchema = v.object({
+ protocolVersion: v.literal(CLOUD_PROTOCOL_VERSION),
+ deployment: cloudDeploymentSchema,
+ apiURL: v.pipe(v.string(), v.url()),
+ authURL: v.pipe(v.string(), v.url()),
+ appURL: v.optional(v.pipe(v.string(), v.url())),
+ authentication: cloudAuthenticationSchema,
+ capabilities: cloudCapabilitiesSchema,
+ listing: v.optional(cloudListingSchema)
+})
+export type CloudDiscovery = v.InferOutput<typeof cloudDiscoverySchema>
+
+export function parseCloudDiscovery(input: unknown): CloudDiscovery {
+ return v.parse(cloudDiscoverySchema, input)
+}
diff --git a/packages/cloud/src/contract/documents.ts b/packages/cloud/src/contract/documents.ts
new file mode 100644
index 000000000..719619831
--- /dev/null
+++ b/packages/cloud/src/contract/documents.ts
@@ -0,0 +1,118 @@
+import * as v from 'valibot'
+
+export const CLOUD_PROTOCOL_MAX_UPLOAD_BYTES = 1024 * 1024 * 1024
+
+const checksumSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9+/]{43}=$/))
+
+export const documentPermissionSchema = v.picklist(['view', 'edit'])
+export type DocumentPermission = v.InferOutput<typeof documentPermissionSchema>
+
+export const documentAccessSourceSchema = v.picklist(['owner', 'workspace', 'direct-grant'])
+export type DocumentAccessSource = v.InferOutput<typeof documentAccessSourceSchema>
+
+export const documentAccessSchema = v.object({
+ permission: documentPermissionSchema,
+ canManageSharing: v.boolean(),
+ sources: v.array(documentAccessSourceSchema)
+})
+export type DocumentAccess = v.InferOutput<typeof documentAccessSchema>
+
+export const documentSummarySchema = v.object({
+ id: v.pipe(v.string(), v.uuid()),
+ workspaceId: v.pipe(v.string(), v.uuid()),
+ name: v.string(),
+ currentRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),
+ version: v.number(),
+ createdAt: v.string(),
+ updatedAt: v.string()
+})
+export type DocumentSummary = v.InferOutput<typeof documentSummarySchema>
+
+/** A document someone granted the person directly, in a workspace they are not a member of. */
+export const sharedDocumentSchema = v.object({
+ ...documentSummarySchema.entries,
+ workspaceName: v.string(),
+ permission: documentPermissionSchema,
+ sharedBy: v.nullable(v.object({ name: v.string() })),
+ sharedAt: v.string()
+})
+export type SharedDocument = v.InferOutput<typeof sharedDocumentSchema>
+
+export const documentDownloadSchema = v.object({
+ document: documentSummarySchema,
+ revisionId: v.pipe(v.string(), v.uuid()),
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
+ checksum: checksumSchema,
+ contentType: v.string(),
+ download: v.object({
+ url: v.pipe(v.string(), v.url()),
+ method: v.literal('GET'),
+ headers: v.record(v.string(), v.string()),
+ expiresAt: v.string()
+ })
+})
+export type DocumentDownload = v.InferOutput<typeof documentDownloadSchema>
+
+export const cloudActorSchema = v.object({
+ userId: v.string(),
+ email: v.pipe(v.string(), v.email()),
+ name: v.string()
+})
+export type CloudActorContract = v.InferOutput<typeof cloudActorSchema>
+
+export const cloudSessionSchema = v.object({ user: cloudActorSchema })
+export type CloudSession = v.InferOutput<typeof cloudSessionSchema>
+
+export const workspaceUsageSchema = v.object({
+ bytesUsed: v.pipe(v.number(), v.integer(), v.minValue(0)),
+ objectCount: v.pipe(v.number(), v.integer(), v.minValue(0)),
+ documentCount: v.pipe(v.number(), v.integer(), v.minValue(0))
+})
+export type WorkspaceUsage = v.InferOutput<typeof workspaceUsageSchema>
+
+export const createDocumentSchema = v.object({
+ id: v.optional(v.pipe(v.string(), v.uuid())),
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255))
+})
+export type CreateDocumentInput = v.InferOutput<typeof createDocumentSchema>
+
+export const createUploadSchema = v.object({
+ baseRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),
+ byteSize: v.pipe(
+ v.number(),
+ v.integer(),
+ v.minValue(1),
+ v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES)
+ ),
+ checksum: checksumSchema,
+ contentType: v.literal('application/octet-stream')
+})
+export type CreateUploadInput = v.InferOutput<typeof createUploadSchema>
+
+export const completedUploadPartSchema = v.object({
+ partNumber: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(10_000)),
+ etag: v.pipe(v.string(), v.minLength(1), v.maxLength(255))
+})
+
+export const commitUploadSchema = v.object({
+ checksum: checksumSchema,
+ multipart: v.optional(
+ v.object({
+ uploadId: v.pipe(v.string(), v.minLength(1)),
+ parts: v.pipe(v.array(completedUploadPartSchema), v.minLength(1), v.maxLength(10_000))
+ })
+ )
+})
+export type CommitUploadInput = v.InferOutput<typeof commitUploadSchema>
+
+export function parseCreateDocument(input: unknown): CreateDocumentInput {
+ return v.parse(createDocumentSchema, input)
+}
+
+export function parseCreateUpload(input: unknown): CreateUploadInput {
+ return v.parse(createUploadSchema, input)
+}
+
+export function parseCommitUpload(input: unknown): CommitUploadInput {
+ return v.parse(commitUploadSchema, input)
+}
diff --git a/packages/cloud/src/contract/entitlements.ts b/packages/cloud/src/contract/entitlements.ts
new file mode 100644
index 000000000..74d4bcdd8
--- /dev/null
+++ b/packages/cloud/src/contract/entitlements.ts
@@ -0,0 +1,22 @@
+import * as v from 'valibot'
+
+export const workspaceEntitlementsSchema = v.object({
+ features: v.object({
+ capabilityLinks: v.boolean(),
+ anonymousView: v.boolean(),
+ anonymousEdit: v.boolean(),
+ guestPresence: v.boolean(),
+ collaboration: v.boolean(),
+ revisionHistory: v.boolean()
+ }),
+ limits: v.object({
+ maximumFileBytes: v.pipe(v.number(), v.integer(), v.minValue(1)),
+ maximumStorageBytes: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1))),
+ maximumParticipants: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1)))
+ }),
+ usage: v.object({
+ committedStorageBytes: v.pipe(v.number(), v.integer(), v.minValue(0)),
+ reservedStorageBytes: v.pipe(v.number(), v.integer(), v.minValue(0))
+ })
+})
+export type WorkspaceEntitlements = v.InferOutput<typeof workspaceEntitlementsSchema>
diff --git a/packages/cloud/src/contract/index.ts b/packages/cloud/src/contract/index.ts
new file mode 100644
index 000000000..8854c6fbf
--- /dev/null
+++ b/packages/cloud/src/contract/index.ts
@@ -0,0 +1,125 @@
+export * from './account'
+export * from './admin'
+export {
+ collaborationPrincipalSchema,
+ collaborationTicketSchema,
+ type CollaborationPrincipal,
+ type CollaborationTicket
+} from './collaboration'
+export { workspaceEntitlementsSchema, type WorkspaceEntitlements } from './entitlements'
+export {
+ CLOUD_DISCOVERY_PATH,
+ CLOUD_PROTOCOL_VERSION,
+ cloudAuthenticationSchema,
+ cloudCapabilitiesSchema,
+ cloudDeploymentSchema,
+ cloudDiscoverySchema,
+ cloudEditorVersionSchema,
+ cloudListingSchema,
+ parseCloudDiscovery,
+ type CloudAuthentication,
+ type CloudCapabilities,
+ type CloudDeployment,
+ type CloudDiscovery,
+ type CloudListing
+} from './discovery'
+export {
+ CLOUD_PROTOCOL_MAX_UPLOAD_BYTES,
+ cloudActorSchema,
+ cloudSessionSchema,
+ commitUploadSchema,
+ createDocumentSchema,
+ createUploadSchema,
+ documentAccessSchema,
+ documentAccessSourceSchema,
+ documentDownloadSchema,
+ documentPermissionSchema,
+ documentSummarySchema,
+ sharedDocumentSchema,
+ type SharedDocument,
+ workspaceUsageSchema,
+ parseCommitUpload,
+ parseCreateDocument,
+ parseCreateUpload,
+ type CloudActorContract,
+ type CloudSession,
+ type CommitUploadInput,
+ type CreateDocumentInput,
+ type CreateUploadInput,
+ type DocumentAccess,
+ type DocumentAccessSource,
+ type DocumentDownload,
+ type DocumentPermission,
+ type DocumentSummary,
+ type WorkspaceUsage
+} from './documents'
+export {
+ acceptDocumentInvitationSchema,
+ cloudUserProfileSchema,
+ createInvitationContinuationSchema,
+ createDocumentInvitationSchema,
+ createDocumentShareSchema,
+ acceptedInvitationSchema,
+ documentGrantSchema,
+ documentInvitationSchema,
+ documentShareSchema,
+ invitationContinuationSchema,
+ invitationPreviewSchema,
+ lookupCloudUserSchema,
+ parseAcceptDocumentInvitation,
+ parseCreateInvitationContinuation,
+ parseCreateDocumentInvitation,
+ parseCreateDocumentShare,
+ parseLookupCloudUser,
+ parsePutDocumentGrant,
+ parseResolveDocumentShare,
+ parseUpdateDocumentShare,
+ putDocumentGrantSchema,
+ resolveDocumentShareSchema,
+ resolvedDocumentShareSchema,
+ updateDocumentShareSchema,
+ type AcceptDocumentInvitationInput,
+ type CloudUserProfile,
+ type CreateInvitationContinuationInput,
+ type CreateDocumentInvitationInput,
+ type CreateDocumentShareInput,
+ type AcceptedInvitation,
+ type DocumentGrant,
+ type DocumentInvitation,
+ type DocumentShare,
+ type InvitationContinuation,
+ type InvitationPreview,
+ type LookupCloudUserInput,
+ type PutDocumentGrantInput,
+ type ResolveDocumentShareInput,
+ type ResolvedDocumentShare,
+ type UpdateDocumentShareInput
+} from './sharing'
+export {
+ createWorkspaceInvitationSchema,
+ createWorkspaceSchema,
+ createdWorkspaceInvitationSchema,
+ parseCreateWorkspace,
+ parseCreateWorkspaceInvitation,
+ parseUpdateWorkspace,
+ parseUpdateWorkspaceMember,
+ updateWorkspaceMemberSchema,
+ updateWorkspaceSchema,
+ workspaceInvitationSchema,
+ workspaceListSchema,
+ workspaceMemberSchema,
+ workspaceMembersSchema,
+ workspaceRoleSchema,
+ workspaceSummarySchema,
+ type CreateWorkspaceInput,
+ type CreateWorkspaceInvitationInput,
+ type CreatedWorkspaceInvitation,
+ type UpdateWorkspaceInput,
+ type UpdateWorkspaceMemberInput,
+ type WorkspaceInvitation,
+ type WorkspaceList,
+ type WorkspaceMember,
+ type WorkspaceMembers,
+ type WorkspaceRole,
+ type WorkspaceSummary
+} from './workspaces'
diff --git a/packages/cloud/src/contract/sharing.ts b/packages/cloud/src/contract/sharing.ts
new file mode 100644
index 000000000..0905c847c
--- /dev/null
+++ b/packages/cloud/src/contract/sharing.ts
@@ -0,0 +1,180 @@
+import * as v from 'valibot'
+
+import { collaborationPrincipalSchema } from './collaboration'
+import { documentPermissionSchema } from './documents'
+import { workspaceRoleSchema } from './workspaces'
+
+export const documentShareSchema = v.object({
+ id: v.pipe(v.string(), v.uuid()),
+ documentId: v.pipe(v.string(), v.uuid()),
+ permission: documentPermissionSchema,
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
+ createdBy: v.string(),
+ createdAt: v.string(),
+ updatedAt: v.string(),
+ expiresAt: v.nullable(v.string()),
+ revokedAt: v.nullable(v.string()),
+ lastUsedAt: v.nullable(v.string())
+})
+export type DocumentShare = v.InferOutput<typeof documentShareSchema>
+
+/** When a link stops working, as an ISO timestamp; `null` keeps it working until revoked. */
+const shareExpirySchema = v.optional(v.nullable(v.pipe(v.string(), v.isoTimestamp())))
+
+export const createDocumentShareSchema = v.object({
+ permission: documentPermissionSchema,
+ expiresAt: shareExpirySchema
+})
+export type CreateDocumentShareInput = v.InferOutput<typeof createDocumentShareSchema>
+
+export const updateDocumentShareSchema = v.object({
+ permission: v.optional(documentPermissionSchema),
+ expiresAt: shareExpirySchema
+})
+export type UpdateDocumentShareInput = v.InferOutput<typeof updateDocumentShareSchema>
+
+export const resolveDocumentShareSchema = v.object({
+ secret: v.pipe(v.string(), v.minLength(32), v.maxLength(128)),
+ guestName: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),
+ guestId: v.optional(v.pipe(v.string(), v.minLength(16), v.maxLength(128)))
+})
+export type ResolveDocumentShareInput = v.InferOutput<typeof resolveDocumentShareSchema>
+
+export const resolvedDocumentShareSchema = v.object({
+ documentId: v.pipe(v.string(), v.uuid()),
+ permission: documentPermissionSchema,
+ principal: collaborationPrincipalSchema,
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0))
+})
+export type ResolvedDocumentShare = v.InferOutput<typeof resolvedDocumentShareSchema>
+
+export const cloudUserProfileSchema = v.object({
+ id: v.string(),
+ name: v.string(),
+ email: v.pipe(v.string(), v.email()),
+ image: v.nullable(v.pipe(v.string(), v.url()))
+})
+export type CloudUserProfile = v.InferOutput<typeof cloudUserProfileSchema>
+
+export const documentGrantSchema = v.object({
+ id: v.pipe(v.string(), v.uuid()),
+ documentId: v.pipe(v.string(), v.uuid()),
+ userId: v.string(),
+ permission: documentPermissionSchema,
+ createdBy: v.string(),
+ createdAt: v.string(),
+ updatedAt: v.string()
+})
+export type DocumentGrant = v.InferOutput<typeof documentGrantSchema>
+
+/** What accepting an invitation gave: access to a document, or a place in a workspace. */
+export const acceptedInvitationSchema = v.variant('kind', [
+ v.object({ kind: v.literal('document'), grant: documentGrantSchema }),
+ v.object({
+ kind: v.literal('workspace'),
+ workspaceId: v.pipe(v.string(), v.uuid()),
+ role: workspaceRoleSchema
+ })
+])
+export type AcceptedInvitation = v.InferOutput<typeof acceptedInvitationSchema>
+
+export const lookupCloudUserSchema = v.object({
+ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email())
+})
+export type LookupCloudUserInput = v.InferOutput<typeof lookupCloudUserSchema>
+
+export const putDocumentGrantSchema = v.object({ permission: documentPermissionSchema })
+export type PutDocumentGrantInput = v.InferOutput<typeof putDocumentGrantSchema>
+
+export const createDocumentInvitationSchema = v.object({
+ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
+ permission: documentPermissionSchema
+})
+export type CreateDocumentInvitationInput = v.InferOutput<typeof createDocumentInvitationSchema>
+
+export const acceptDocumentInvitationSchema = v.object({
+ token: v.pipe(v.string(), v.minLength(32), v.maxLength(128))
+})
+export type AcceptDocumentInvitationInput = v.InferOutput<typeof acceptDocumentInvitationSchema>
+
+export const createInvitationContinuationSchema = v.object({
+ invitationId: v.pipe(v.string(), v.uuid()),
+ token: v.pipe(v.string(), v.minLength(32), v.maxLength(128))
+})
+export type CreateInvitationContinuationInput = v.InferOutput<
+ typeof createInvitationContinuationSchema
+>
+
+export const invitationContinuationSchema = v.object({
+ id: v.pipe(v.string(), v.minLength(16), v.maxLength(128))
+})
+export type InvitationContinuation = v.InferOutput<typeof invitationContinuationSchema>
+
+const invitationPreviewFields = {
+ inviterName: v.string(),
+ expiresAt: v.string(),
+ recipientHint: v.string()
+}
+
+/** What an invitation link opens: one document, or a whole workspace. */
+export const invitationPreviewSchema = v.variant('kind', [
+ v.object({
+ kind: v.literal('document'),
+ documentName: v.string(),
+ permission: documentPermissionSchema,
+ ...invitationPreviewFields
+ }),
+ v.object({
+ kind: v.literal('workspace'),
+ workspaceName: v.string(),
+ role: workspaceRoleSchema,
+ ...invitationPreviewFields
+ })
+])
+export type InvitationPreview = v.InferOutput<typeof invitationPreviewSchema>
+
+export const documentInvitationSchema = v.object({
+ id: v.pipe(v.string(), v.uuid()),
+ documentId: v.pipe(v.string(), v.uuid()),
+ email: v.pipe(v.string(), v.email()),
+ permission: documentPermissionSchema,
+ invitedBy: v.string(),
+ invitedAt: v.string(),
+ expiresAt: v.string(),
+ acceptedAt: v.nullable(v.string())
+})
+export type DocumentInvitation = v.InferOutput<typeof documentInvitationSchema>
+
+export function parseCreateInvitationContinuation(
+ input: unknown
+): CreateInvitationContinuationInput {
+ return v.parse(createInvitationContinuationSchema, input)
+}
+
+export function parseLookupCloudUser(input: unknown): LookupCloudUserInput {
+ return v.parse(lookupCloudUserSchema, input)
+}
+
+export function parseCreateDocumentShare(input: unknown): CreateDocumentShareInput {
+ return v.parse(createDocumentShareSchema, input)
+}
+
+export function parseUpdateDocumentShare(input: unknown): UpdateDocumentShareInput {
+ return v.parse(updateDocumentShareSchema, input)
+}
+
+export function parseResolveDocumentShare(input: unknown): ResolveDocumentShareInput {
+ return v.parse(resolveDocumentShareSchema, input)
+}
+
+export function parsePutDocumentGrant(input: unknown): PutDocumentGrantInput {
+ return v.parse(putDocumentGrantSchema, input)
+}
+
+export function parseCreateDocumentInvitation(input: unknown): CreateDocumentInvitationInput {
+ return v.parse(createDocumentInvitationSchema, input)
+}
+
+export function parseAcceptDocumentInvitation(input: unknown): AcceptDocumentInvitationInput {
+ return v.parse(acceptDocumentInvitationSchema, input)
+}
diff --git a/packages/cloud/src/contract/workspaces.ts b/packages/cloud/src/contract/workspaces.ts
new file mode 100644
index 000000000..4f4905f87
--- /dev/null
+++ b/packages/cloud/src/contract/workspaces.ts
@@ -0,0 +1,97 @@
+import * as v from 'valibot'
+
+export const workspaceRoleSchema = v.picklist(['viewer', 'editor', 'admin'])
+export type WorkspaceRole = v.InferOutput<typeof workspaceRoleSchema>
+
+export const workspaceSummarySchema = v.object({
+ id: v.pipe(v.string(), v.uuid()),
+ name: v.string(),
+ slug: v.string(),
+ role: workspaceRoleSchema,
+ createdAt: v.string(),
+ updatedAt: v.string()
+})
+export type WorkspaceSummary = v.InferOutput<typeof workspaceSummarySchema>
+
+export const createWorkspaceSchema = v.object({
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)),
+ slug: v.optional(
+ v.pipe(
+ v.string(),
+ v.trim(),
+ v.minLength(3),
+ v.maxLength(63),
+ v.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)
+ )
+ )
+})
+export type CreateWorkspaceInput = v.InferOutput<typeof createWorkspaceSchema>
+
+export const workspaceListSchema = v.object({
+ workspaces: v.array(workspaceSummarySchema)
+})
+export type WorkspaceList = v.InferOutput<typeof workspaceListSchema>
+
+export const updateWorkspaceSchema = v.object({
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100))
+})
+export type UpdateWorkspaceInput = v.InferOutput<typeof updateWorkspaceSchema>
+
+/** Someone who belongs to a workspace, and what they may do in it. */
+export const workspaceMemberSchema = v.object({
+ userId: v.string(),
+ name: v.string(),
+ email: v.string(),
+ role: workspaceRoleSchema,
+ joinedAt: v.string()
+})
+export type WorkspaceMember = v.InferOutput<typeof workspaceMemberSchema>
+
+/** An invitation to join a workspace that has not been accepted yet. */
+export const workspaceInvitationSchema = v.object({
+ id: v.pipe(v.string(), v.uuid()),
+ email: v.string(),
+ role: workspaceRoleSchema,
+ invitedAt: v.string(),
+ expiresAt: v.string()
+})
+export type WorkspaceInvitation = v.InferOutput<typeof workspaceInvitationSchema>
+
+export const workspaceMembersSchema = v.object({
+ members: v.array(workspaceMemberSchema),
+ /** Only administrators see pending invitations. */
+ invitations: v.array(workspaceInvitationSchema)
+})
+export type WorkspaceMembers = v.InferOutput<typeof workspaceMembersSchema>
+
+export const createWorkspaceInvitationSchema = v.object({
+ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
+ role: workspaceRoleSchema
+})
+export type CreateWorkspaceInvitationInput = v.InferOutput<typeof createWorkspaceInvitationSchema>
+
+/** A new invitation and its link, for an administrator to pass on when email is off. */
+export const createdWorkspaceInvitationSchema = v.object({
+ invitation: workspaceInvitationSchema,
+ acceptanceURL: v.string()
+})
+export type CreatedWorkspaceInvitation = v.InferOutput<typeof createdWorkspaceInvitationSchema>
+
+export const updateWorkspaceMemberSchema = v.object({ role: workspaceRoleSchema })
+export type UpdateWorkspaceMemberInput = v.InferOutput<typeof updateWorkspaceMemberSchema>
+
+export function parseCreateWorkspace(input: unknown): CreateWorkspaceInput {
+ return v.parse(createWorkspaceSchema, input)
+}
+
+export function parseUpdateWorkspace(input: unknown): UpdateWorkspaceInput {
+ return v.parse(updateWorkspaceSchema, input)
+}
+
+export function parseCreateWorkspaceInvitation(input: unknown): CreateWorkspaceInvitationInput {
+ return v.parse(createWorkspaceInvitationSchema, input)
+}
+
+export function parseUpdateWorkspaceMember(input: unknown): UpdateWorkspaceMemberInput {
+ return v.parse(updateWorkspaceMemberSchema, input)
+}
diff --git a/packages/cloud/src/email/index.ts b/packages/cloud/src/email/index.ts
new file mode 100644
index 000000000..6f24770bc
--- /dev/null
+++ b/packages/cloud/src/email/index.ts
@@ -0,0 +1,12 @@
+export { renderTransactionalEmail } from './render'
+export { transactionalEmailContentSchema } from './types'
+export type {
+ AdminEnrollmentNotificationPayload,
+ DocumentInvitationEmailPayload,
+ EnrollmentEmailPayload,
+ RenderedTransactionalEmail,
+ TransactionalEmailContent,
+ TransactionalEmailKind,
+ TransactionalEmailMessage,
+ TransactionalEmailPayloadByKind
+} from './types'
diff --git a/packages/cloud/src/email/render.ts b/packages/cloud/src/email/render.ts
new file mode 100644
index 000000000..8296e488c
--- /dev/null
+++ b/packages/cloud/src/email/render.ts
@@ -0,0 +1,184 @@
+import { render } from '@vue-email/render'
+
+import { DocumentInvitationEmail } from './templates/document-invitation'
+import { EnrollmentEmail } from './templates/enrollment'
+import type {
+ AdminEnrollmentNotificationPayload,
+ AuthenticationEmailPayload,
+ DocumentInvitationEmailPayload,
+ WorkspaceInvitationEmailPayload,
+ EnrollmentEmailPayload,
+ RenderedTransactionalEmail,
+ TransactionalEmailContent,
+ TransactionalEmailKind
+} from './types'
+
+async function rendered(
+ component: Parameters<typeof render>[0],
+ props: Record<string, string | undefined>,
+ subject: string
+): Promise<RenderedTransactionalEmail> {
+ const [html, text] = await Promise.all([
+ render(component, props),
+ render(component, props, { plainText: true })
+ ])
+ return { subject, html, text }
+}
+
+async function renderDocumentInvitation(payload: DocumentInvitationEmailPayload) {
+ const permissionLabel = payload.permission === 'edit' ? 'edit' : 'view'
+ return rendered(
+ DocumentInvitationEmail,
+ {
+ inviterName: payload.inviterName,
+ documentName: payload.documentName,
+ permissionLabel,
+ expiresAt: new Date(payload.expiresAt).toUTCString(),
+ acceptanceURL: payload.acceptanceURL
+ },
+ `${payload.inviterName} invited you to ${permissionLabel} ${payload.documentName}`
+ )
+}
+
+const WORKSPACE_ROLE_LABELS = { admin: 'manage', editor: 'edit in', viewer: 'view' } as const
+
+async function renderWorkspaceInvitation(payload: WorkspaceInvitationEmailPayload) {
+ const action = WORKSPACE_ROLE_LABELS[payload.role]
+ return rendered(
+ EnrollmentEmail,
+ {
+ heading: `Join ${payload.workspaceName}`,
+ preview: `${payload.inviterName} invited you to ${payload.workspaceName}`,
+ message: `${payload.inviterName} invited you to ${action} the workspace “${payload.workspaceName}” on OpenPencil Cloud. You will see its documents on Home once you join.`,
+ actionLabel: 'Join workspace',
+ actionURL: payload.acceptanceURL,
+ footer: `This invitation expires ${new Date(payload.expiresAt).toUTCString()}.`
+ },
+ `${payload.inviterName} invited you to ${payload.workspaceName}`
+ )
+}
+
+type EnrollmentMessageKind = Exclude<
+ TransactionalEmailKind,
+ | 'document-invitation'
+ | 'workspace-invitation'
+ | 'admin-enrollment-notification'
+ | 'email-verification'
+ | 'password-reset'
+ | 'password-changed'
+>
+
+type EnrollmentCopy = {
+ subject: string
+ heading: string
+ preview: string
+ message: string
+ actionLabel: string
+}
+
+const ENROLLMENT_COPY: Record<EnrollmentMessageKind, Omit<EnrollmentCopy, 'message'>> = {
+ 'enrollment-requested': {
+ subject: 'We received your OpenPencil Cloud request',
+ heading: 'Request received',
+ preview: 'Your OpenPencil Cloud access request is awaiting review.',
+ actionLabel: 'Open OpenPencil Cloud'
+ },
+ 'enrollment-approved': {
+ subject: 'Your OpenPencil Cloud access is ready',
+ heading: 'Access approved',
+ preview: 'You can now sign in to OpenPencil Cloud.',
+ actionLabel: 'Sign in'
+ },
+ 'enrollment-rejected': {
+ subject: 'Your OpenPencil Cloud request was reviewed',
+ heading: 'Request reviewed',
+ preview: 'Your current access request was not approved.',
+ actionLabel: 'Request access again'
+ },
+ 'enrollment-revoked': {
+ subject: 'Your OpenPencil Cloud access has changed',
+ heading: 'Access changed',
+ preview: 'Your OpenPencil Cloud access is no longer active.',
+ actionLabel: 'Open OpenPencil'
+ }
+}
+
+function enrollmentCopy(kind: EnrollmentMessageKind, name: string): EnrollmentCopy {
+ const copy = ENROLLMENT_COPY[kind]
+ const messages: Record<EnrollmentMessageKind, string> = {
+ 'enrollment-requested': `Hi ${name}, your request is awaiting manual review.`,
+ 'enrollment-approved': `Hi ${name}, your access request was approved.`,
+ 'enrollment-rejected': `Hi ${name}, your current access request was not approved.`,
+ 'enrollment-revoked': `Hi ${name}, your Cloud access is no longer active.`
+ }
+ return { ...copy, message: messages[kind] }
+}
+
+async function renderEnrollment(kind: EnrollmentMessageKind, payload: EnrollmentEmailPayload) {
+ const copy = enrollmentCopy(kind, payload.name)
+ return rendered(EnrollmentEmail, { ...copy, actionURL: payload.actionURL }, copy.subject)
+}
+
+async function renderAdminNotification(payload: AdminEnrollmentNotificationPayload) {
+ return rendered(
+ EnrollmentEmail,
+ {
+ heading: 'New Cloud access request',
+ preview: `${payload.requesterEmail} requested OpenPencil Cloud access.`,
+ message: `${payload.requesterName} (${payload.requesterEmail}) requested access. ${payload.reason}`,
+ actionLabel: 'Review request',
+ actionURL: payload.actionURL
+ },
+ 'New OpenPencil Cloud access request'
+ )
+}
+
+async function renderAuthentication(
+ kind: 'email-verification' | 'password-reset' | 'password-changed',
+ payload: AuthenticationEmailPayload
+) {
+ const copy = {
+ 'email-verification': {
+ subject: 'Confirm your OpenPencil Cloud email',
+ heading: 'Confirm your email',
+ preview: 'One click to finish creating your OpenPencil Cloud account.',
+ message: `Hi ${payload.name}, confirm this address to finish creating your OpenPencil Cloud account. Then go back to OpenPencil; it signs you in by itself.`,
+ actionLabel: 'Confirm email',
+ footer: 'Didn’t create an account? Ignore this email and nothing happens.'
+ },
+ 'password-reset': {
+ subject: 'Reset your OpenPencil Cloud password',
+ heading: 'Reset your password',
+ preview: 'Use this secure link to choose a new password.',
+ message: `Hi ${payload.name}, use the link below to choose a new password.`,
+ actionLabel: 'Reset password',
+ footer: 'Didn’t ask for this? Ignore this email and your password stays the same.'
+ },
+ 'password-changed': {
+ subject: 'Your OpenPencil Cloud password changed',
+ heading: 'Password changed',
+ preview: 'Your OpenPencil Cloud password was changed.',
+ message: `Hi ${payload.name}, your password was changed. If this was not you, contact your administrator.`,
+ actionLabel: 'Open OpenPencil Cloud'
+ }
+ }[kind]
+ return rendered(EnrollmentEmail, { ...copy, actionURL: payload.actionURL ?? '#' }, copy.subject)
+}
+
+export async function renderTransactionalEmail(
+ content: TransactionalEmailContent
+): Promise<RenderedTransactionalEmail> {
+ if (content.kind === 'document-invitation') return renderDocumentInvitation(content.payload)
+ if (content.kind === 'workspace-invitation') return renderWorkspaceInvitation(content.payload)
+ if (content.kind === 'admin-enrollment-notification') {
+ return renderAdminNotification(content.payload)
+ }
+ if (
+ content.kind === 'email-verification' ||
+ content.kind === 'password-reset' ||
+ content.kind === 'password-changed'
+ ) {
+ return renderAuthentication(content.kind, content.payload)
+ }
+ return renderEnrollment(content.kind, content.payload)
+}
diff --git a/packages/cloud/src/email/templates/document-invitation.ts b/packages/cloud/src/email/templates/document-invitation.ts
new file mode 100644
index 000000000..747c228ea
--- /dev/null
+++ b/packages/cloud/src/email/templates/document-invitation.ts
@@ -0,0 +1,35 @@
+import { defineComponent, type PropType } from 'vue'
+
+import { transactionalEmailLayout } from './layout'
+
+export type DocumentInvitationEmailProps = {
+ inviterName: string
+ documentName: string
+ permissionLabel: string
+ expiresAt: string
+ acceptanceURL: string
+}
+
+export const DocumentInvitationEmail = defineComponent({
+ props: {
+ inviterName: { type: String, required: true },
+ documentName: { type: String, required: true },
+ permissionLabel: { type: String, required: true },
+ expiresAt: { type: String, required: true },
+ acceptanceURL: { type: String, required: true }
+ } satisfies Record<
+ keyof DocumentInvitationEmailProps,
+ { type: PropType<string>; required: true }
+ >,
+ setup(props) {
+ return () =>
+ transactionalEmailLayout({
+ preview: `${props.inviterName} invited you to ${props.permissionLabel} a document`,
+ heading: 'OpenPencil invitation',
+ message: `${props.inviterName} invited you to ${props.permissionLabel} “${props.documentName}”.`,
+ actionLabel: 'Open document',
+ actionURL: props.acceptanceURL,
+ footer: `This invitation expires ${props.expiresAt}.`
+ })
+ }
+})
diff --git a/packages/cloud/src/email/templates/enrollment.ts b/packages/cloud/src/email/templates/enrollment.ts
new file mode 100644
index 000000000..a6f332284
--- /dev/null
+++ b/packages/cloud/src/email/templates/enrollment.ts
@@ -0,0 +1,27 @@
+import { defineComponent, type PropType } from 'vue'
+
+import { transactionalEmailLayout } from './layout'
+
+export type EnrollmentEmailProps = {
+ heading: string
+ preview: string
+ message: string
+ actionLabel: string
+ actionURL: string
+ /** Small print under the button. */
+ footer?: string
+}
+
+export const EnrollmentEmail = defineComponent({
+ props: {
+ heading: { type: String, required: true },
+ preview: { type: String, required: true },
+ message: { type: String, required: true },
+ actionLabel: { type: String, required: true },
+ actionURL: { type: String, required: true },
+ footer: { type: String, required: false }
+ } satisfies Record<keyof EnrollmentEmailProps, { type: PropType<string>; required: boolean }>,
+ setup(props) {
+ return () => transactionalEmailLayout(props)
+ }
+})
diff --git a/packages/cloud/src/email/templates/layout.ts b/packages/cloud/src/email/templates/layout.ts
new file mode 100644
index 000000000..4beb61bd9
--- /dev/null
+++ b/packages/cloud/src/email/templates/layout.ts
@@ -0,0 +1,18 @@
+import type { VNode } from 'vue'
+
+import { emailLayout } from '@open-pencil/feedback/email'
+
+export type TransactionalEmailLayout = {
+ preview: string
+ heading: string
+ message: string
+ actionLabel: string
+ actionURL: string
+ footer?: string
+}
+
+/** Cloud's mail in the same branded layout as the waitlist's, so people know who wrote. */
+export function transactionalEmailLayout(props: TransactionalEmailLayout): VNode {
+ const { footer, ...content } = props
+ return emailLayout({ ...content, note: footer ? { text: footer } : undefined })
+}
diff --git a/packages/cloud/src/email/types.ts b/packages/cloud/src/email/types.ts
new file mode 100644
index 000000000..a6fc23871
--- /dev/null
+++ b/packages/cloud/src/email/types.ts
@@ -0,0 +1,101 @@
+import { documentPermissionSchema, workspaceRoleSchema } from '#cloud/contract'
+import * as v from 'valibot'
+
+export type TransactionalEmailKind =
+ | 'document-invitation'
+ | 'workspace-invitation'
+ | 'enrollment-requested'
+ | 'admin-enrollment-notification'
+ | 'enrollment-approved'
+ | 'enrollment-rejected'
+ | 'enrollment-revoked'
+ | 'email-verification'
+ | 'password-reset'
+ | 'password-changed'
+
+const documentInvitationEmailPayloadSchema = v.object({
+ inviterName: v.string(),
+ documentName: v.string(),
+ permission: documentPermissionSchema,
+ expiresAt: v.string(),
+ acceptanceURL: v.string()
+})
+
+const workspaceInvitationEmailPayloadSchema = v.object({
+ inviterName: v.string(),
+ workspaceName: v.string(),
+ role: workspaceRoleSchema,
+ expiresAt: v.string(),
+ acceptanceURL: v.string()
+})
+
+const enrollmentEmailPayloadSchema = v.object({
+ name: v.string(),
+ actionURL: v.string()
+})
+
+const adminEnrollmentNotificationPayloadSchema = v.object({
+ requesterEmail: v.string(),
+ requesterName: v.string(),
+ reason: v.string(),
+ actionURL: v.string()
+})
+
+const authenticationEmailPayloadSchema = v.object({
+ name: v.string(),
+ actionURL: v.optional(v.string())
+})
+
+function content<const Kind extends TransactionalEmailKind, Payload extends v.GenericSchema>(
+ kind: Kind,
+ payload: Payload
+) {
+ return v.object({ kind: v.literal(kind), payload })
+}
+
+export const transactionalEmailContentSchema = v.variant('kind', [
+ content('document-invitation', documentInvitationEmailPayloadSchema),
+ content('workspace-invitation', workspaceInvitationEmailPayloadSchema),
+ content('enrollment-requested', enrollmentEmailPayloadSchema),
+ content('admin-enrollment-notification', adminEnrollmentNotificationPayloadSchema),
+ content('enrollment-approved', enrollmentEmailPayloadSchema),
+ content('enrollment-rejected', enrollmentEmailPayloadSchema),
+ content('enrollment-revoked', enrollmentEmailPayloadSchema),
+ content('email-verification', authenticationEmailPayloadSchema),
+ content('password-reset', authenticationEmailPayloadSchema),
+ content('password-changed', authenticationEmailPayloadSchema)
+])
+
+/** A transactional email's kind with the payload that kind renders. */
+export type TransactionalEmailContent = v.InferOutput<typeof transactionalEmailContentSchema>
+
+export type DocumentInvitationEmailPayload = v.InferOutput<
+ typeof documentInvitationEmailPayloadSchema
+>
+export type WorkspaceInvitationEmailPayload = v.InferOutput<
+ typeof workspaceInvitationEmailPayloadSchema
+>
+export type EnrollmentEmailPayload = v.InferOutput<typeof enrollmentEmailPayloadSchema>
+export type AdminEnrollmentNotificationPayload = v.InferOutput<
+ typeof adminEnrollmentNotificationPayloadSchema
+>
+export type AuthenticationEmailPayload = v.InferOutput<typeof authenticationEmailPayloadSchema>
+
+export type TransactionalEmailPayloadByKind = {
+ [Kind in TransactionalEmailKind]: Extract<TransactionalEmailContent, { kind: Kind }>['payload']
+}
+
+export type TransactionalEmailMessage<
+ Kind extends TransactionalEmailKind = TransactionalEmailKind
+> = {
+ id: string
+ kind: Kind
+ recipientEmail: string
+ payload: TransactionalEmailPayloadByKind[Kind]
+}
+
+export type RenderedTransactionalEmail = {
+ subject: string
+ html: string
+ text: string
+}
diff --git a/packages/cloud/src/runtime/node/admin.ts b/packages/cloud/src/runtime/node/admin.ts
new file mode 100644
index 000000000..1de845146
--- /dev/null
+++ b/packages/cloud/src/runtime/node/admin.ts
@@ -0,0 +1,59 @@
+#!/usr/bin/env node
+
+import { createMigratedNodeCloudDatabase } from './bootstrap'
+
+const [operation, email] = process.argv.slice(2)
+if ((operation !== 'approve' && operation !== 'grant') || !email) {
+ throw new Error('Usage: admin <approve|grant> <email>')
+}
+
+const { database } = await createMigratedNodeCloudDatabase(process.env)
+try {
+ const normalized = email.trim().toLowerCase()
+ if (operation === 'approve') {
+ await database
+ .insertInto('cloudEnrollment')
+ .values({
+ id: crypto.randomUUID(),
+ emailNormalized: normalized,
+ name: null,
+ reason: 'Administrative bootstrap',
+ status: 'approved',
+ reviewedAt: new Date(),
+ reviewedBy: 'cli-bootstrap',
+ reviewNote: 'Approved through CLI bootstrap',
+ approvedUserId: null
+ })
+ .onConflict((conflict) =>
+ conflict.column('emailNormalized').doUpdateSet({
+ status: 'approved',
+ reviewedAt: new Date(),
+ reviewedBy: 'cli-bootstrap',
+ reviewNote: 'Approved through CLI bootstrap'
+ })
+ )
+ .execute()
+ console.log(JSON.stringify({ approved: normalized }))
+ } else {
+ const user = await database
+ .selectFrom('user')
+ .select(['id', 'email'])
+ .where('email', '=', normalized)
+ .executeTakeFirstOrThrow()
+ await database.updateTable('user').set({ role: 'admin' }).where('id', '=', user.id).execute()
+ await database
+ .insertInto('cloudAdminAuditEvent')
+ .values({
+ id: crypto.randomUUID(),
+ actorUserId: 'cli-bootstrap',
+ action: 'user.admin-granted',
+ subjectType: 'user',
+ subjectId: user.id,
+ metadata: { email: normalized }
+ })
+ .execute()
+ console.log(JSON.stringify({ admin: normalized, userId: user.id }))
+ }
+} finally {
+ await database.destroy()
+}
diff --git a/packages/cloud/src/runtime/node/application.ts b/packages/cloud/src/runtime/node/application.ts
new file mode 100644
index 000000000..78e5a74bc
--- /dev/null
+++ b/packages/cloud/src/runtime/node/application.ts
@@ -0,0 +1,47 @@
+import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
+import {
+ createCloudAuthenticationRuntime,
+ createCloudApp,
+ type CloudApp,
+ type CloudEnvironment,
+ type CloudServerConfig,
+ type ObjectStore
+} from '#cloud/server'
+
+import { loadNodeCloudServerConfig } from './config'
+import { createNodeCloudDatabase } from './database'
+import { createNodeTransactionalEmailRuntime } from './email-runtime'
+
+export type NodeCloudApplicationOptions = {
+ environment?: CloudEnvironment
+ databaseURL?: string
+}
+
+export async function createNodeCloudApplication(
+ options: NodeCloudApplicationOptions = {}
+): Promise<{
+ app: CloudApp
+ config: CloudServerConfig
+ database: ReturnType<typeof createNodeCloudDatabase>
+ objects: ObjectStore
+ email: ReturnType<typeof createNodeTransactionalEmailRuntime>['email']
+}> {
+ const environment = options.environment ?? process.env
+ const config = await loadNodeCloudServerConfig(environment)
+ const database = createNodeCloudDatabase({
+ connectionString: options.databaseURL ?? config.databaseURL
+ })
+ const objects = createS3ObjectStore(config)
+ const { email, invitationOutbox } = createNodeTransactionalEmailRuntime(config, database)
+ const { auth, enrollment } = createCloudAuthenticationRuntime(config, database, email)
+ const app = createCloudApp({
+ config,
+ database,
+ auth,
+ objects,
+ invitationOutbox,
+ transactionalEmail: email,
+ enrollment
+ })
+ return { app, config, database, objects, email }
+}
diff --git a/packages/cloud/src/runtime/node/bootstrap.ts b/packages/cloud/src/runtime/node/bootstrap.ts
new file mode 100644
index 000000000..d7e13dacb
--- /dev/null
+++ b/packages/cloud/src/runtime/node/bootstrap.ts
@@ -0,0 +1,22 @@
+import {
+ createBetterAuthAdapter,
+ migrateCloudDatabase,
+ type CloudServerConfig
+} 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>
+ auth: ReturnType<typeof createBetterAuthAdapter>
+}> {
+ const config = await loadNodeCloudServerConfig(environment)
+ const database = createNodeCloudDatabase({ 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
new file mode 100644
index 000000000..b6019e268
--- /dev/null
+++ b/packages/cloud/src/runtime/node/cleanup.ts
@@ -0,0 +1,23 @@
+import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
+import { createDocumentCleanupService, createUploadCleanupService } from '#cloud/server'
+
+import { loadNodeCloudServerConfig } from './config'
+import { createNodeCloudDatabase } from './database'
+
+const config = await loadNodeCloudServerConfig(process.env)
+const database = createNodeCloudDatabase({ 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
+ })
+ console.log(JSON.stringify({ uploads, documents }))
+} finally {
+ await database.destroy()
+}
diff --git a/packages/cloud/src/runtime/node/command.ts b/packages/cloud/src/runtime/node/command.ts
new file mode 100644
index 000000000..837e2d842
--- /dev/null
+++ b/packages/cloud/src/runtime/node/command.ts
@@ -0,0 +1,17 @@
+import { createMigratedNodeCloudDatabase } from './bootstrap'
+
+type MigratedNodeCloudDatabase = Awaited<ReturnType<typeof createMigratedNodeCloudDatabase>>
+
+export async function withNodeCloudDatabase<T>(
+ operation: (
+ database: MigratedNodeCloudDatabase['database'],
+ config: MigratedNodeCloudDatabase['config']
+ ) => Promise<T>
+): Promise<T> {
+ const { config, database } = await createMigratedNodeCloudDatabase(process.env)
+ try {
+ return await operation(database, config)
+ } finally {
+ await database.destroy()
+ }
+}
diff --git a/packages/cloud/src/runtime/node/config.ts b/packages/cloud/src/runtime/node/config.ts
new file mode 100644
index 000000000..6078ebb45
--- /dev/null
+++ b/packages/cloud/src/runtime/node/config.ts
@@ -0,0 +1,16 @@
+import { readFile } from 'node:fs/promises'
+
+import {
+ CloudConfigError,
+ parseCloudDeploymentTOML,
+ type CloudEnvironment,
+ type CloudServerConfig
+} from '#cloud/server'
+
+export async function loadNodeCloudServerConfig(
+ environment: CloudEnvironment
+): Promise<CloudServerConfig> {
+ const path = environment.OPENPENCIL_CLOUD_CONFIG
+ if (!path) throw new CloudConfigError('OPENPENCIL_CLOUD_CONFIG must name a deployment TOML file')
+ return parseCloudDeploymentTOML(await readFile(path, 'utf8'), environment)
+}
diff --git a/packages/cloud/src/runtime/node/database.ts b/packages/cloud/src/runtime/node/database.ts
new file mode 100644
index 000000000..3ba74110f
--- /dev/null
+++ b/packages/cloud/src/runtime/node/database.ts
@@ -0,0 +1,19 @@
+import { createCloudDatabase } from '#cloud/server'
+import { PostgresDialect } from 'kysely'
+import { Pool, type PoolConfig } from 'pg'
+
+export type NodeCloudDatabaseOptions = {
+ connectionString: string
+ pool?: Omit<PoolConfig, 'connectionString'>
+}
+
+export function createNodeCloudDatabase(options: NodeCloudDatabaseOptions) {
+ return createCloudDatabase({
+ dialect: new PostgresDialect({
+ pool: new Pool({
+ ...options.pool,
+ connectionString: options.connectionString
+ })
+ })
+ })
+}
diff --git a/packages/cloud/src/runtime/node/email-runtime.ts b/packages/cloud/src/runtime/node/email-runtime.ts
new file mode 100644
index 000000000..8f4e65a1e
--- /dev/null
+++ b/packages/cloud/src/runtime/node/email-runtime.ts
@@ -0,0 +1,42 @@
+import { createSMTPTransactionalEmailTransport } from '#cloud/runtime/node/email'
+import {
+ createInvitationOutbox,
+ createTransactionalEmailService,
+ type CloudServerConfig,
+ type TransactionalEmailService,
+ type TransactionalEmailTransport
+} from '#cloud/server'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { Kysely } from 'kysely'
+
+export type NodeTransactionalEmailRuntime = {
+ email: TransactionalEmailService
+ transport?: TransactionalEmailTransport
+ invitationOutbox?: ReturnType<typeof createInvitationOutbox>
+}
+
+export function createNodeTransactionalEmailRuntime(
+ config: CloudServerConfig,
+ database: Kysely<CloudDatabase>
+): NodeTransactionalEmailRuntime {
+ const transport =
+ config.emailTransport === 'smtp' && config.smtpHost && config.smtpPort
+ ? createSMTPTransactionalEmailTransport({
+ host: config.smtpHost,
+ port: config.smtpPort,
+ secure: config.smtpSecure ?? config.smtpPort === 465,
+ user: config.smtpUser,
+ password: config.smtpPassword
+ })
+ : undefined
+ const email = createTransactionalEmailService(database, {
+ encryptionSecret: config.authSecret,
+ from: config.emailFrom ?? '',
+ transport
+ })
+ return {
+ email,
+ transport,
+ invitationOutbox: transport ? createInvitationOutbox(email) : undefined
+ }
+}
diff --git a/packages/cloud/src/runtime/node/email.ts b/packages/cloud/src/runtime/node/email.ts
new file mode 100644
index 000000000..f2d3e07d4
--- /dev/null
+++ b/packages/cloud/src/runtime/node/email.ts
@@ -0,0 +1,112 @@
+import { renderTransactionalEmail } from '#cloud/email'
+import type { TransactionalEmailTransport } from '#cloud/server/email'
+import type { DocumentInvitationMessage, InvitationDelivery } from '#cloud/server/invitations'
+import nodemailer, { type Transporter } from 'nodemailer'
+import type Mail from 'nodemailer/lib/mailer/index.js'
+
+export type NodemailerTransporter = {
+ sendMail(mail: Mail.Options): Promise<unknown>
+}
+
+export type NodemailerTransactionalEmailTransportOptions = {
+ transporter: NodemailerTransporter
+}
+
+export function createNodemailerTransactionalEmailTransport(
+ options: NodemailerTransactionalEmailTransportOptions
+): TransactionalEmailTransport {
+ return {
+ id: 'smtp',
+ async send(message) {
+ const result = (await options.transporter.sendMail({
+ from: message.from,
+ to: message.to,
+ subject: message.subject,
+ html: message.html,
+ text: message.text,
+ headers: message.headers,
+ messageId: `<${message.deliveryId}@openpencil.cloud>`
+ })) as { messageId?: unknown }
+ if (typeof result.messageId !== 'string') {
+ throw new TypeError('SMTP transport returned no message ID')
+ }
+ return {
+ transportMessageId: result.messageId,
+ acceptedAt: new Date().toISOString()
+ }
+ }
+ }
+}
+
+export type SMTPTransactionalEmailTransportOptions = {
+ host: string
+ port: number
+ secure: boolean
+ user?: string
+ password?: string
+}
+
+function createSMTPTransporter(options: SMTPTransactionalEmailTransportOptions): Transporter {
+ return nodemailer.createTransport({
+ host: options.host,
+ port: options.port,
+ secure: options.secure,
+ connectionTimeout: 10_000,
+ greetingTimeout: 10_000,
+ socketTimeout: 30_000,
+ auth:
+ options.user && options.password ? { user: options.user, pass: options.password } : undefined
+ })
+}
+
+export function createSMTPTransactionalEmailTransport(
+ options: SMTPTransactionalEmailTransportOptions
+): TransactionalEmailTransport {
+ return createNodemailerTransactionalEmailTransport({
+ transporter: createSMTPTransporter(options)
+ })
+}
+
+export type NodemailerInvitationDeliveryOptions = NodemailerTransactionalEmailTransportOptions & {
+ from: string
+}
+
+export function createNodemailerInvitationDelivery(
+ options: NodemailerInvitationDeliveryOptions
+): InvitationDelivery {
+ const transport = createNodemailerTransactionalEmailTransport(options)
+ return {
+ async sendDocumentInvitation(message: DocumentInvitationMessage): Promise<void> {
+ const rendered = await renderTransactionalEmail({
+ kind: 'document-invitation',
+ payload: {
+ inviterName: message.inviterName,
+ documentName: message.documentName,
+ permission: message.permission,
+ expiresAt: message.expiresAt,
+ acceptanceURL: message.acceptanceURL
+ }
+ })
+ await transport.send({
+ deliveryId: message.deliveryId,
+ from: options.from,
+ to: message.recipientEmail,
+ ...rendered,
+ headers: { 'X-OpenPencil-Delivery-ID': message.deliveryId }
+ })
+ }
+ }
+}
+
+export type SMTPInvitationDeliveryOptions = SMTPTransactionalEmailTransportOptions & {
+ from: string
+}
+
+export function createSMTPInvitationDelivery(
+ options: SMTPInvitationDeliveryOptions
+): InvitationDelivery {
+ return createNodemailerInvitationDelivery({
+ transporter: createSMTPTransporter(options),
+ from: options.from
+ })
+}
diff --git a/packages/cloud/src/runtime/node/entitlements-command.ts b/packages/cloud/src/runtime/node/entitlements-command.ts
new file mode 100644
index 000000000..5264d2eba
--- /dev/null
+++ b/packages/cloud/src/runtime/node/entitlements-command.ts
@@ -0,0 +1,15 @@
+import type { CloudServerConfig } from '#cloud/server'
+
+/**
+ * Why the `entitlements` command must not write, if it must not: with
+ * `[entitlements] source = "static"` the server never reads the database rows it would change.
+ */
+export function entitlementWriteRefusal(
+ config: Pick<CloudServerConfig, 'staticEntitlements'>,
+ operation: string | undefined,
+ dryRun: boolean
+): string | null {
+ if (!config.staticEntitlements || dryRun) return null
+ if (operation !== 'set' && operation !== 'clear') return null
+ return 'Entitlements come from the static [entitlements] table in the deployment TOML; change them there'
+}
diff --git a/packages/cloud/src/runtime/node/entitlements.ts b/packages/cloud/src/runtime/node/entitlements.ts
new file mode 100644
index 000000000..9bee1a40f
--- /dev/null
+++ b/packages/cloud/src/runtime/node/entitlements.ts
@@ -0,0 +1,41 @@
+import { readFile } from 'node:fs/promises'
+
+import { createWorkspaceEntitlementRepository, parseStaticEntitlementsTOML } from '#cloud/server'
+import { parse as parseTOML } from 'smol-toml'
+
+import { withNodeCloudDatabase } from './command'
+import { entitlementWriteRefusal } from './entitlements-command'
+
+const operation = process.argv[2]
+const workspaceIndex = process.argv.indexOf('--workspace')
+const fileIndex = process.argv.indexOf('--file')
+const dryRun = process.argv.includes('--dry-run')
+const workspaceId = workspaceIndex !== -1 ? process.argv[workspaceIndex + 1] : undefined
+if (!workspaceId) throw new Error('Expected --workspace <uuid>')
+
+await withNodeCloudDatabase(async (database, config) => {
+ const repository = createWorkspaceEntitlementRepository(database)
+ const refusal = entitlementWriteRefusal(config, operation, dryRun)
+ if (refusal) throw new Error(refusal)
+ if (operation === 'get') {
+ console.log(JSON.stringify({ entitlement: await repository.get(workspaceId) }))
+ } else if (operation === 'clear') {
+ if (dryRun) {
+ console.log(JSON.stringify({ dryRun, cleared: false, workspaceId }))
+ return
+ }
+ await repository.clear(workspaceId)
+ console.log(JSON.stringify({ cleared: true, workspaceId }))
+ } else if (operation === 'set') {
+ const file = fileIndex !== -1 ? process.argv[fileIndex + 1] : undefined
+ if (!file) throw new Error('Expected --file <path>')
+ const values = parseStaticEntitlementsTOML(parseTOML(await readFile(file, 'utf8')))
+ if (dryRun) {
+ console.log(JSON.stringify({ dryRun, workspaceId, values }))
+ return
+ }
+ console.log(JSON.stringify({ entitlement: await repository.set(workspaceId, values, 'cli') }))
+ } else {
+ throw new Error('Expected operation: get, set, or clear')
+ }
+})
diff --git a/packages/cloud/src/runtime/node/index.ts b/packages/cloud/src/runtime/node/index.ts
new file mode 100644
index 000000000..748180f86
--- /dev/null
+++ b/packages/cloud/src/runtime/node/index.ts
@@ -0,0 +1,20 @@
+export { createMigratedNodeCloudDatabase } from './bootstrap'
+export { createNodeCloudApplication, type NodeCloudApplicationOptions } from './application'
+export { loadNodeCloudServerConfig } from './config'
+export {
+ createNodeTransactionalEmailRuntime,
+ type NodeTransactionalEmailRuntime
+} from './email-runtime'
+export { createNodeCloudDatabase, type NodeCloudDatabaseOptions } from './database'
+export {
+ createNodemailerInvitationDelivery,
+ createSMTPInvitationDelivery,
+ createNodemailerTransactionalEmailTransport,
+ createSMTPTransactionalEmailTransport,
+ type NodemailerInvitationDeliveryOptions,
+ type SMTPInvitationDeliveryOptions,
+ type NodemailerTransactionalEmailTransportOptions,
+ type SMTPTransactionalEmailTransportOptions
+} from './email'
+export { createS3ObjectStore } from '#cloud/runtime/s3/objects'
+export { startNodeCloudServer, type NodeCloudServerOptions } from './server'
diff --git a/packages/cloud/src/runtime/node/main.ts b/packages/cloud/src/runtime/node/main.ts
new file mode 100644
index 000000000..3a3c76a37
--- /dev/null
+++ b/packages/cloud/src/runtime/node/main.ts
@@ -0,0 +1,11 @@
+import { startNodeCloudServer } from './server'
+
+const cloud = await startNodeCloudServer()
+console.log(`OpenPencil Cloud listening on ${cloud.url}`)
+
+function shutdown() {
+ void cloud.stop().then(() => process.exit(0))
+}
+
+process.on('SIGINT', shutdown)
+process.on('SIGTERM', shutdown)
diff --git a/packages/cloud/src/runtime/node/migrate.ts b/packages/cloud/src/runtime/node/migrate.ts
new file mode 100644
index 000000000..1d8d077e0
--- /dev/null
+++ b/packages/cloud/src/runtime/node/migrate.ts
@@ -0,0 +1,13 @@
+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 })
+try {
+ const auth = createBetterAuthAdapter(config, database)
+ await migrateCloudDatabase(database, { run: auth.migrate, schemaVersion: auth.schemaVersion })
+} finally {
+ await database.destroy()
+}
diff --git a/packages/cloud/src/runtime/node/quota-reconcile.ts b/packages/cloud/src/runtime/node/quota-reconcile.ts
new file mode 100644
index 000000000..0aecbf13e
--- /dev/null
+++ b/packages/cloud/src/runtime/node/quota-reconcile.ts
@@ -0,0 +1,9 @@
+import { createStorageReconciliationService } from '#cloud/server'
+
+import { withNodeCloudDatabase } from './command'
+
+const dryRun = process.argv.includes('--dry-run')
+const results = await withNodeCloudDatabase((database) =>
+ createStorageReconciliationService(database).reconcile({ dryRun })
+)
+console.log(JSON.stringify({ dryRun, results }))
diff --git a/packages/cloud/src/runtime/node/server.ts b/packages/cloud/src/runtime/node/server.ts
new file mode 100644
index 000000000..b28e461a5
--- /dev/null
+++ b/packages/cloud/src/runtime/node/server.ts
@@ -0,0 +1,112 @@
+import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
+import {
+ createCloudApp,
+ createCloudAuthenticationRuntime,
+ createDocumentCleanupService,
+ createRateLimitCleanupService,
+ createUploadCleanupService,
+ startCleanupWorker,
+ startTransactionalEmailWorker,
+ withIndexingPolicy
+} from '#cloud/server'
+import { serve, type ServerType } from '@hono/node-server'
+
+import { createMigratedNodeCloudDatabase } from './bootstrap'
+import { createNodeTransactionalEmailRuntime } from './email-runtime'
+
+export type NodeCloudServerOptions = {
+ environment?: Readonly<Record<string, string | undefined>>
+ port?: number
+}
+
+export async function startNodeCloudServer(options: NodeCloudServerOptions = {}) {
+ const environment = options.environment ?? process.env
+ const { config, database } = await createMigratedNodeCloudDatabase(environment)
+ const objects = createS3ObjectStore(config)
+ const {
+ email,
+ invitationOutbox,
+ transport: emailTransport
+ } = createNodeTransactionalEmailRuntime(config, database)
+ const { auth, enrollment } = createCloudAuthenticationRuntime(config, database, email)
+ const cleanup = config.cleanupEnabled
+ ? startCleanupWorker(
+ {
+ documents: createDocumentCleanupService(database, objects),
+ 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)
+ }
+ )
+ : undefined
+ const app = createCloudApp({
+ config,
+ database,
+ auth,
+ objects,
+ invitationOutbox,
+ transactionalEmail: email,
+ enrollment
+ })
+ const emailWorker = emailTransport
+ ? startTransactionalEmailWorker(email, {
+ batchSize: config.emailBatchSize,
+ intervalMs: config.emailIntervalMs,
+ leaseDurationMs: config.emailLeaseDurationMs,
+ maximumAttempts: config.emailMaximumAttempts,
+ onError: (error) => console.error('[Cloud] Email worker failed:', error)
+ })
+ : undefined
+ const server = await listen(
+ async (request) => {
+ const path = new URL(request.url).pathname
+ return withIndexingPolicy(await app.fetch(request), path, config.indexingPolicy)
+ },
+ options.port ?? Number(environment.PORT ?? 8787),
+ environment.HOST ?? '0.0.0.0'
+ )
+ return {
+ app,
+ database,
+ url: server.url,
+ async stop() {
+ await server.close()
+ await cleanup?.stop()
+ await emailWorker?.stop()
+ await database.destroy()
+ }
+ }
+}
+
+async function listen(
+ fetch: (request: Request) => Promise<Response>,
+ port: number,
+ hostname: string
+) {
+ let server: ServerType | undefined
+ const url = await new Promise<URL>((resolve) => {
+ server = serve({ fetch, hostname, port }, (info) => {
+ resolve(new URL(`http://localhost:${info.port}`))
+ })
+ })
+ return {
+ url,
+ close: () =>
+ new Promise<void>((done, fail) => {
+ if (!server) {
+ done()
+ return
+ }
+ server.close((error) => {
+ if (error) fail(error)
+ else done()
+ })
+ })
+ }
+}
diff --git a/packages/cloud/src/runtime/s3/objects.ts b/packages/cloud/src/runtime/s3/objects.ts
new file mode 100644
index 000000000..8b7c93488
--- /dev/null
+++ b/packages/cloud/src/runtime/s3/objects.ts
@@ -0,0 +1,244 @@
+import type { CloudServerConfig } from '#cloud/server'
+import type { ObjectStore } from '#cloud/server/objects'
+import {
+ AbortMultipartUploadCommand,
+ CompleteMultipartUploadCommand,
+ CreateMultipartUploadCommand,
+ DeleteObjectCommand,
+ GetObjectCommand,
+ HeadObjectCommand,
+ PutObjectCommand,
+ S3Client,
+ UploadPartCommand
+} from '@aws-sdk/client-s3'
+// eslint-disable-next-line open-pencil/no-mixed-case-acronym-identifiers -- Upstream export spelling.
+import { getSignedUrl as getSignedURL } from '@aws-sdk/s3-request-presigner'
+
+const CHECKSUM_METADATA_KEY = 'openpencil-sha256'
+const READINESS_BODY = new TextEncoder().encode('openpencil-ready')
+const READINESS_CHECKSUM = 'Hq6g3mmWpyBNobXoWZIz/d0/d8KLjJyEKqNnJh6KXjA='
+const MULTIPART_THRESHOLD = 32 * 1024 * 1024
+const MULTIPART_PART_SIZE = 16 * 1024 * 1024
+const MAX_MULTIPART_PARTS = 10_000
+
+type S3ErrorMetadata = {
+ $metadata?: {
+ httpStatusCode?: number
+ }
+}
+
+function isNotFoundError(error: unknown): boolean {
+ return (
+ typeof error === 'object' &&
+ error !== null &&
+ '$metadata' in error &&
+ (error as S3ErrorMetadata).$metadata?.httpStatusCode === 404
+ )
+}
+
+function encryption(config: CloudServerConfig) {
+ return config.s3ServerSideEncryption
+ ? {
+ ServerSideEncryption: config.s3ServerSideEncryption,
+ ...(config.s3KmsKeyId ? { SSEKMSKeyId: config.s3KmsKeyId } : {})
+ }
+ : {}
+}
+
+export function createS3ObjectStore(config: CloudServerConfig): ObjectStore {
+ const client = new S3Client({
+ endpoint: config.s3Endpoint,
+ region: config.s3Region,
+ forcePathStyle: config.s3ForcePathStyle,
+ requestChecksumCalculation: 'WHEN_REQUIRED',
+ responseChecksumValidation: 'WHEN_REQUIRED',
+ credentials: {
+ accessKeyId: config.s3AccessKeyId,
+ secretAccessKey: config.s3SecretAccessKey,
+ ...(config.s3SessionToken ? { sessionToken: config.s3SessionToken } : {})
+ }
+ })
+ const nativeSHA256 = config.s3ChecksumVerification === 'native'
+
+ async function headObject(key: string) {
+ return client.send(
+ new HeadObjectCommand({
+ Bucket: config.s3Bucket,
+ Key: key,
+ ...(nativeSHA256 ? { ChecksumMode: 'ENABLED' as const } : {})
+ })
+ )
+ }
+
+ return {
+ capabilities: {
+ nativeSHA256,
+ multipartUpload: true,
+ conditionalWrites: false
+ },
+
+ async checkReadiness() {
+ const key = `.openpencil/readiness/${crypto.randomUUID()}`
+ try {
+ await client.send(
+ new PutObjectCommand({
+ Bucket: config.s3Bucket,
+ Key: key,
+ Body: READINESS_BODY,
+ ContentType: 'application/octet-stream',
+ ChecksumSHA256: nativeSHA256 ? READINESS_CHECKSUM : undefined,
+ Metadata: { [CHECKSUM_METADATA_KEY]: READINESS_CHECKSUM },
+ ...encryption(config)
+ })
+ )
+ const object = await headObject(key)
+ const checksum = nativeSHA256
+ ? object.ChecksumSHA256
+ : object.Metadata?.[CHECKSUM_METADATA_KEY]
+ return {
+ ok: object.ContentLength === READINESS_BODY.byteLength && checksum === READINESS_CHECKSUM,
+ checksumVerification: nativeSHA256 ? 'native' : 'metadata'
+ }
+ } finally {
+ await client.send(new DeleteObjectCommand({ Bucket: config.s3Bucket, Key: key }))
+ }
+ },
+
+ async createDownload(input) {
+ const expiresIn = Math.max(1, Math.floor((input.expiresAt.getTime() - Date.now()) / 1000))
+ const url = await getSignedURL(
+ client,
+ new GetObjectCommand({ Bucket: config.s3Bucket, Key: input.key }),
+ { expiresIn }
+ )
+ return {
+ url,
+ method: 'GET',
+ headers: {},
+ expiresAt: input.expiresAt.toISOString()
+ }
+ },
+
+ async createUpload(input) {
+ if (input.byteSize > MULTIPART_THRESHOLD) {
+ const created = await client.send(
+ new CreateMultipartUploadCommand({
+ Bucket: config.s3Bucket,
+ Key: input.key,
+ ContentType: input.contentType,
+ Metadata: { [CHECKSUM_METADATA_KEY]: input.checksum },
+ ...encryption(config)
+ })
+ )
+ if (!created.UploadId) throw new Error('S3 did not return a multipart upload ID')
+ const partCount = Math.ceil(input.byteSize / MULTIPART_PART_SIZE)
+ if (partCount > MAX_MULTIPART_PARTS) throw new Error('Object requires too many S3 parts')
+ const expiresIn = Math.max(1, Math.floor((input.expiresAt.getTime() - Date.now()) / 1000))
+ const parts = await Promise.all(
+ Array.from({ length: partCount }, async (_, index) => {
+ const partNumber = index + 1
+ return {
+ partNumber,
+ url: await getSignedURL(
+ client,
+ new UploadPartCommand({
+ Bucket: config.s3Bucket,
+ Key: input.key,
+ UploadId: created.UploadId,
+ PartNumber: partNumber
+ }),
+ { expiresIn }
+ ),
+ method: 'PUT' as const,
+ headers: {}
+ }
+ })
+ )
+ return {
+ kind: 'multipart',
+ uploadId: created.UploadId,
+ partSize: MULTIPART_PART_SIZE,
+ parts,
+ expiresAt: input.expiresAt.toISOString()
+ }
+ }
+ const expiresIn = Math.max(1, Math.floor((input.expiresAt.getTime() - Date.now()) / 1000))
+ const command = new PutObjectCommand({
+ Bucket: config.s3Bucket,
+ Key: input.key,
+ ContentType: input.contentType,
+ ChecksumSHA256: nativeSHA256 ? input.checksum : undefined,
+ Metadata: { [CHECKSUM_METADATA_KEY]: input.checksum },
+ ...encryption(config)
+ })
+ const url = await getSignedURL(client, command, {
+ expiresIn,
+ unhoistableHeaders: new Set([
+ ...(nativeSHA256 ? ['x-amz-checksum-sha256'] : []),
+ `x-amz-meta-${CHECKSUM_METADATA_KEY}`
+ ])
+ })
+ return {
+ kind: 'single',
+ url,
+ method: 'PUT',
+ headers: {
+ 'Content-Type': input.contentType,
+ ...(nativeSHA256 ? { 'x-amz-checksum-sha256': input.checksum } : {}),
+ [`x-amz-meta-${CHECKSUM_METADATA_KEY}`]: input.checksum
+ },
+ expiresAt: input.expiresAt.toISOString()
+ }
+ },
+
+ async completeUpload(input) {
+ await client.send(
+ new CompleteMultipartUploadCommand({
+ Bucket: config.s3Bucket,
+ Key: input.key,
+ UploadId: input.uploadId,
+ MultipartUpload: {
+ Parts: input.parts.map((part) => ({ ETag: part.etag, PartNumber: part.partNumber }))
+ }
+ })
+ )
+ },
+
+ async abortUpload(input) {
+ try {
+ await client.send(
+ new AbortMultipartUploadCommand({
+ Bucket: config.s3Bucket,
+ Key: input.key,
+ UploadId: input.uploadId
+ })
+ )
+ } catch (error) {
+ if (!isNotFoundError(error)) throw error
+ }
+ },
+
+ async head(key) {
+ try {
+ const object = await headObject(key)
+ const checksum = nativeSHA256
+ ? object.ChecksumSHA256
+ : object.Metadata?.[CHECKSUM_METADATA_KEY]
+ if (object.ContentLength == null || !checksum || !object.ContentType) return null
+ return {
+ byteSize: object.ContentLength,
+ checksum,
+ checksumVerification: nativeSHA256 ? 'native' : 'metadata',
+ contentType: object.ContentType
+ }
+ } catch (error) {
+ if (isNotFoundError(error)) return null
+ throw error
+ }
+ },
+
+ async delete(key) {
+ await client.send(new DeleteObjectCommand({ Bucket: config.s3Bucket, Key: key }))
+ }
+ }
+}
diff --git a/packages/cloud/src/server/account/actions.ts b/packages/cloud/src/server/account/actions.ts
new file mode 100644
index 000000000..20719d084
--- /dev/null
+++ b/packages/cloud/src/server/account/actions.ts
@@ -0,0 +1,63 @@
+import type { AccountSecurityErrorCode } from '#cloud/contract'
+import type { CloudIdentityResolver, CloudSessionResolver } from '#cloud/server/auth'
+import { APIError } from 'better-auth'
+import type { Context } from 'hono'
+
+const ACCOUNT_SECURITY_ERROR_CODES: Record<string, AccountSecurityErrorCode> = {
+ INVALID_PASSWORD: 'current_password_invalid',
+ PASSWORD_TOO_SHORT: 'password_too_short',
+ PASSWORD_TOO_LONG: 'password_too_long',
+ FAILED_TO_UNLINK_LAST_ACCOUNT: 'last_authentication_method',
+ SESSION_NOT_FRESH: 'session_not_fresh'
+}
+
+async function accountAction<Value>(operation: () => Promise<Value>, context: Context) {
+ try {
+ return await operation()
+ } catch (error) {
+ if (!(error instanceof APIError)) throw error
+ return context.json(
+ {
+ error: {
+ code:
+ ACCOUNT_SECURITY_ERROR_CODES[error.body?.code ?? ''] ?? 'authentication_method_failed'
+ }
+ },
+ error.statusCode as 400 | 401 | 403 | 404 | 409 | 422 | 429 | 500
+ )
+ }
+}
+
+function completedMFAResponse(result: Response | undefined, context: Context): Response {
+ if (!(result instanceof Response)) return context.json({ ok: true as const })
+ if (!result.ok) return result
+ const headers = new Headers(result.headers)
+ headers.set('Content-Type', 'application/json')
+ return new Response(JSON.stringify({ ok: true }), { status: 200, headers })
+}
+
+export function createAccountActions(resolveSession: CloudSessionResolver) {
+ return {
+ accountAction,
+ activeAccountAction: async <Value>(
+ context: Context,
+ operation: () => Promise<Value>
+ ): Promise<Value | Response> => {
+ if (!(await resolveSession(context.req.raw))) {
+ return context.json({ error: { code: 'unauthorized' as const } }, 401)
+ }
+ return accountAction(operation, context)
+ },
+ verifiedMFAAction: async (
+ context: Context,
+ identityResolver: CloudIdentityResolver,
+ verify: () => Promise<Response | undefined>
+ ): Promise<Response> => {
+ if (!(await identityResolver(context.req.raw))) {
+ return context.json({ error: { code: 'unauthorized' as const } }, 401)
+ }
+ const result = await accountAction(verify, context)
+ return completedMFAResponse(result instanceof Response ? result : undefined, context)
+ }
+ }
+}
diff --git a/packages/cloud/src/server/account/routes.ts b/packages/cloud/src/server/account/routes.ts
new file mode 100644
index 000000000..92fb2c310
--- /dev/null
+++ b/packages/cloud/src/server/account/routes.ts
@@ -0,0 +1,198 @@
+import type { EnrollmentService } from '#cloud/admin'
+import {
+ parseCloudPasswordChange,
+ parseCloudMFAEnable,
+ parseCloudMFAVerify,
+ parseCloudPasskeyDelete,
+ parseCloudSocialLink,
+ parseCloudUnlinkAuthenticationMethod
+} from '#cloud/contract'
+import type { CloudAPIEnvironment } from '#cloud/server/api'
+import {
+ createAccountAuthenticationService,
+ type CloudAuthAdapter,
+ type CloudIdentityResolver,
+ type CloudSessionResolver
+} from '#cloud/server/auth'
+import type { CloudServerConfig } from '#cloud/server/config'
+import { validatedJSON } from '#cloud/server/validation'
+import type { WorkspaceService } from '#cloud/server/workspaces'
+import { Hono, type MiddlewareHandler } from 'hono'
+
+import { createAccountActions } from './actions'
+
+export type AccountRouteDependencies = {
+ auth: CloudAuthAdapter
+ config: CloudServerConfig
+ enrollment: EnrollmentService
+ workspaces: WorkspaceService
+ resolveIdentity: CloudIdentityResolver
+ resolveSession: CloudSessionResolver
+ requireActiveSession: MiddlewareHandler<CloudAPIEnvironment>
+ authenticatedMutationLimiter: MiddlewareHandler<CloudAPIEnvironment>
+}
+
+export function createAccountRoutes(services: AccountRouteDependencies) {
+ const {
+ enrollment,
+ workspaces,
+ resolveIdentity,
+ resolveSession,
+ requireActiveSession,
+ authenticatedMutationLimiter
+ } = services
+ const accountAuthentication = createAccountAuthenticationService(services.auth, services.config)
+ const { accountAction, activeAccountAction, verifiedMFAAction } =
+ createAccountActions(resolveSession)
+ return new Hono<CloudAPIEnvironment>()
+ .get('/api/account/status', async (context) => {
+ const identity = await resolveIdentity(context.req.raw)
+ if (!identity) return context.json({ error: { code: 'unauthorized' as const } }, 401)
+ let enrollmentStatus = await enrollment.statusForEmail(identity.email)
+ if (services.config.enrollmentMode === 'approval' && !enrollmentStatus) {
+ await enrollment.request({ email: identity.email, name: identity.name })
+ enrollmentStatus = 'pending'
+ }
+ const state =
+ services.config.enrollmentMode !== 'approval' || enrollmentStatus === 'approved'
+ ? ('active' as const)
+ : (enrollmentStatus ?? 'pending')
+ if (state === 'active') await workspaces.ensurePersonal(identity)
+ return context.json({ user: identity, state })
+ })
+ .get('/api/account/mfa', async (context) => {
+ const actor = await resolveSession(context.req.raw)
+ if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)
+ const mfa = await services.auth.mfaStatus(context.req.raw.headers)
+ return mfa
+ ? context.json({ mfa })
+ : context.json({ error: { code: 'unauthorized' as const } }, 401)
+ })
+ .post('/api/account/mfa/totp/enable', validatedJSON(parseCloudMFAEnable), async (context) => {
+ const result = await activeAccountAction(context, () =>
+ services.auth.enableTOTP(context.req.raw.headers, context.req.valid('json').password)
+ )
+ return result instanceof Response ? result : context.json(result)
+ })
+ .post('/api/account/mfa/totp/verify', validatedJSON(parseCloudMFAVerify), (context) =>
+ verifiedMFAAction(context, resolveSession, () =>
+ services.auth.verifyTOTP(context.req.raw.headers, context.req.valid('json').code)
+ )
+ )
+ .post('/api/account/mfa/recovery/verify', validatedJSON(parseCloudMFAVerify), (context) =>
+ verifiedMFAAction(context, resolveIdentity, () =>
+ services.auth.verifyRecoveryCode(context.req.raw.headers, context.req.valid('json').code)
+ )
+ )
+ .post(
+ '/api/account/mfa/recovery/regenerate',
+ validatedJSON(parseCloudMFAEnable),
+ async (context) => {
+ const result = await activeAccountAction(context, () =>
+ services.auth.generateRecoveryCodes(
+ context.req.raw.headers,
+ context.req.valid('json').password
+ )
+ )
+ return result instanceof Response ? result : context.json({ backupCodes: result })
+ }
+ )
+ .post('/api/account/mfa/totp/disable', validatedJSON(parseCloudMFAEnable), async (context) => {
+ const actor = await resolveSession(context.req.raw)
+ if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)
+ if (actor.deploymentRole === 'admin' && services.config.deploymentAdminMFARequired) {
+ const passkeys = await services.auth.listPasskeys(context.req.raw.headers)
+ if (passkeys.length === 0) {
+ return context.json({ error: { code: 'mfa_required' as const } }, 403)
+ }
+ }
+ const result = await accountAction(
+ () =>
+ services.auth.disableTOTP(context.req.raw.headers, context.req.valid('json').password),
+ context
+ )
+ return result instanceof Response ? result : context.json({ ok: true as const })
+ })
+ .get('/api/account/mfa/passkeys', async (context) => {
+ const actor = await resolveSession(context.req.raw)
+ if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)
+ return context.json({ passkeys: await services.auth.listPasskeys(context.req.raw.headers) })
+ })
+ .post(
+ '/api/account/mfa/passkeys/delete',
+ validatedJSON(parseCloudPasskeyDelete),
+ async (context) => {
+ const actor = await resolveSession(context.req.raw)
+ if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)
+ const { id } = context.req.valid('json')
+ if (actor.deploymentRole === 'admin' && services.config.deploymentAdminMFARequired) {
+ // An administrator keeps at least one second factor: TOTP or another passkey.
+ const status = await services.auth.mfaStatus(context.req.raw.headers)
+ const passkeys = await services.auth.listPasskeys(context.req.raw.headers)
+ const otherPasskeys = passkeys.filter((passkey) => passkey.id !== id)
+ if (!status?.totpEnabled && otherPasskeys.length === 0) {
+ return context.json({ error: { code: 'mfa_required' as const } }, 403)
+ }
+ }
+ const result = await accountAction(
+ () => services.auth.deletePasskey(context.req.raw.headers, id),
+ context
+ )
+ return result instanceof Response ? result : context.json({ ok: true as const })
+ }
+ )
+ .use('/api/account/authentication/*', requireActiveSession)
+ .use('/api/account/authentication/*', authenticatedMutationLimiter)
+ .post(
+ '/api/account/authentication/change-password',
+ validatedJSON(parseCloudPasswordChange),
+ async (context) => {
+ const result = await accountAction(
+ () =>
+ accountAuthentication.changePassword(
+ context.req.raw.headers,
+ context.req.valid('json')
+ ),
+ context
+ )
+ return result instanceof Response ? result : context.json({ ok: true as const })
+ }
+ )
+ .post(
+ '/api/account/authentication/link-social',
+ validatedJSON(parseCloudSocialLink),
+ async (context) => {
+ const result = await accountAction(
+ () =>
+ accountAuthentication.startSocialLink(
+ context.req.raw.headers,
+ context.req.valid('json')
+ ),
+ context
+ )
+ return result instanceof Response ? result : context.json({ url: result })
+ }
+ )
+ .post(
+ '/api/account/authentication/unlink',
+ validatedJSON(parseCloudUnlinkAuthenticationMethod),
+ async (context) => {
+ const result = await accountAction(
+ () =>
+ accountAuthentication.unlink(
+ context.req.raw.headers,
+ context.req.valid('json').methodId
+ ),
+ context
+ )
+ return result instanceof Response ? result : context.json({ ok: true as const })
+ }
+ )
+ .get('/api/account/authentication', async (context) => {
+ const result = await accountAction(
+ () => accountAuthentication.methods(context.req.raw.headers),
+ context
+ )
+ return result instanceof Response ? result : context.json(result)
+ })
+}
diff --git a/packages/cloud/src/server/api/index.ts b/packages/cloud/src/server/api/index.ts
new file mode 100644
index 000000000..8d8b3684b
--- /dev/null
+++ b/packages/cloud/src/server/api/index.ts
@@ -0,0 +1,8 @@
+export {
+ createCloudAPIRouter,
+ createPublicCloudAPIRouter,
+ type CloudAPI,
+ type CloudAPIServices,
+ type PublicCloudAPI
+} from './router'
+export type { CloudAPIEnvironment } from './types'
diff --git a/packages/cloud/src/server/api/router.ts b/packages/cloud/src/server/api/router.ts
new file mode 100644
index 000000000..41c4098ec
--- /dev/null
+++ b/packages/cloud/src/server/api/router.ts
@@ -0,0 +1,96 @@
+import type { CloudAPIEnvironment } from '#cloud/server/api/types'
+import type { CloudSessionResolver } from '#cloud/server/auth'
+import type { CollaborationTicketService } from '#cloud/server/collaboration'
+import {
+ createCollaborationRoutes,
+ createPublicCollaborationRoutes
+} from '#cloud/server/collaboration'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { DocumentService } from '#cloud/server/documents'
+import { createDocumentRoutes } from '#cloud/server/documents'
+import type { EntitlementService } from '#cloud/server/policy'
+import type { DocumentSharingService } from '#cloud/server/sharing'
+import {
+ createDocumentSharingRoutes,
+ createPublicDocumentRoutes,
+ createPublicSharingRoutes
+} from '#cloud/server/sharing'
+import type { WorkspaceMemberService, WorkspaceService } from '#cloud/server/workspaces'
+import { createWorkspaceRoutes } from '#cloud/server/workspaces'
+import { Hono } from 'hono'
+import type { Kysely } from 'kysely'
+
+export type CloudAPIServices = {
+ database?: Kysely<CloudDatabase>
+ rateLimitSecret?: string
+ collaboration: CollaborationTicketService
+ documents: DocumentService
+ sharing: DocumentSharingService
+ resolveSession?: CloudSessionResolver
+ entitlements?: EntitlementService
+ workspaces: WorkspaceService
+ workspaceMembers: WorkspaceMemberService
+}
+
+export function createPublicCloudAPIRouter(services: CloudAPIServices) {
+ return new Hono<CloudAPIEnvironment>()
+ .route('/', createPublicSharingRoutes(services.sharing))
+ .route('/', createPublicDocumentRoutes(services.sharing, services.documents))
+ .route('/', createPublicCollaborationRoutes(services.collaboration, services.resolveSession))
+}
+
+export function createCloudAPIRouter(services: CloudAPIServices) {
+ return new Hono<CloudAPIEnvironment>()
+ .route('/public', createPublicCloudAPIRouter(services))
+ .get('/workspaces/:workspaceId/entitlements', async (context) => {
+ if (!services.entitlements)
+ return context.json({ error: { code: 'not_found' as const } }, 404)
+ return context.json({
+ entitlements: await services.entitlements.workspace(
+ context.get('actor').userId,
+ context.req.param('workspaceId')
+ )
+ })
+ })
+ .get('/session', (context) => context.json({ user: context.get('actor') }))
+ .route(
+ '/',
+ createCollaborationRoutes(
+ services.collaboration,
+ services.database && services.rateLimitSecret
+ ? { database: services.database, secret: services.rateLimitSecret }
+ : undefined
+ )
+ )
+ .route(
+ '/',
+ createDocumentRoutes(
+ services.documents,
+ services.database && services.rateLimitSecret
+ ? { database: services.database, secret: services.rateLimitSecret }
+ : undefined
+ )
+ )
+ .route(
+ '/',
+ createDocumentSharingRoutes(
+ services.sharing,
+ services.database && services.rateLimitSecret
+ ? { database: services.database, secret: services.rateLimitSecret }
+ : undefined
+ )
+ )
+ .route(
+ '/workspaces',
+ createWorkspaceRoutes(
+ services.workspaces,
+ services.workspaceMembers,
+ services.database && services.rateLimitSecret
+ ? { database: services.database, secret: services.rateLimitSecret }
+ : undefined
+ )
+ )
+}
+
+export type CloudAPI = ReturnType<typeof createCloudAPIRouter>
+export type PublicCloudAPI = ReturnType<typeof createPublicCloudAPIRouter>
diff --git a/packages/cloud/src/server/api/types.ts b/packages/cloud/src/server/api/types.ts
new file mode 100644
index 000000000..e731c38af
--- /dev/null
+++ b/packages/cloud/src/server/api/types.ts
@@ -0,0 +1,7 @@
+import type { CloudActor } from '#cloud/server/auth'
+
+export type CloudAPIEnvironment = {
+ Variables: {
+ actor: CloudActor
+ }
+}
diff --git a/packages/cloud/src/server/app.ts b/packages/cloud/src/server/app.ts
new file mode 100644
index 000000000..ff5fe7a70
--- /dev/null
+++ b/packages/cloud/src/server/app.ts
@@ -0,0 +1,359 @@
+import {
+ createAdminAuditService,
+ createAdminEmailService,
+ createAdminOperationsService,
+ createAdminUserService,
+ createCloudAdminRoutes,
+ createEnrollmentService,
+ type EnrollmentService
+} from '#cloud/admin'
+import { CLOUD_DISCOVERY_PATH, CLOUD_PROTOCOL_VERSION, type CloudDiscovery } from '#cloud/contract'
+import { createAccountRoutes } from '#cloud/server/account/routes'
+import {
+ createCloudAPIRouter,
+ createPublicCloudAPIRouter,
+ type CloudAPIEnvironment
+} from '#cloud/server/api'
+import {
+ createCloudIdentityResolver,
+ createCloudSessionResolver,
+ type CloudAuthAdapter,
+ type CloudIdentityResolver,
+ type CloudSessionResolver
+} from '#cloud/server/auth'
+import { createCollaborationTicketService } from '#cloud/server/collaboration'
+import { cloudDiscoveryFromConfig, type CloudServerConfig } from '#cloud/server/config'
+import type { CloudDatabase } from '#cloud/server/db'
+import { createDocumentService } from '#cloud/server/documents'
+import type { TransactionalEmailService } from '#cloud/server/email'
+import type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'
+import type { ObjectStore } from '#cloud/server/objects'
+import {
+ createDefaultCloudPolicy,
+ createEntitlementService,
+ DatabaseEntitlementSource,
+ EntitlementOpenFeatureProvider,
+ StaticEntitlementSource,
+ staticEntitlementValues,
+ type CloudPolicy,
+ type EntitlementSource
+} from '#cloud/server/policy'
+import {
+ CLOUD_RATE_LIMITS,
+ createActorRateLimiter,
+ createTrustedIPRateLimiter
+} from '#cloud/server/rate-limit'
+import { createDocumentSharingService } from '#cloud/server/sharing'
+import { createWorkspaceMemberService, createWorkspaceService } from '#cloud/server/workspaces'
+import { Hono, type Context } from 'hono'
+import { cors } from 'hono/cors'
+import type { Kysely } from 'kysely'
+
+export type CloudServices = {
+ config: CloudServerConfig
+ database: Kysely<CloudDatabase>
+ auth: CloudAuthAdapter
+ objects: ObjectStore
+ resolveIdentity?: CloudIdentityResolver
+ resolveSession?: CloudSessionResolver
+ invitationDelivery?: InvitationDelivery
+ invitationOutbox?: InvitationOutbox
+ transactionalEmail?: TransactionalEmailService
+ enrollment?: EnrollmentService
+ entitlementSource?: EntitlementSource
+ policy?: CloudPolicy
+}
+
+type CloudEnvironment = CloudAPIEnvironment
+
+function discoveryFromServices(services: CloudServices): CloudDiscovery {
+ return cloudDiscoveryFromConfig(services.config)
+}
+
+const POLICY_MANAGED_AUTH_PATHS = new Set([
+ '/api/auth/passkey/delete-passkey',
+ '/api/auth/two-factor/disable'
+])
+
+const ACTIVE_ACCOUNT_AUTH_PATHS = new Set([
+ '/api/auth/passkey/delete-passkey',
+ '/api/auth/passkey/generate-register-options',
+ '/api/auth/passkey/list-user-passkeys',
+ '/api/auth/passkey/update-passkey',
+ '/api/auth/passkey/verify-registration',
+ '/api/auth/two-factor/disable',
+ '/api/auth/two-factor/enable',
+ '/api/auth/two-factor/generate-backup-codes',
+ '/api/auth/two-factor/get-totp-uri',
+ '/api/auth/account-info',
+ '/api/auth/change-email',
+ '/api/auth/change-password',
+ '/api/auth/delete-user',
+ '/api/auth/get-access-token',
+ '/api/auth/link-social',
+ '/api/auth/list-accounts',
+ '/api/auth/list-sessions',
+ '/api/auth/refresh-token',
+ '/api/auth/revoke-other-sessions',
+ '/api/auth/revoke-session',
+ '/api/auth/revoke-sessions',
+ '/api/auth/unlink-account'
+])
+
+export function shouldPreventIndexing(path: string, policy: 'allow' | 'deny'): boolean {
+ return (
+ policy === 'deny' ||
+ path.startsWith('/api/') ||
+ path.startsWith('/admin') ||
+ path.startsWith('/auth') ||
+ path.startsWith('/account') ||
+ path === '/app' ||
+ path === '/sign-in' ||
+ path === '/sign-up' ||
+ path === '/join' ||
+ path === CLOUD_DISCOVERY_PATH
+ )
+}
+
+export function withIndexingPolicy(
+ response: Response,
+ path: string,
+ policy: 'allow' | 'deny'
+): Response {
+ if (!shouldPreventIndexing(path, policy)) return response
+ const headers = new Headers(response.headers)
+ headers.set('X-Robots-Tag', 'noindex, nofollow, noarchive')
+ return new Response(response.body, {
+ status: response.status,
+ statusText: response.statusText,
+ headers
+ })
+}
+
+export function createCloudApp(services: CloudServices) {
+ const discovery = discoveryFromServices(services)
+ const resolveIdentity = services.resolveIdentity ?? createCloudIdentityResolver(services.auth)
+ const resolveSession = services.resolveSession ?? createCloudSessionResolver(services.auth)
+ const allowedOrigins = new Set(
+ [services.config.publicURL, ...services.config.trustedOrigins].map(
+ (origin) => new URL(origin).origin
+ )
+ )
+ const cloudCORS = cors({
+ origin: (origin) => (allowedOrigins.has(origin) ? origin : null),
+ allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
+ allowHeaders: ['Content-Type', 'Authorization'],
+ credentials: true,
+ maxAge: 600
+ })
+ const workspaces = createWorkspaceService(services.database)
+ const workspaceMembers = createWorkspaceMemberService(services.database, {
+ email: services.transactionalEmail,
+ publicURL: services.config.publicURL,
+ appURL: services.config.appURL ?? services.config.publicURL
+ })
+ const enrollment =
+ services.enrollment ??
+ createEnrollmentService(services.database, {
+ appURL: services.config.appURL ?? services.config.publicURL,
+ adminRecipients: services.config.enrollmentAdminNotificationEmails,
+ email: services.transactionalEmail
+ })
+ const admin = createCloudAdminRoutes(
+ {
+ email: createAdminEmailService(
+ services.database,
+ services.transactionalEmail,
+ services.config.appURL ?? services.config.publicURL
+ ),
+ enrollment,
+ users: createAdminUserService(services.database, services.auth, {
+ requireMFA: services.config.deploymentAdminMFARequired
+ }),
+ audit: createAdminAuditService(services.database),
+ operations: createAdminOperationsService(services.database, services.config)
+ },
+ allowedOrigins,
+ {
+ database: services.database,
+ secret: services.config.authSecret,
+ auth: services.auth,
+ 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))
+ const documents = createDocumentService(services.database, services.objects, {
+ policy,
+ technicalMaximumUploadBytes: services.config.technicalLimits.maximumUploadBytes
+ })
+ const entitlements = createEntitlementService(
+ services.database,
+ policy,
+ services.config.technicalLimits.maximumUploadBytes,
+ services.config.technicalLimits.maximumConnectionsPerRoom
+ )
+ const sharing = createDocumentSharingService(services.database, {
+ delivery: services.invitationDelivery,
+ outbox: services.invitationOutbox,
+ continuationSecret: services.config.authSecret,
+ publicURL: services.config.publicURL,
+ appURL: services.config.appURL ?? services.config.publicURL,
+ policy,
+ deploymentMode: services.config.deployment,
+ workspaceInvitations: workspaceMembers
+ })
+ const collaboration = createCollaborationTicketService({
+ database: services.database,
+ sharing,
+ authSecret: services.config.authSecret,
+ collaborationURL: services.config.collaborationURL,
+ policy,
+ deploymentMode: services.config.deployment
+ })
+
+ const requireActiveSession = async (context: Context, next: () => Promise<void>) => {
+ const actor = await resolveSession(context.req.raw)
+ if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)
+ context.set('actor', actor)
+ return next()
+ }
+ const publicRateLimiter = createTrustedIPRateLimiter(
+ services.database,
+ services.config.authSecret,
+ CLOUD_RATE_LIMITS.publicCapability,
+ { trustedHeaders: services.config.authTrustedIPHeaders },
+ (context) => context.json({ error: { code: 'not_found' as const } }, 404),
+ {
+ resource: (context) => context.req.path,
+ // Guests refresh collaboration tickets on their own budget, `publicCollaborationLimiter`.
+ skip: (context) => context.req.path.endsWith('/collaboration-ticket')
+ }
+ )
+ const publicCollaborationLimiter = createTrustedIPRateLimiter(
+ services.database,
+ services.config.authSecret,
+ CLOUD_RATE_LIMITS.collaborationTicket,
+ { trustedHeaders: services.config.authTrustedIPHeaders },
+ (context) => context.json({ error: { code: 'not_found' as const } }, 404),
+ { resource: (context) => context.req.path }
+ )
+ const authenticatedMutationLimiter = createActorRateLimiter(
+ services.database,
+ services.config.authSecret,
+ CLOUD_RATE_LIMITS.authenticatedMutation,
+ (context) =>
+ context.req.method === 'GET' ||
+ context.req.path.endsWith('/collaboration-ticket') ||
+ context.req.path.endsWith('/invitations') ||
+ context.req.path.endsWith('/uploads') ||
+ /^\/api\/workspaces(?:\/[^/]+\/documents)?$/.test(context.req.path)
+ )
+
+ const accountRoutes = createAccountRoutes({
+ auth: services.auth,
+ config: services.config,
+ enrollment,
+ workspaces,
+ resolveIdentity,
+ resolveSession,
+ requireActiveSession,
+ authenticatedMutationLimiter
+ })
+ const cloudAPI = createCloudAPIRouter({
+ collaboration,
+ database: services.database,
+ rateLimitSecret: services.config.authSecret,
+ documents,
+ entitlements,
+ sharing,
+ workspaces,
+ workspaceMembers,
+ resolveSession
+ })
+ const publicCloudAPI = createPublicCloudAPIRouter({
+ collaboration,
+ documents,
+ entitlements,
+ sharing,
+ workspaces,
+ workspaceMembers,
+ resolveSession
+ })
+
+ return new Hono<CloudEnvironment>()
+ .use(CLOUD_DISCOVERY_PATH, cloudCORS)
+ .use('/api/*', cloudCORS)
+ .use('*', async (context, next) => {
+ await next()
+ if (shouldPreventIndexing(context.req.path, services.config.indexingPolicy)) {
+ context.header('X-Robots-Tag', 'noindex, nofollow, noarchive')
+ }
+ })
+ .get('/robots.txt', (context) => {
+ context.header('Content-Type', 'text/plain; charset=utf-8')
+ return context.body(
+ services.config.indexingPolicy === 'deny'
+ ? 'User-agent: *\nDisallow: /\n'
+ : 'User-agent: *\nDisallow: /admin\nDisallow: /account\nDisallow: /app\nDisallow: /api\nDisallow: /auth\nDisallow: /sign-in\nDisallow: /sign-up\nDisallow: /join\nDisallow: /.well-known\n'
+ )
+ })
+ .get('/health', (context) =>
+ context.json({
+ status: 'ok' as const,
+ protocolVersion: CLOUD_PROTOCOL_VERSION
+ })
+ )
+ .get('/ready', async (context) => {
+ try {
+ await services.database.selectFrom('workspace').select('id').limit(1).execute()
+ const objects = await services.objects.checkReadiness()
+ if (!objects.ok) {
+ return context.json(
+ { status: 'unavailable' as const, dependency: 'object_storage' as const },
+ 503
+ )
+ }
+ return context.json({
+ status: 'ready' as const,
+ objectStorage: {
+ checksumVerification: objects.checksumVerification,
+ multipartUpload: services.objects.capabilities.multipartUpload
+ }
+ })
+ } catch {
+ return context.json({ status: 'unavailable' as const }, 503)
+ }
+ })
+ .get(CLOUD_DISCOVERY_PATH, (context) => context.json(discovery))
+ .on(['GET', 'POST'], '/api/auth/*', async (context) => {
+ if (POLICY_MANAGED_AUTH_PATHS.has(context.req.path)) {
+ return context.json({ error: { code: 'forbidden' as const } }, 403)
+ }
+ if (
+ ACTIVE_ACCOUNT_AUTH_PATHS.has(context.req.path) &&
+ !(await resolveSession(context.req.raw))
+ ) {
+ return context.json({ error: { code: 'unauthorized' as const } }, 401)
+ }
+ return services.auth.handler(context.req.raw)
+ })
+ .route('/', accountRoutes)
+ .use('/api/shares/:shareId/collaboration-ticket', publicCollaborationLimiter)
+ .use('/api/public/*', publicRateLimiter)
+ .use('/api/shares/*', publicRateLimiter)
+ .use('/api/invitations/*', publicRateLimiter)
+ .route('/api', publicCloudAPI)
+ .use('/api/*', requireActiveSession)
+ .route('/api/admin', admin)
+ .use('/api/*', authenticatedMutationLimiter)
+ .route('/api', cloudAPI)
+}
+
+export type CloudApp = ReturnType<typeof createCloudApp>
diff --git a/packages/cloud/src/server/auth/account.ts b/packages/cloud/src/server/auth/account.ts
new file mode 100644
index 000000000..8fffd7843
--- /dev/null
+++ b/packages/cloud/src/server/auth/account.ts
@@ -0,0 +1,62 @@
+import type {
+ CloudAuthenticationMethod,
+ CloudAuthenticationProvider
+} from '#cloud/contract/account'
+import { configuredSocialProviders, type CloudServerConfig } from '#cloud/server/config'
+
+import type { CloudAuthAdapter } from './adapter'
+
+const supportedProvider = (provider: string): provider is CloudAuthenticationProvider =>
+ provider === 'credential' || provider === 'google' || provider === 'apple'
+
+export function createAccountAuthenticationService(
+ auth: CloudAuthAdapter,
+ config: CloudServerConfig
+) {
+ return {
+ async methods(headers: Headers) {
+ const accounts = await auth.listAuthenticationMethods(headers)
+ const methods = accounts.flatMap((account): CloudAuthenticationMethod[] => {
+ if (!supportedProvider(account.providerId)) return []
+ return [
+ {
+ id: account.id,
+ provider: account.providerId,
+ createdAt: account.createdAt.toISOString(),
+ canUnlink: accounts.length > 1
+ }
+ ]
+ })
+ return {
+ methods,
+ availableSocialProviders: configuredSocialProviders(config).filter(
+ (provider) => !methods.some((method) => method.provider === provider)
+ )
+ }
+ },
+ async changePassword(
+ headers: Headers,
+ input: { currentPassword: string; newPassword: string }
+ ): Promise<void> {
+ await auth.changePassword(headers, input)
+ },
+ async startSocialLink(
+ headers: Headers,
+ input: { provider: 'google' | 'apple'; callbackURL: string }
+ ): Promise<string> {
+ if (!configuredSocialProviders(config).includes(input.provider)) {
+ throw new Error('Authentication provider is unavailable')
+ }
+ const callback = new URL(input.callbackURL)
+ if (callback.origin !== new URL(config.publicURL).origin) {
+ throw new Error('Authentication callback origin is unavailable')
+ }
+ return auth.startSocialLink(headers, { ...input, callbackURL: callback.href })
+ },
+ async unlink(headers: Headers, methodId: string): Promise<void> {
+ await auth.unlinkAuthenticationMethod(headers, methodId)
+ }
+ }
+}
+
+export type AccountAuthenticationService = ReturnType<typeof createAccountAuthenticationService>
diff --git a/packages/cloud/src/server/auth/adapter.ts b/packages/cloud/src/server/auth/adapter.ts
new file mode 100644
index 000000000..16a84db75
--- /dev/null
+++ b/packages/cloud/src/server/auth/adapter.ts
@@ -0,0 +1,72 @@
+import type { CloudActor } from '#cloud/server/auth/session'
+
+export type CloudAdminUser = {
+ id: string
+ name: string
+ email: string
+ role?: string
+ banned: boolean | null
+ banReason?: string | null
+ createdAt: Date
+}
+
+export type CloudMFAStatus = {
+ required: boolean
+ enabled: boolean
+ /** Whether an authenticator app is set up, apart from any passkeys. */
+ totpEnabled: boolean
+ assured: boolean
+ totpAvailable: boolean
+ passkeysAvailable: boolean
+ recoveryCodesAvailable: boolean
+}
+
+export type CloudIdentity = {
+ userId: string
+ email: string
+ name: string
+ deploymentRole?: 'user' | 'admin'
+}
+
+export type CloudAuthenticationMethodRecord = {
+ id: string
+ providerId: string
+ createdAt: Date
+}
+
+export interface CloudAuthAdapter {
+ handler(request: Request): Promise<Response>
+ resolveIdentity(headers: Headers): Promise<CloudIdentity | null>
+ resolveSession(headers: Headers): Promise<CloudActor | null>
+ listAuthenticationMethods(headers: Headers): Promise<CloudAuthenticationMethodRecord[]>
+ changePassword(
+ headers: Headers,
+ input: { currentPassword: string; newPassword: string }
+ ): Promise<void>
+ startSocialLink(
+ headers: Headers,
+ input: { provider: 'google' | 'apple'; callbackURL: string }
+ ): Promise<string>
+ unlinkAuthenticationMethod(headers: Headers, methodId: string): Promise<void>
+ listUsers(
+ headers: Headers,
+ query?: { searchValue?: string; limit?: number; offset?: number }
+ ): Promise<{ users: CloudAdminUser[]; total: number }>
+ banUser(headers: Headers, userId: string, reason?: string): Promise<void>
+ unbanUser(headers: Headers, userId: string): Promise<void>
+ revokeUserSessions(headers: Headers, userId: string): Promise<void>
+ setRole(headers: Headers, userId: string, role: 'user' | 'admin'): Promise<void>
+ mfaStatus(headers: Headers): Promise<CloudMFAStatus | null>
+ enableTOTP(
+ headers: Headers,
+ password?: string
+ ): Promise<{ totpURI: string; backupCodes: string[] }>
+ verifyTOTP(headers: Headers, code: string): Promise<Response | undefined>
+ verifyRecoveryCode(headers: Headers, code: string): Promise<Response | undefined>
+ generateRecoveryCodes(headers: Headers, password?: string): Promise<string[]>
+ disableTOTP(headers: Headers, password?: string): Promise<void>
+ listPasskeys(headers: Headers): Promise<Array<{ id: string; name?: string; createdAt: Date }>>
+ deletePasskey(headers: Headers, id: string): Promise<void>
+ migrate: () => Promise<void>
+ schemaVersion: string
+}
diff --git a/packages/cloud/src/server/auth/email.ts b/packages/cloud/src/server/auth/email.ts
new file mode 100644
index 000000000..128284918
--- /dev/null
+++ b/packages/cloud/src/server/auth/email.ts
@@ -0,0 +1,60 @@
+import type { TransactionalEmailService } from '#cloud/server/email'
+import { sha256 } from '@noble/hashes/sha2.js'
+import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'
+
+export type AuthenticationEmailService = {
+ sendVerification(input: {
+ email: string
+ name: string
+ url: string
+ token: string
+ }): Promise<void>
+ sendPasswordReset(input: {
+ email: string
+ name: string
+ url: string
+ token: string
+ }): Promise<void>
+ sendPasswordChanged(input: {
+ email: string
+ name: string
+ userId: string
+ url: string
+ }): Promise<void>
+}
+
+function tokenHash(value: string): string {
+ return bytesToHex(sha256(utf8ToBytes(value)))
+}
+
+export function createAuthenticationEmailService(
+ email: TransactionalEmailService,
+ publicURL: string
+): AuthenticationEmailService {
+ return {
+ async sendVerification(input) {
+ await email.enqueue({
+ idempotencyKey: `email-verification/${input.email.toLowerCase()}/${tokenHash(input.token)}`,
+ kind: 'email-verification',
+ recipientEmail: input.email,
+ payload: { name: input.name, actionURL: input.url }
+ })
+ },
+ async sendPasswordReset(input) {
+ await email.enqueue({
+ idempotencyKey: `password-reset/${input.email.toLowerCase()}/${tokenHash(input.token)}`,
+ kind: 'password-reset',
+ recipientEmail: input.email,
+ payload: { name: input.name, actionURL: input.url }
+ })
+ },
+ async sendPasswordChanged(input) {
+ await email.enqueue({
+ idempotencyKey: `password-changed/${input.userId}/${crypto.randomUUID()}`,
+ kind: 'password-changed',
+ recipientEmail: input.email,
+ payload: { name: input.name, actionURL: new URL('/auth/sign-in', publicURL).href }
+ })
+ }
+ }
+}
diff --git a/packages/cloud/src/server/auth/factory.ts b/packages/cloud/src/server/auth/factory.ts
new file mode 100644
index 000000000..be8689bc2
--- /dev/null
+++ b/packages/cloud/src/server/auth/factory.ts
@@ -0,0 +1,467 @@
+import { createEnrollmentService, type EnrollmentService } from '#cloud/admin/enrollment/service'
+import type { CloudServerConfig } from '#cloud/server/config'
+import type { CloudDatabase } from '#cloud/server/db'
+import { passkey } from '@better-auth/passkey'
+import { APIError, betterAuth, type BetterAuthOptions } from 'better-auth'
+import { getMigrations } from 'better-auth/db/migration'
+import {
+ admin,
+ bearer,
+ captcha,
+ deviceAuthorization,
+ haveIBeenPwned,
+ twoFactor
+} from 'better-auth/plugins'
+import { importPKCS8, SignJWT } from 'jose'
+import type { Kysely } from 'kysely'
+
+import type { CloudAuthAdapter } from './adapter'
+import type { AuthenticationEmailService } from './email'
+import { createMFAAssuranceService } from './mfa-assurance'
+
+const APPLE_AUDIENCE = 'https://appleid.apple.com'
+const APPLE_SECRET_LIFETIME_SECONDS = 180 * 24 * 60 * 60
+const BETTER_AUTH_SCHEMA_VERSION = '1.7.7+mfa.1'
+const ACCOUNT_SECURITY_FRESH_AGE_SECONDS = 10 * 60
+
+async function generateAppleClientSecret(config: CloudServerConfig): Promise<string> {
+ if (
+ !config.appleClientId ||
+ !config.appleTeamId ||
+ !config.appleKeyId ||
+ !config.applePrivateKey
+ ) {
+ throw new Error('Apple authentication is not configured')
+ }
+ const privateKey = await importPKCS8(config.applePrivateKey.replaceAll('\\n', '\n'), 'ES256')
+ const issuedAt = Math.floor(Date.now() / 1000)
+ return new SignJWT({})
+ .setProtectedHeader({ alg: 'ES256', kid: config.appleKeyId })
+ .setIssuer(config.appleTeamId)
+ .setSubject(config.appleClientId)
+ .setAudience(APPLE_AUDIENCE)
+ .setIssuedAt(issuedAt)
+ .setExpirationTime(issuedAt + APPLE_SECRET_LIFETIME_SECONDS)
+ .sign(privateKey)
+}
+
+function socialProviders(config: CloudServerConfig): BetterAuthOptions['socialProviders'] {
+ const providers: BetterAuthOptions['socialProviders'] = {}
+ if (config.googleClientId && config.googleClientSecret) {
+ providers.google = {
+ clientId: config.googleClientId,
+ clientSecret: config.googleClientSecret
+ }
+ }
+ if (config.appleClientId) {
+ providers.apple = async () => {
+ const provider: {
+ clientId: string
+ clientSecret: string
+ appBundleIdentifier?: string
+ } = {
+ clientId: config.appleClientId ?? '',
+ clientSecret: await generateAppleClientSecret(config)
+ }
+ if (config.appleAppBundleIdentifier) {
+ provider.appBundleIdentifier = config.appleAppBundleIdentifier
+ }
+ return provider
+ }
+ }
+ return providers
+}
+
+function assuranceMethod(path: string): 'totp' | 'recovery-code' | 'passkey' | null {
+ if (path === '/api/auth/two-factor/verify-totp') return 'totp'
+ if (path === '/api/auth/two-factor/verify-backup-code') return 'recovery-code'
+ if (path === '/api/auth/passkey/verify-authentication') return 'passkey'
+ return null
+}
+
+async function recordResponseAssurance(
+ response: Response,
+ method: 'totp' | 'recovery-code' | 'passkey',
+ database: Kysely<CloudDatabase>,
+ assurance: ReturnType<typeof createMFAAssuranceService>
+): Promise<void> {
+ const signedToken = response.headers.get('set-auth-token')
+ const token = signedToken?.split('.', 1)[0]
+ if (!token) return
+ const session = await database
+ .selectFrom('session')
+ .select(['id', 'userId'])
+ .where('token', '=', token)
+ .executeTakeFirst()
+ if (session) await assurance.record({ sessionId: session.id, userId: session.userId, method })
+}
+
+async function verifySecondFactor(
+ auth: { handler(request: Request): Promise<Response> },
+ config: CloudServerConfig,
+ database: Kysely<CloudDatabase>,
+ assurance: ReturnType<typeof createMFAAssuranceService>,
+ headers: Headers,
+ code: string,
+ method: 'totp' | 'recovery-code'
+): Promise<Response> {
+ const path = method === 'totp' ? 'verify-totp' : 'verify-backup-code'
+ const response = await auth.handler(
+ new Request(new URL(`/api/auth/two-factor/${path}`, config.publicURL), {
+ method: 'POST',
+ headers: new Headers({
+ ...Object.fromEntries(headers),
+ 'Content-Type': 'application/json'
+ }),
+ body: JSON.stringify({ code, trustDevice: false })
+ })
+ )
+ if (!response.ok) throw APIError.fromStatus(response.status as 401)
+ await recordResponseAssurance(response, method, database, assurance)
+ return response
+}
+
+export type CloudAuthRuntimeOptions = {
+ email?: AuthenticationEmailService
+ runInBackground?: (promise: Promise<unknown>) => void
+}
+
+export function createBetterAuthAdapter(
+ config: CloudServerConfig,
+ database: Kysely<CloudDatabase>,
+ enrollment: EnrollmentService = createEnrollmentService(database),
+ runtime: CloudAuthRuntimeOptions = {}
+): CloudAuthAdapter {
+ const authenticationEmail = runtime.email
+ const assurance = createMFAAssuranceService(database, config)
+ const auth = betterAuth({
+ appName: 'OpenPencil Cloud',
+ baseURL: config.publicURL,
+ basePath: '/api/auth',
+ secret: config.authSecret,
+ database: {
+ db: database,
+ type: 'postgres',
+ casing: 'camel',
+ transaction: true
+ },
+ account: {
+ accountLinking: {
+ enabled: true,
+ disableImplicitLinking: false,
+ trustedProviders: ['google', 'apple'],
+ allowDifferentEmails: false,
+ allowUnlinkingAll: false,
+ requireLocalEmailVerified: true
+ }
+ },
+ session: { freshAge: ACCOUNT_SECURITY_FRESH_AGE_SECONDS },
+ advanced: {
+ database: { generateId: 'uuid' },
+ ipAddress: {
+ ipAddressHeaders: config.authTrustedIPHeaders,
+ trustedProxies: config.authTrustedProxies
+ },
+ ...(runtime.runInBackground ? { backgroundTasks: { handler: runtime.runInBackground } } : {})
+ },
+ rateLimit: {
+ enabled: true,
+ storage: 'database',
+ window: 60,
+ max: 100,
+ customRules: {
+ '/device/code': { window: 60, max: 10 },
+ '/device/token': { window: 60, max: 60 },
+ '/device/approve': { window: 60, max: 10 },
+ '/device/deny': { window: 60, max: 10 },
+ '/sign-in/email': { window: 10, max: 3 },
+ '/sign-up/email': { window: 10, max: 3 },
+ '/request-password-reset': { window: 60, max: 3 },
+ '/send-verification-email': { window: 60, max: 3 }
+ }
+ },
+ emailAndPassword: config.emailPasswordEnabled
+ ? {
+ enabled: true,
+ disableSignUp: !config.emailPasswordSignUpEnabled,
+ requireEmailVerification: true,
+ minPasswordLength: config.emailPasswordMinimumLength,
+ maxPasswordLength: config.emailPasswordMaximumLength,
+ autoSignIn: false,
+ resetPasswordTokenExpiresIn: config.passwordResetExpiresIn,
+ revokeSessionsOnPasswordReset: true,
+ sendResetPassword: authenticationEmail
+ ? ({ user, url, token }) =>
+ authenticationEmail.sendPasswordReset({
+ email: user.email,
+ name: user.name,
+ url,
+ token
+ })
+ : undefined,
+ onPasswordReset: authenticationEmail
+ ? ({ user }) =>
+ authenticationEmail.sendPasswordChanged({
+ email: user.email,
+ name: user.name,
+ userId: user.id,
+ url: config.publicURL
+ })
+ : undefined
+ }
+ : undefined,
+ emailVerification:
+ config.emailPasswordEnabled && authenticationEmail
+ ? {
+ expiresIn: config.emailVerificationExpiresIn,
+ sendOnSignUp: true,
+ // Signing in unverified only says so; people ask for another link with Send again.
+ sendOnSignIn: false,
+ autoSignInAfterVerification: true,
+ sendVerificationEmail: ({ user, url, token }) =>
+ authenticationEmail.sendVerification({
+ email: user.email,
+ name: user.name,
+ url,
+ token
+ }),
+ afterEmailVerification: async (user) => {
+ if (config.enrollmentMode === 'approval') {
+ await enrollment.request({ email: user.email, name: user.name })
+ }
+ await enrollment.bindApprovedUser(user.email, user.id)
+ }
+ }
+ : undefined,
+ user: {
+ validateUserInfo: ({ source }) => {
+ if (source.action === 'create-user' && config.enrollmentMode === 'closed') {
+ return { error: 'enrollment_closed', errorDescription: 'Cloud enrollment is closed' }
+ }
+ return undefined
+ }
+ },
+ databaseHooks: {
+ user: {
+ create: {
+ after: async (user) => {
+ if (!user.emailVerified) return
+ if (config.enrollmentMode === 'approval') {
+ await enrollment.request({ email: user.email, name: user.name })
+ }
+ await enrollment.bindApprovedUser(user.email, user.id)
+ }
+ }
+ }
+ },
+ plugins: [
+ ...(config.captchaProvider && config.captchaSecretKey
+ ? [
+ captcha({
+ provider: config.captchaProvider,
+ secretKey: config.captchaSecretKey,
+ allowedHostnames: config.captchaAllowedHostnames,
+ endpoints: ['/sign-up/email', '/sign-in/email', '/request-password-reset']
+ })
+ ]
+ : []),
+ ...(config.compromisedPasswordCheck ? [haveIBeenPwned()] : []),
+ twoFactor({
+ issuer: 'OpenPencil Cloud',
+ trustDeviceMaxAge: config.mfaTrustedDeviceDays * 24 * 60 * 60,
+ allowPasswordless: true,
+ totpOptions: { disable: !config.totpEnabled, allowPasswordless: true },
+ backupCodeOptions: {
+ disable: !config.totpEnabled || !config.recoveryCodesEnabled,
+ storeBackupCodes: 'encrypted'
+ }
+ }),
+ passkey({
+ rpID: config.passkeyRPID ?? new URL(config.publicURL).hostname,
+ rpName: config.passkeyRPName,
+ origin: config.passkeyOrigin ?? new URL(config.publicURL).origin
+ }),
+ admin(
+ config.deploymentAdminUserIds.length > 0
+ ? { adminUserIds: config.deploymentAdminUserIds }
+ : {}
+ ),
+ // Device authorization returns opaque database session tokens, not signed cookies.
+ bearer(),
+ deviceAuthorization({
+ verificationUri: new URL('/cloud/device', config.publicURL).href,
+ validateClient: (clientId) => clientId.startsWith('openpencil-desktop:')
+ })
+ ],
+ socialProviders: socialProviders(config),
+ trustedOrigins: [
+ config.publicURL,
+ ...config.trustedOrigins,
+ ...(config.appleClientId ? [APPLE_AUDIENCE] : [])
+ ]
+ })
+
+ // Better Auth's admin plugin treats `adminUserIds` as administrators too, so Cloud does the same.
+ const deploymentRole = (user: { id: string; role?: string | null }) =>
+ user.role === 'admin' || config.deploymentAdminUserIds.includes(user.id)
+ ? ('admin' as const)
+ : ('user' as const)
+
+ const resolveIdentity = async (headers: Headers) => {
+ const session = await auth.api.getSession({ headers })
+ if (!session) return null
+ return {
+ userId: session.user.id,
+ email: session.user.email,
+ name: session.user.name,
+ deploymentRole: deploymentRole(session.user)
+ }
+ }
+
+ return {
+ handler: async (request) => {
+ const path = new URL(request.url).pathname
+ // Administration goes through `/api/admin`, which adds MFA, origin, last-admin, and audit
+ // checks; Better Auth's own admin endpoints would skip all of them.
+ if (path === '/api/auth/admin' || path.startsWith('/api/auth/admin/')) {
+ return Response.json({ error: { code: 'forbidden' } }, { status: 403 })
+ }
+ const response = await auth.handler(request)
+ const method = assuranceMethod(path)
+ if (response.ok && method)
+ await recordResponseAssurance(response, method, database, assurance)
+ return response
+ },
+ resolveIdentity,
+ async resolveSession(headers) {
+ const identity = await resolveIdentity(headers)
+ if (!identity) return null
+ if (config.enrollmentMode === 'approval' && !(await enrollment.isApproved(identity.email))) {
+ return null
+ }
+ return identity
+ },
+ async listAuthenticationMethods(headers) {
+ const accounts = await auth.api.listUserAccounts({ headers })
+ return accounts.map((account) => ({
+ id: account.id,
+ providerId: account.providerId,
+ createdAt: account.createdAt
+ }))
+ },
+ async changePassword(headers, input) {
+ const session = authenticationEmail ? await auth.api.getSession({ headers }) : null
+ await auth.api.changePassword({
+ headers,
+ body: { ...input, revokeOtherSessions: false }
+ })
+ await auth.api.revokeOtherSessions({ headers })
+ if (authenticationEmail && session) {
+ await authenticationEmail.sendPasswordChanged({
+ email: session.user.email,
+ name: session.user.name,
+ userId: session.user.id,
+ url: config.publicURL
+ })
+ }
+ },
+ async startSocialLink(headers, input) {
+ const session = await auth.api.getSession({ headers, query: { disableCookieCache: true } })
+ const createdAt = session?.session.createdAt
+ if (
+ !createdAt ||
+ Date.now() - new Date(createdAt).getTime() >= ACCOUNT_SECURITY_FRESH_AGE_SECONDS * 1000
+ ) {
+ throw APIError.from('FORBIDDEN', {
+ code: 'SESSION_NOT_FRESH',
+ message: 'Session is not fresh'
+ })
+ }
+ const response = await auth.api.linkSocialAccount({
+ headers,
+ body: {
+ provider: input.provider,
+ callbackURL: input.callbackURL,
+ errorCallbackURL: input.callbackURL,
+ disableRedirect: true
+ }
+ })
+ return response.url
+ },
+ async unlinkAuthenticationMethod(headers, methodId) {
+ await auth.api.unlinkAccount({ headers, body: { accountId: methodId } })
+ },
+ async listUsers(headers, query) {
+ const listQuery = query?.searchValue
+ ? {
+ searchValue: query.searchValue,
+ searchField: 'email' as const,
+ limit: query.limit,
+ offset: query.offset
+ }
+ : { limit: query?.limit, offset: query?.offset }
+ const response = await auth.api.listUsers({ headers, query: listQuery })
+ return { users: response.users, total: response.total }
+ },
+ async banUser(headers, userId, reason) {
+ await auth.api.banUser({ headers, body: { userId, banReason: reason } })
+ },
+ async unbanUser(headers, userId) {
+ await auth.api.unbanUser({ headers, body: { userId } })
+ },
+ async revokeUserSessions(headers, userId) {
+ await auth.api.revokeUserSessions({ headers, body: { userId } })
+ },
+ async setRole(headers, userId, role) {
+ await auth.api.setRole({ headers, body: { userId, role } })
+ },
+ async mfaStatus(headers) {
+ const session = await auth.api.getSession({ headers, query: { disableCookieCache: true } })
+ if (!session) return null
+ const passkeys = await auth.api.listPasskeys({ headers })
+ return assurance.status({
+ sessionId: session.session.id,
+ userId: session.user.id,
+ deploymentRole: deploymentRole(session.user),
+ twoFactorEnabled:
+ 'twoFactorEnabled' in session.user && session.user.twoFactorEnabled === true,
+ passkeyCount: passkeys.length
+ })
+ },
+ async enableTOTP(headers, password) {
+ const response = await auth.api.enableTwoFactor({
+ headers,
+ body: { password, method: 'totp' }
+ })
+ if (response.method !== 'totp') throw new Error('TOTP setup was unavailable')
+ return { totpURI: response.totpURI, backupCodes: response.backupCodes }
+ },
+ async verifyTOTP(headers, code) {
+ return verifySecondFactor(auth, config, database, assurance, headers, code, 'totp')
+ },
+ async verifyRecoveryCode(headers, code) {
+ return verifySecondFactor(auth, config, database, assurance, headers, code, 'recovery-code')
+ },
+ async generateRecoveryCodes(headers, password) {
+ return (await auth.api.generateBackupCodes({ headers, body: { password } })).backupCodes
+ },
+ async disableTOTP(headers, password) {
+ await auth.api.disableTwoFactor({ headers, body: { password } })
+ },
+ async listPasskeys(headers) {
+ return (await auth.api.listPasskeys({ headers })).map((item) => ({
+ id: item.id,
+ name: item.name,
+ createdAt: item.createdAt
+ }))
+ },
+ async deletePasskey(headers, id) {
+ await auth.api.deletePasskey({ headers, body: { id } })
+ },
+ schemaVersion: BETTER_AUTH_SCHEMA_VERSION,
+ async migrate() {
+ const migrations = await getMigrations(auth.options)
+ await migrations.runMigrations()
+ }
+ }
+}
diff --git a/packages/cloud/src/server/auth/index.ts b/packages/cloud/src/server/auth/index.ts
new file mode 100644
index 000000000..057d1f06f
--- /dev/null
+++ b/packages/cloud/src/server/auth/index.ts
@@ -0,0 +1,15 @@
+export { createAccountAuthenticationService, type AccountAuthenticationService } from './account'
+export type { CloudAuthAdapter } from './adapter'
+export { createAuthenticationEmailService, type AuthenticationEmailService } from './email'
+export { createMFAAssuranceService, type MFAAssuranceService } from './mfa-assurance'
+export { createCloudAuthenticationRuntime } from './runtime'
+export { createBetterAuthAdapter, type CloudAuthRuntimeOptions } from './factory'
+export {
+ createCloudIdentityResolver,
+ createCloudSessionResolver,
+ type CloudActor,
+ type CloudIdentityResolver,
+ type CloudSessionResolver
+} from './session'
+export type { CloudIdentity } from './adapter'
+export { workspaceAccessControl, workspaceRoles, workspaceStatements } from './workspace-access'
diff --git a/packages/cloud/src/server/auth/mfa-assurance.ts b/packages/cloud/src/server/auth/mfa-assurance.ts
new file mode 100644
index 000000000..31575bd03
--- /dev/null
+++ b/packages/cloud/src/server/auth/mfa-assurance.ts
@@ -0,0 +1,55 @@
+import type { CloudMFAStatus } from '#cloud/server/auth/adapter'
+import type { CloudServerConfig } from '#cloud/server/config'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { Kysely } from 'kysely'
+
+const ASSURANCE_MAX_AGE_MS = 12 * 60 * 60_000
+
+export function createMFAAssuranceService(
+ database: Kysely<CloudDatabase>,
+ config: CloudServerConfig
+) {
+ return {
+ async record(input: {
+ sessionId: string
+ userId: string
+ method: 'totp' | 'recovery-code' | 'passkey'
+ }): Promise<void> {
+ await database
+ .insertInto('cloudMfaAssurance')
+ .values({ ...input, verifiedAt: new Date() })
+ .onConflict((conflict) =>
+ conflict.column('sessionId').doUpdateSet({ method: input.method, verifiedAt: new Date() })
+ )
+ .execute()
+ },
+ async status(input: {
+ sessionId: string
+ userId: string
+ deploymentRole?: 'user' | 'admin'
+ twoFactorEnabled: boolean
+ passkeyCount: number
+ }): Promise<CloudMFAStatus> {
+ const assurance = await database
+ .selectFrom('cloudMfaAssurance')
+ .select('verifiedAt')
+ .where('sessionId', '=', input.sessionId)
+ .where('userId', '=', input.userId)
+ .executeTakeFirst()
+ const assured = Boolean(
+ assurance && new Date(assurance.verifiedAt).getTime() > Date.now() - ASSURANCE_MAX_AGE_MS
+ )
+ return {
+ required: config.deploymentAdminMFARequired && input.deploymentRole === 'admin' && !assured,
+ enabled: input.twoFactorEnabled || input.passkeyCount > 0,
+ totpEnabled: input.twoFactorEnabled,
+ assured,
+ totpAvailable: config.totpEnabled,
+ passkeysAvailable: config.passkeysEnabled,
+ recoveryCodesAvailable: config.totpEnabled && config.recoveryCodesEnabled
+ }
+ }
+ }
+}
+
+export type MFAAssuranceService = ReturnType<typeof createMFAAssuranceService>
diff --git a/packages/cloud/src/server/auth/runtime.ts b/packages/cloud/src/server/auth/runtime.ts
new file mode 100644
index 000000000..4d7d03f9e
--- /dev/null
+++ b/packages/cloud/src/server/auth/runtime.ts
@@ -0,0 +1,26 @@
+import { createEnrollmentService } from '#cloud/admin/enrollment/service'
+import type { CloudServerConfig } from '#cloud/server/config'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { TransactionalEmailService } from '#cloud/server/email'
+import type { Kysely } from 'kysely'
+
+import { createAuthenticationEmailService } from './email'
+import { createBetterAuthAdapter, type CloudAuthRuntimeOptions } from './factory'
+
+export function createCloudAuthenticationRuntime(
+ config: CloudServerConfig,
+ database: Kysely<CloudDatabase>,
+ email: TransactionalEmailService,
+ options: Pick<CloudAuthRuntimeOptions, 'runInBackground'> = {}
+) {
+ const enrollment = createEnrollmentService(database, {
+ appURL: config.appURL ?? config.publicURL,
+ adminRecipients: config.enrollmentAdminNotificationEmails,
+ email
+ })
+ const auth = createBetterAuthAdapter(config, database, enrollment, {
+ email: createAuthenticationEmailService(email, config.publicURL),
+ ...options
+ })
+ return { auth, enrollment }
+}
diff --git a/packages/cloud/src/server/auth/session.ts b/packages/cloud/src/server/auth/session.ts
new file mode 100644
index 000000000..51955553b
--- /dev/null
+++ b/packages/cloud/src/server/auth/session.ts
@@ -0,0 +1,19 @@
+import type { CloudAuthAdapter, CloudIdentity } from '#cloud/server/auth/adapter'
+
+export type CloudActor = {
+ userId: string
+ email: string
+ name: string
+ deploymentRole?: 'user' | 'admin'
+}
+
+export type CloudIdentityResolver = (request: Request) => Promise<CloudIdentity | null>
+export type CloudSessionResolver = (request: Request) => Promise<CloudActor | null>
+
+export function createCloudIdentityResolver(auth: CloudAuthAdapter): CloudIdentityResolver {
+ return (request) => auth.resolveIdentity(request.headers)
+}
+
+export function createCloudSessionResolver(auth: CloudAuthAdapter): CloudSessionResolver {
+ return (request) => auth.resolveSession(request.headers)
+}
diff --git a/packages/cloud/src/server/auth/workspace-access.ts b/packages/cloud/src/server/auth/workspace-access.ts
new file mode 100644
index 000000000..5dc91d362
--- /dev/null
+++ b/packages/cloud/src/server/auth/workspace-access.ts
@@ -0,0 +1,23 @@
+import { createAccessControl } from 'better-auth/plugins/access'
+
+export const workspaceStatements = {
+ workspace: ['read', 'update', 'delete', 'invite', 'manage-members'],
+ document: ['create', 'read', 'edit', 'share', 'delete']
+} as const
+
+export const workspaceAccessControl = createAccessControl(workspaceStatements)
+
+export const workspaceRoles = {
+ admin: workspaceAccessControl.newRole({
+ workspace: ['read', 'update', 'delete', 'invite', 'manage-members'],
+ document: ['create', 'read', 'edit', 'share', 'delete']
+ }),
+ editor: workspaceAccessControl.newRole({
+ workspace: ['read'],
+ document: ['create', 'read', 'edit', 'share']
+ }),
+ viewer: workspaceAccessControl.newRole({
+ workspace: ['read'],
+ document: ['read']
+ })
+}
diff --git a/packages/cloud/src/server/cleanup/documents.ts b/packages/cloud/src/server/cleanup/documents.ts
new file mode 100644
index 000000000..66e595aed
--- /dev/null
+++ b/packages/cloud/src/server/cleanup/documents.ts
@@ -0,0 +1,238 @@
+import type { CloudDatabase } from '#cloud/server/db'
+import type { ObjectStore } from '#cloud/server/objects'
+import type { Kysely } from 'kysely'
+
+export type DocumentCleanupOptions = {
+ batchSize: number
+ leaseDurationMs: number
+ retentionMs: number
+ now?: Date
+}
+
+export type DocumentCleanupResult = {
+ claimed: number
+ cleaned: number
+ failed: number
+ objectsDeleted: number
+ bytesReclaimed: number
+}
+
+export type DocumentCleanupService = {
+ cleanupDeletedDocuments(options: DocumentCleanupOptions): Promise<DocumentCleanupResult>
+}
+
+type ClaimedDocument = {
+ id: string
+ workspaceId: string
+ deletedAt: Date
+}
+
+type StoredRevisionObject = {
+ id: string
+ objectKey: string
+ byteSize: number
+}
+
+export function createDocumentCleanupService(
+ database: Kysely<CloudDatabase>,
+ objects: ObjectStore
+): DocumentCleanupService {
+ return {
+ async cleanupDeletedDocuments(options) {
+ const now = options.now ?? new Date()
+ const retentionBefore = new Date(now.getTime() - options.retentionMs)
+ const staleBefore = new Date(now.getTime() - options.leaseDurationMs)
+ const claimId = crypto.randomUUID()
+ const documents = await claimDocuments(
+ database,
+ options.batchSize,
+ retentionBefore,
+ staleBefore,
+ now,
+ claimId
+ )
+ const result: DocumentCleanupResult = {
+ claimed: documents.length,
+ cleaned: 0,
+ failed: 0,
+ objectsDeleted: 0,
+ bytesReclaimed: 0
+ }
+ for (const document of documents) {
+ try {
+ const revisionObjects = await documentObjects(database, document.id)
+ for (const object of revisionObjects) await objects.delete(object.objectKey)
+ const reclaimed = await removeDocumentMetadata(
+ database,
+ document,
+ revisionObjects,
+ retentionBefore,
+ claimId
+ )
+ if (!reclaimed) continue
+ result.cleaned++
+ result.objectsDeleted += reclaimed.objectsDeleted
+ result.bytesReclaimed += reclaimed.bytesReclaimed
+ } catch {
+ result.failed++
+ await releaseClaim(database, document.id, claimId)
+ }
+ }
+ return result
+ }
+ }
+}
+
+async function claimDocuments(
+ database: Kysely<CloudDatabase>,
+ batchSize: number,
+ retentionBefore: Date,
+ staleBefore: Date,
+ now: Date,
+ claimId: string
+): Promise<ClaimedDocument[]> {
+ return database.transaction().execute(async (transaction) => {
+ const candidates = await transaction
+ .selectFrom('document')
+ .select(['id', 'workspaceId', 'deletedAt'])
+ .where('deletedAt', 'is not', null)
+ .where('deletedAt', '<=', retentionBefore)
+ .where((expression) =>
+ expression.or([
+ expression('cleanupClaimId', 'is', null),
+ expression('cleanupClaimedAt', '<=', staleBefore)
+ ])
+ )
+ .where((expression) =>
+ expression.not(
+ expression.exists(
+ expression
+ .selectFrom('upload')
+ .select('upload.id')
+ .whereRef('upload.documentId', '=', 'document.id')
+ .where('upload.status', 'in', ['pending', 'cleaning'])
+ )
+ )
+ )
+ .orderBy('deletedAt')
+ .limit(batchSize)
+ .forUpdate()
+ .skipLocked()
+ .execute()
+ const claimed = candidates.filter(
+ (document): document is ClaimedDocument => document.deletedAt !== null
+ )
+ if (claimed.length === 0) return []
+ await transaction
+ .updateTable('document')
+ .set({ cleanupClaimId: claimId, cleanupClaimedAt: now })
+ .where(
+ 'id',
+ 'in',
+ claimed.map((document) => document.id)
+ )
+ .execute()
+ return claimed
+ })
+}
+
+async function documentObjects(
+ database: Kysely<CloudDatabase>,
+ documentId: string
+): Promise<StoredRevisionObject[]> {
+ const rows = await database
+ .selectFrom('documentRevision')
+ .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')
+ .select(['storageObject.id', 'storageObject.objectKey', 'storageObject.byteSize'])
+ .where('documentRevision.documentId', '=', documentId)
+ .where((expression) =>
+ expression.not(
+ expression.exists(
+ expression
+ .selectFrom('documentRevision as otherRevision')
+ .select('otherRevision.id')
+ .whereRef('otherRevision.storageObjectId', '=', 'storageObject.id')
+ .where('otherRevision.documentId', '!=', documentId)
+ )
+ )
+ )
+ .execute()
+ return rows.map((row) => ({ ...row, byteSize: Number(row.byteSize) }))
+}
+
+async function removeDocumentMetadata(
+ database: Kysely<CloudDatabase>,
+ document: ClaimedDocument,
+ objects: StoredRevisionObject[],
+ retentionBefore: Date,
+ claimId: string
+): Promise<{ objectsDeleted: number; bytesReclaimed: number } | null> {
+ return database.transaction().execute(async (transaction) => {
+ const locked = await transaction
+ .selectFrom('document')
+ .select(['deletedAt', 'cleanupClaimId'])
+ .where('id', '=', document.id)
+ .forUpdate()
+ .executeTakeFirst()
+ if (
+ !locked?.deletedAt ||
+ locked.deletedAt > retentionBefore ||
+ locked.cleanupClaimId !== claimId
+ ) {
+ return null
+ }
+ await transaction
+ .updateTable('document')
+ .set({ currentRevisionId: null })
+ .where('id', '=', document.id)
+ .execute()
+ await transaction.deleteFrom('documentRevision').where('documentId', '=', document.id).execute()
+ let objectsDeleted = 0
+ let bytesReclaimed = 0
+ for (const object of objects) {
+ const deleted = await transaction
+ .deleteFrom('storageObject')
+ .where('id', '=', object.id)
+ .where((expression) =>
+ expression.not(
+ expression.exists(
+ expression
+ .selectFrom('documentRevision')
+ .select('documentRevision.id')
+ .whereRef('documentRevision.storageObjectId', '=', 'storageObject.id')
+ )
+ )
+ )
+ .executeTakeFirst()
+ if (Number(deleted.numDeletedRows) > 0) {
+ objectsDeleted++
+ bytesReclaimed += object.byteSize
+ }
+ }
+ if (bytesReclaimed > 0) {
+ await transaction
+ .updateTable('workspaceStorageUsage')
+ .set({
+ committedBytes: (expression) => expression('committedBytes', '-', bytesReclaimed),
+ updatedAt: new Date()
+ })
+ .where('workspaceId', '=', document.workspaceId)
+ .execute()
+ }
+ await transaction.deleteFrom('document').where('id', '=', document.id).execute()
+ return { objectsDeleted, bytesReclaimed }
+ })
+}
+
+async function releaseClaim(
+ database: Kysely<CloudDatabase>,
+ documentId: string,
+ claimId: string
+): Promise<void> {
+ await database
+ .updateTable('document')
+ .set({ cleanupClaimId: null, cleanupClaimedAt: null })
+ .where('id', '=', documentId)
+ .where('cleanupClaimId', '=', claimId)
+ .execute()
+}
diff --git a/packages/cloud/src/server/cleanup/index.ts b/packages/cloud/src/server/cleanup/index.ts
new file mode 100644
index 000000000..db140b086
--- /dev/null
+++ b/packages/cloud/src/server/cleanup/index.ts
@@ -0,0 +1,19 @@
+export {
+ createDocumentCleanupService,
+ type DocumentCleanupOptions,
+ type DocumentCleanupResult,
+ type DocumentCleanupService
+} from './documents'
+export {
+ createUploadCleanupService,
+ type UploadCleanupOptions,
+ type UploadCleanupResult,
+ type UploadCleanupService
+} from './uploads'
+export {
+ startCleanupWorker,
+ type CleanupResult,
+ type CleanupServices,
+ type CleanupWorker,
+ type CleanupWorkerOptions
+} from './worker'
diff --git a/packages/cloud/src/server/cleanup/uploads.ts b/packages/cloud/src/server/cleanup/uploads.ts
new file mode 100644
index 000000000..a2e803d01
--- /dev/null
+++ b/packages/cloud/src/server/cleanup/uploads.ts
@@ -0,0 +1,129 @@
+import type { CloudDatabase } from '#cloud/server/db'
+import type { ObjectStore } from '#cloud/server/objects'
+import { createStorageQuotaService } from '#cloud/server/quota'
+import type { Kysely } from 'kysely'
+
+export type UploadCleanupOptions = {
+ batchSize: number
+ leaseDurationMs: number
+ now?: Date
+}
+
+export type UploadCleanupResult = {
+ claimed: number
+ cleaned: number
+ failed: number
+}
+
+export type UploadCleanupService = {
+ cleanupExpiredUploads(options: UploadCleanupOptions): Promise<UploadCleanupResult>
+}
+
+type ClaimedUpload = {
+ id: string
+ objectKey: string
+ multipartUploadId: string | null
+}
+
+export function createUploadCleanupService(
+ database: Kysely<CloudDatabase>,
+ objects: ObjectStore
+): UploadCleanupService {
+ const quota = createStorageQuotaService(database)
+ return {
+ async cleanupExpiredUploads(options) {
+ const now = options.now ?? new Date()
+ const staleBefore = new Date(now.getTime() - options.leaseDurationMs)
+ const claimId = crypto.randomUUID()
+ const uploads = await database.transaction().execute(async (transaction) => {
+ const candidates = await transaction
+ .selectFrom('upload')
+ .select(['id', 'objectKey', 'multipartUploadId'])
+ .where((expression) =>
+ expression.or([
+ expression.and([
+ expression('status', '=', 'pending'),
+ expression('expiresAt', '<=', now)
+ ]),
+ expression.and([
+ expression('status', '=', 'finalizing'),
+ expression('finalizationStartedAt', '<=', staleBefore)
+ ]),
+ expression.and([
+ expression('status', '=', 'cleaning'),
+ expression('cleanupClaimedAt', '<=', staleBefore)
+ ])
+ ])
+ )
+ .orderBy('expiresAt')
+ .limit(options.batchSize)
+ .forUpdate()
+ .skipLocked()
+ .execute()
+ if (candidates.length === 0) return []
+ const ids = candidates.map((upload) => upload.id)
+ await transaction
+ .updateTable('upload')
+ .set({
+ status: 'cleaning',
+ finalizationStartedAt: null,
+ cleanupClaimId: claimId,
+ cleanupClaimedAt: now
+ })
+ .where('id', 'in', ids)
+ .execute()
+ return candidates
+ })
+
+ let cleaned = 0
+ let failed = 0
+ for (const upload of uploads) {
+ try {
+ await removeUploadObject(objects, upload)
+ const result = await database
+ .updateTable('upload')
+ .set({
+ status: 'abandoned',
+ finalizationStartedAt: null,
+ cleanupClaimId: null,
+ cleanupClaimedAt: null
+ })
+ .where('id', '=', upload.id)
+ .where('status', '=', 'cleaning')
+ .where('cleanupClaimId', '=', claimId)
+ .executeTakeFirst()
+ if (Number(result.numUpdatedRows) > 0) {
+ await quota.release(upload.id)
+ cleaned++
+ }
+ } catch {
+ failed++
+ await database
+ .updateTable('upload')
+ .set({
+ status: 'pending',
+ finalizationStartedAt: null,
+ cleanupClaimId: null,
+ cleanupClaimedAt: null
+ })
+ .where('id', '=', upload.id)
+ .where('status', '=', 'cleaning')
+ .where('cleanupClaimId', '=', claimId)
+ .execute()
+ }
+ }
+ return { claimed: uploads.length, cleaned, failed }
+ }
+ }
+}
+
+/**
+ * Aborting covers a multipart upload that never finished; deleting covers one that did, such as an
+ * upload whose commit lost to a newer revision after its parts were assembled.
+ */
+async function removeUploadObject(objects: ObjectStore, upload: ClaimedUpload): Promise<void> {
+ if (upload.multipartUploadId) {
+ await objects.abortUpload({ key: upload.objectKey, uploadId: upload.multipartUploadId })
+ }
+ await objects.delete(upload.objectKey)
+}
diff --git a/packages/cloud/src/server/cleanup/worker.ts b/packages/cloud/src/server/cleanup/worker.ts
new file mode 100644
index 000000000..19005d4cf
--- /dev/null
+++ b/packages/cloud/src/server/cleanup/worker.ts
@@ -0,0 +1,55 @@
+import { startPeriodicWorker } from '../worker/periodic'
+import type { DocumentCleanupResult, DocumentCleanupService } from './documents'
+import type { UploadCleanupResult, UploadCleanupService } from './uploads'
+
+export type CleanupWorkerOptions = {
+ batchSize: number
+ documentRetentionMs: number
+ intervalMs: number
+ leaseDurationMs: number
+ signal?: AbortSignal
+ onError?: (error: unknown) => void
+}
+
+export type CleanupResult = {
+ uploads: UploadCleanupResult
+ documents: DocumentCleanupResult
+ rateLimits: number
+}
+
+export type CleanupServices = {
+ documents: DocumentCleanupService
+ uploads: UploadCleanupService
+ rateLimits?: { cleanupExpired(before: Date): Promise<number> }
+}
+
+export type CleanupWorker = {
+ runOnce(): Promise<CleanupResult>
+ stop(): Promise<void>
+}
+
+export function startCleanupWorker(
+ cleanup: CleanupServices,
+ options: CleanupWorkerOptions
+): CleanupWorker {
+ return startPeriodicWorker({
+ 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 rateLimits = cleanup.rateLimits
+ ? await cleanup.rateLimits.cleanupExpired(new Date(Date.now() - 24 * 60 * 60_000))
+ : 0
+ return { uploads, documents, rateLimits }
+ }
+ })
+}
diff --git a/packages/cloud/src/server/collaboration/index.ts b/packages/cloud/src/server/collaboration/index.ts
new file mode 100644
index 000000000..bacc6f40c
--- /dev/null
+++ b/packages/cloud/src/server/collaboration/index.ts
@@ -0,0 +1,10 @@
+export {
+ createCollaborationRoutes,
+ createPublicCollaborationRoutes,
+ type CollaborationRouteEnvironment
+} from './routes'
+export {
+ createCollaborationTicketService,
+ type CollaborationTicketService,
+ type CollaborationTicketServiceOptions
+} from './service'
diff --git a/packages/cloud/src/server/collaboration/routes.ts b/packages/cloud/src/server/collaboration/routes.ts
new file mode 100644
index 000000000..0f31416b8
--- /dev/null
+++ b/packages/cloud/src/server/collaboration/routes.ts
@@ -0,0 +1,74 @@
+import { parseResolveDocumentShare } from '#cloud/contract'
+import type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'
+import type { CollaborationTicketService } from '#cloud/server/collaboration/service'
+import type { CloudDatabase } from '#cloud/server/db'
+import { DocumentNotFoundError } from '#cloud/server/documents'
+import { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'
+import { DocumentShareInvalidError } from '#cloud/server/sharing'
+import { validatedJSON } from '#cloud/server/validation'
+import { Hono, type Context } from 'hono'
+import type { Kysely } from 'kysely'
+
+export type CollaborationRouteEnvironment = { Variables: { actor: CloudActor } }
+
+function notFound(context: Context, error: unknown): Response | null {
+ if (error instanceof DocumentNotFoundError || error instanceof DocumentShareInvalidError) {
+ return context.json({ error: { code: 'not_found' as const } }, 404)
+ }
+ return null
+}
+
+export function createCollaborationRoutes(
+ service: CollaborationTicketService,
+ rateLimit?: { database: Kysely<CloudDatabase>; secret: string }
+) {
+ const router = new Hono<CollaborationRouteEnvironment>()
+ if (rateLimit) {
+ router.use(
+ '/documents/:documentId/collaboration-ticket',
+ createActorRateLimiter(
+ rateLimit.database,
+ rateLimit.secret,
+ CLOUD_RATE_LIMITS.collaborationTicket,
+ undefined,
+ (context) => context.req.param('documentId') ?? 'unknown-document'
+ )
+ )
+ }
+ return router.post('/documents/:documentId/collaboration-ticket', async (context) => {
+ try {
+ return context.json({
+ ticket: await service.issueUserTicket(context.get('actor'), context.req.param('documentId'))
+ })
+ } catch (error) {
+ const response = notFound(context, error)
+ if (response) return response
+ throw error
+ }
+ })
+}
+
+export function createPublicCollaborationRoutes(
+ service: CollaborationTicketService,
+ resolveSession?: CloudSessionResolver
+) {
+ return new Hono().post(
+ '/shares/:shareId/collaboration-ticket',
+ validatedJSON(parseResolveDocumentShare),
+ async (context) => {
+ try {
+ return context.json({
+ ticket: await service.issueShareTicket(
+ context.req.param('shareId'),
+ context.req.valid('json'),
+ resolveSession ? ((await resolveSession(context.req.raw)) ?? undefined) : undefined
+ )
+ })
+ } catch (error) {
+ const response = notFound(context, error)
+ if (response) return response
+ throw error
+ }
+ }
+ )
+}
diff --git a/packages/cloud/src/server/collaboration/service.ts b/packages/cloud/src/server/collaboration/service.ts
new file mode 100644
index 000000000..5660684ec
--- /dev/null
+++ b/packages/cloud/src/server/collaboration/service.ts
@@ -0,0 +1,172 @@
+import type {
+ CollaborationPrincipal,
+ CollaborationTicket,
+ DocumentPermission,
+ ResolveDocumentShareInput
+} from '#cloud/contract'
+import type { CloudActor } from '#cloud/server/auth'
+import type { CloudDatabase } from '#cloud/server/db'
+import { DocumentNotFoundError } from '#cloud/server/documents'
+import { resolveDocumentAccess } from '#cloud/server/documents/access'
+import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'
+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'
+
+const TICKET_LIFETIME_SECONDS = 5 * 60
+
+async function derivedRoomKey(authSecret: string, documentId: string, roomEpoch: number) {
+ const inputBytes = new TextEncoder().encode(`${authSecret}:room:${documentId}:${roomEpoch}`)
+ const key = await crypto.subtle.importKey('raw', inputBytes, 'HKDF', false, ['deriveBits'])
+ const bits = await crypto.subtle.deriveBits(
+ {
+ name: 'HKDF',
+ hash: 'SHA-256',
+ salt: new TextEncoder().encode(`openpencil-cloud:${documentId}`),
+ info: new TextEncoder().encode(`collaboration-room:${roomEpoch}`)
+ },
+ key,
+ 256
+ )
+ return base64url.encode(new Uint8Array(bits))
+}
+
+async function signedTicket(
+ authSecret: string,
+ documentId: string,
+ principal: CollaborationPrincipal,
+ permission: DocumentPermission,
+ roomEpoch: number,
+ collaborationURL?: string
+): Promise<CollaborationTicket> {
+ const issuedAt = Math.floor(Date.now() / 1000)
+ const expiresAtSeconds = issuedAt + TICKET_LIFETIME_SECONDS
+ const roomId = `cloud:${documentId}:${roomEpoch}`
+ const roomKey = await derivedRoomKey(authSecret, documentId, roomEpoch)
+ const claims = {
+ documentId,
+ roomId,
+ principal,
+ permission,
+ roomEpoch,
+ serverEnforcedWrites: Boolean(collaborationURL)
+ }
+ const token = await new SignJWT(claims)
+ .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
+ .setIssuedAt(issuedAt)
+ .setExpirationTime(expiresAtSeconds)
+ .setSubject(principal.kind === 'user' ? principal.userId : principal.guestId)
+ .sign(new TextEncoder().encode(authSecret))
+ return {
+ token,
+ provider: collaborationURL ? ('hocuspocus' as const) : ('trystero' as const),
+ ...(collaborationURL ? { serverURL: collaborationURL } : {}),
+ ...claims,
+ roomKey,
+ expiresAt: new Date(expiresAtSeconds * 1000).toISOString()
+ }
+}
+
+export type CollaborationTicketServiceOptions = {
+ database: Kysely<CloudDatabase>
+ sharing: DocumentSharingService
+ authSecret: string
+ collaborationURL?: string
+ policy?: CloudPolicy
+ deploymentMode?: 'official' | 'self-hosted'
+}
+
+export function createCollaborationTicketService({
+ database,
+ sharing,
+ authSecret,
+ collaborationURL,
+ policy,
+ deploymentMode = 'self-hosted'
+}: CollaborationTicketServiceOptions) {
+ return {
+ async issueUserTicket(actor: CloudActor, documentId: string): Promise<CollaborationTicket> {
+ const access = await resolveDocumentAccess(database, actor.userId, documentId)
+ if (!access) throw new DocumentNotFoundError()
+ if (policy) {
+ const workspace = await database
+ .selectFrom('document')
+ .select('workspaceId')
+ .where('id', '=', documentId)
+ .executeTakeFirstOrThrow()
+ if (
+ !(await policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, {
+ targetingKey: workspace.workspaceId,
+ actorId: actor.userId,
+ workspaceId: workspace.workspaceId,
+ documentId,
+ deploymentMode
+ }))
+ ) {
+ throw new DocumentNotFoundError()
+ }
+ }
+ const document = await database
+ .selectFrom('document')
+ .select('collaborationEpoch')
+ .where('id', '=', documentId)
+ .where('deletedAt', 'is', null)
+ .executeTakeFirst()
+ if (!document) throw new DocumentNotFoundError()
+ return signedTicket(
+ authSecret,
+ documentId,
+ { kind: 'user', userId: actor.userId, name: actor.name, email: actor.email },
+ access.permission,
+ document.collaborationEpoch,
+ collaborationURL
+ )
+ },
+
+ async issueShareTicket(
+ shareId: string,
+ input: ResolveDocumentShareInput,
+ actor?: CloudActor
+ ): Promise<CollaborationTicket> {
+ const resolved = await sharing.resolveShare(shareId, input, actor)
+ if (policy) {
+ const workspace = await database
+ .selectFrom('document')
+ .select('workspaceId')
+ .where('id', '=', resolved.documentId)
+ .executeTakeFirstOrThrow()
+ const context = {
+ targetingKey: workspace.workspaceId,
+ ...(actor ? { actorId: actor.userId } : {}),
+ workspaceId: workspace.workspaceId,
+ documentId: resolved.documentId,
+ deploymentMode
+ }
+ if (!(await policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, context))) {
+ throw new DocumentNotFoundError()
+ }
+ if (!actor && !(await policy.boolean(CLOUD_FEATURE_KEYS.guestPresence, false, context))) {
+ throw new DocumentNotFoundError()
+ }
+ }
+ const document = await database
+ .selectFrom('document')
+ .select('collaborationEpoch')
+ .where('id', '=', resolved.documentId)
+ .where('deletedAt', 'is', null)
+ .executeTakeFirst()
+ if (!document) throw new DocumentNotFoundError()
+ return signedTicket(
+ authSecret,
+ resolved.documentId,
+ resolved.principal,
+ resolved.permission,
+ document.collaborationEpoch,
+ collaborationURL
+ )
+ }
+ }
+}
+
+export type CollaborationTicketService = ReturnType<typeof createCollaborationTicketService>
diff --git a/packages/cloud/src/server/config/deployment.ts b/packages/cloud/src/server/config/deployment.ts
new file mode 100644
index 000000000..9fcd9b3c8
--- /dev/null
+++ b/packages/cloud/src/server/config/deployment.ts
@@ -0,0 +1,404 @@
+import { cloudEditorVersionSchema } from '#cloud/contract'
+import { staticEntitlementsTOMLSchema } from '#cloud/server/policy/static'
+import { parse as parseTOML } from 'smol-toml'
+import * as v from 'valibot'
+
+import { parseCloudServerConfig, type CloudServerConfig } from './schema'
+
+export type CloudEnvironment = Readonly<Record<string, string | undefined>>
+
+const DEFAULT_SECRET_NAMES = {
+ databaseURL: 'DATABASE_URL',
+ authSecret: 'BETTER_AUTH_SECRET',
+ googleClientId: 'GOOGLE_CLIENT_ID',
+ googleClientSecret: 'GOOGLE_CLIENT_SECRET',
+ applePrivateKey: 'APPLE_PRIVATE_KEY',
+ s3AccessKeyId: 'S3_ACCESS_KEY_ID',
+ s3SecretAccessKey: 'S3_SECRET_ACCESS_KEY',
+ s3SessionToken: 'S3_SESSION_TOKEN',
+ smtpUser: 'OPENPENCIL_CLOUD_SMTP_USER',
+ smtpPassword: 'OPENPENCIL_CLOUD_SMTP_PASSWORD',
+ turnstileSecretKey: 'TURNSTILE_SECRET_KEY'
+} as const
+
+const url = v.pipe(v.string(), v.url())
+const text = v.pipe(v.string(), v.trim(), v.minLength(1))
+const positiveInteger = v.pipe(v.number(), v.integer(), v.minValue(1))
+const secretReferenceSchema = v.object({ from_env: text })
+const configurableTextSchema = v.union([text, secretReferenceSchema])
+const defaultReference = (name: string) => v.optional(secretReferenceSchema, { from_env: name })
+
+const providerSchema = v.object({
+ google: v.optional(
+ v.object({
+ client_id: v.optional(configurableTextSchema, {
+ from_env: DEFAULT_SECRET_NAMES.googleClientId
+ }),
+ client_secret: defaultReference(DEFAULT_SECRET_NAMES.googleClientSecret)
+ })
+ ),
+ apple: v.optional(
+ v.object({
+ client_id: text,
+ team_id: text,
+ key_id: text,
+ private_key: defaultReference(DEFAULT_SECRET_NAMES.applePrivateKey),
+ app_bundle_identifier: v.optional(text)
+ })
+ )
+})
+
+const emailSchema = v.optional(
+ v.variant('transport', [
+ v.object({ transport: v.literal('none') }),
+ v.object({
+ transport: v.literal('smtp'),
+ from: text,
+ smtp: v.object({
+ host: text,
+ port: positiveInteger,
+ secure: v.optional(v.boolean()),
+ user: v.optional(secretReferenceSchema, {
+ from_env: DEFAULT_SECRET_NAMES.smtpUser
+ }),
+ password: v.optional(secretReferenceSchema, {
+ from_env: DEFAULT_SECRET_NAMES.smtpPassword
+ })
+ })
+ }),
+ v.object({ transport: v.literal('cloudflare'), from: text })
+ ]),
+ { transport: 'none' }
+)
+
+export const cloudDeploymentConfigSchema = v.object({
+ schema_version: v.literal(2),
+ deployment: v.object({
+ mode: v.picklist(['official', 'self-hosted']),
+ public_url: url,
+ app_url: v.optional(url),
+ indexing: v.optional(v.picklist(['allow', 'deny']), 'deny'),
+ trusted_origins: v.optional(v.array(url), []),
+ listing: v.optional(v.object({ minimum_editor_version: cloudEditorVersionSchema }))
+ }),
+ database: v.optional(v.object({ url: defaultReference(DEFAULT_SECRET_NAMES.databaseURL) }), {
+ url: { from_env: DEFAULT_SECRET_NAMES.databaseURL }
+ }),
+ authentication: v.object({
+ secret: defaultReference(DEFAULT_SECRET_NAMES.authSecret),
+ enrollment_mode: v.optional(v.picklist(['open', 'approval', 'closed']), 'open'),
+ admin_notification_emails: v.optional(v.array(v.pipe(v.string(), v.email())), []),
+ admin_user_ids: v.optional(v.array(text), []),
+ email_password: v.optional(
+ v.object({
+ enabled: v.optional(v.boolean(), false),
+ sign_up: v.optional(v.boolean(), true),
+ minimum_password_length: v.optional(
+ v.pipe(v.number(), v.integer(), v.minValue(8), v.maxValue(128)),
+ 8
+ ),
+ maximum_password_length: v.optional(
+ v.pipe(v.number(), v.integer(), v.minValue(15), v.maxValue(128)),
+ 128
+ ),
+ verification_link_expires_minutes: v.optional(positiveInteger, 60),
+ password_reset_link_expires_minutes: v.optional(positiveInteger, 60),
+ compromised_password_check: v.optional(v.boolean(), false)
+ }),
+ {
+ enabled: false,
+ sign_up: true,
+ minimum_password_length: 8,
+ maximum_password_length: 128,
+ verification_link_expires_minutes: 60,
+ password_reset_link_expires_minutes: 60,
+ compromised_password_check: false
+ }
+ ),
+ mfa: v.optional(
+ v.object({
+ deployment_admin_required: v.optional(v.boolean(), false),
+ totp_enabled: v.optional(v.boolean(), false),
+ passkeys_enabled: v.optional(v.boolean(), false),
+ recovery_codes_enabled: v.optional(v.boolean(), false),
+ trusted_device_days: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0)), 14)
+ }),
+ {
+ deployment_admin_required: false,
+ totp_enabled: false,
+ passkeys_enabled: false,
+ recovery_codes_enabled: false,
+ trusted_device_days: 14
+ }
+ ),
+ passkeys: v.optional(
+ v.object({
+ rp_id: text,
+ rp_name: v.optional(text, 'OpenPencil Cloud'),
+ origin: url
+ })
+ ),
+ captcha: v.optional(
+ v.object({
+ provider: v.literal('cloudflare-turnstile'),
+ site_key: text,
+ secret_key: defaultReference(DEFAULT_SECRET_NAMES.turnstileSecretKey),
+ allowed_hostnames: v.optional(v.array(text), [])
+ })
+ ),
+ trusted_proxies: v.optional(
+ v.object({
+ headers: v.optional(v.array(text), []),
+ addresses: v.optional(v.array(text), [])
+ }),
+ { headers: [], addresses: [] }
+ ),
+ providers: v.optional(providerSchema, {})
+ }),
+ object_storage: v.object({
+ endpoint: url,
+ region: text,
+ bucket: text,
+ credentials: v.optional(
+ v.object({
+ access_key_id: defaultReference(DEFAULT_SECRET_NAMES.s3AccessKeyId),
+ secret_access_key: defaultReference(DEFAULT_SECRET_NAMES.s3SecretAccessKey),
+ session_token: v.optional(secretReferenceSchema, {
+ from_env: DEFAULT_SECRET_NAMES.s3SessionToken
+ })
+ }),
+ {
+ access_key_id: { from_env: DEFAULT_SECRET_NAMES.s3AccessKeyId },
+ secret_access_key: { from_env: DEFAULT_SECRET_NAMES.s3SecretAccessKey }
+ }
+ ),
+ force_path_style: v.optional(v.boolean(), true),
+ checksum_verification: v.optional(v.picklist(['native', 'metadata']), 'native'),
+ server_side_encryption: v.optional(v.picklist(['AES256', 'aws:kms'])),
+ kms_key_id: v.optional(text)
+ }),
+ collaboration: v.optional(
+ v.object({ public_url: v.pipe(v.string(), v.url()), port: v.optional(positiveInteger, 1234) })
+ ),
+ email: emailSchema,
+ workers: v.optional(
+ v.object({
+ email: v.optional(
+ v.object({
+ batch_size: v.optional(positiveInteger, 50),
+ interval_ms: v.optional(positiveInteger, 30_000),
+ lease_ms: v.optional(positiveInteger, 300_000),
+ maximum_attempts: v.optional(positiveInteger, 5)
+ }),
+ { batch_size: 50, interval_ms: 30_000, lease_ms: 300_000, maximum_attempts: 5 }
+ ),
+ cleanup: v.optional(
+ v.object({
+ enabled: v.optional(v.boolean(), true),
+ batch_size: v.optional(positiveInteger, 100),
+ interval_ms: v.optional(positiveInteger, 60_000),
+ lease_ms: v.optional(positiveInteger, 300_000),
+ document_retention_days: v.optional(v.pipe(v.number(), v.minValue(0)), 30)
+ }),
+ {
+ enabled: true,
+ batch_size: 100,
+ interval_ms: 60_000,
+ lease_ms: 300_000,
+ document_retention_days: 30
+ }
+ )
+ })
+ ),
+ entitlements: v.optional(
+ v.variant('source', [
+ v.object({ source: v.literal('static'), ...staticEntitlementsTOMLSchema.entries }),
+ v.object({ source: v.literal('database') })
+ ])
+ ),
+ technical_limits: v.optional(
+ v.object({
+ maximum_upload_bytes: v.optional(positiveInteger),
+ maximum_collaboration_message_bytes: v.optional(positiveInteger),
+ maximum_connections_per_room: v.optional(positiveInteger)
+ })
+ )
+})
+
+export type CloudDeploymentConfig = v.InferOutput<typeof cloudDeploymentConfigSchema>
+/** Deployment configuration as an operator writes it, before defaults are applied. */
+export type CloudDeploymentInput = v.InferInput<typeof cloudDeploymentConfigSchema>
+export type CloudSecretReference = v.InferOutput<typeof secretReferenceSchema>
+
+export function parseCloudDeploymentSource(source: string): CloudDeploymentConfig {
+ return v.parse(cloudDeploymentConfigSchema, parseTOML(source))
+}
+
+function requiredSecret(environment: CloudEnvironment, reference: CloudSecretReference): string {
+ const value = environment[reference.from_env]
+ if (!value) throw new Error(`Required secret binding is unavailable: ${reference.from_env}`)
+ return value
+}
+
+function configuredText(
+ environment: CloudEnvironment,
+ value: string | CloudSecretReference
+): string {
+ return typeof value === 'string' ? value : requiredSecret(environment, value)
+}
+
+function optionalSecret(
+ environment: CloudEnvironment,
+ reference?: CloudSecretReference
+): string | undefined {
+ return reference ? environment[reference.from_env] : undefined
+}
+
+function staticEntitlements(config: CloudDeploymentConfig) {
+ if (config.entitlements?.source !== 'static') return undefined
+ return {
+ documents: {
+ maximumFileBytes: config.entitlements.documents?.maximum_file_bytes,
+ revisionHistory: config.entitlements.documents?.revision_history
+ },
+ storage: { maximumBytes: config.entitlements.storage?.maximum_bytes },
+ sharing: {
+ capabilityLinks: config.entitlements.sharing?.capability_links,
+ anonymousView: config.entitlements.sharing?.anonymous_view,
+ anonymousEdit: config.entitlements.sharing?.anonymous_edit,
+ guestPresence: config.entitlements.sharing?.guest_presence
+ },
+ collaboration: {
+ enabled: config.entitlements.collaboration?.enabled,
+ maximumParticipants: config.entitlements.collaboration?.maximum_participants
+ }
+ }
+}
+
+function emailConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {
+ if (config.email.transport === 'none') return { emailTransport: 'none' as const }
+ if (config.email.transport === 'cloudflare') {
+ return { emailTransport: 'cloudflare' as const, emailFrom: config.email.from }
+ }
+ return {
+ emailTransport: 'smtp' as const,
+ emailFrom: config.email.from,
+ smtpHost: config.email.smtp.host,
+ smtpPort: config.email.smtp.port,
+ smtpSecure: config.email.smtp.secure,
+ smtpUser: optionalSecret(environment, config.email.smtp.user),
+ smtpPassword: optionalSecret(environment, config.email.smtp.password)
+ }
+}
+
+function authenticationConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {
+ const google = config.authentication.providers.google
+ const apple = config.authentication.providers.apple
+ return {
+ googleClientId: google ? configuredText(environment, google.client_id) : undefined,
+ googleClientSecret: google ? requiredSecret(environment, google.client_secret) : undefined,
+ appleClientId: apple?.client_id,
+ appleTeamId: apple?.team_id,
+ appleKeyId: apple?.key_id,
+ applePrivateKey: apple ? requiredSecret(environment, apple.private_key) : undefined,
+ appleAppBundleIdentifier: apple?.app_bundle_identifier
+ }
+}
+
+function workerConfig(config: CloudDeploymentConfig) {
+ const email = config.workers?.email
+ const cleanup = config.workers?.cleanup
+ return {
+ emailBatchSize: email?.batch_size,
+ emailIntervalMs: email?.interval_ms,
+ emailLeaseDurationMs: email?.lease_ms,
+ emailMaximumAttempts: email?.maximum_attempts,
+ cleanupEnabled: cleanup?.enabled,
+ cleanupBatchSize: cleanup?.batch_size,
+ cleanupIntervalMs: cleanup?.interval_ms,
+ cleanupLeaseDurationMs: cleanup?.lease_ms,
+ documentRetentionMs: cleanup ? cleanup.document_retention_days * 86_400_000 : undefined
+ }
+}
+
+function technicalLimits(config: CloudDeploymentConfig) {
+ const limits = config.technical_limits
+ if (!limits) return undefined
+ return {
+ maximumUploadBytes: limits.maximum_upload_bytes,
+ maximumCollaborationMessageBytes: limits.maximum_collaboration_message_bytes,
+ maximumConnectionsPerRoom: limits.maximum_connections_per_room
+ }
+}
+
+export function parseCloudDeploymentConfig(
+ input: unknown,
+ environment: CloudEnvironment
+): CloudServerConfig {
+ const config = v.parse(cloudDeploymentConfigSchema, input)
+ return parseCloudServerConfig({
+ deployment: config.deployment.mode,
+ publicURL: config.deployment.public_url,
+ appURL: config.deployment.app_url,
+ indexingPolicy: config.deployment.indexing,
+ trustedOrigins: config.deployment.trusted_origins,
+ listingMinimumEditorVersion: config.deployment.listing?.minimum_editor_version,
+ databaseURL: requiredSecret(environment, config.database.url),
+ authSecret: requiredSecret(environment, config.authentication.secret),
+ enrollmentMode: config.authentication.enrollment_mode,
+ enrollmentAdminNotificationEmails: config.authentication.admin_notification_emails,
+ deploymentAdminUserIds: config.authentication.admin_user_ids,
+ emailPasswordEnabled: config.authentication.email_password.enabled,
+ emailPasswordSignUpEnabled: config.authentication.email_password.sign_up,
+ emailPasswordMinimumLength: config.authentication.email_password.minimum_password_length,
+ emailPasswordMaximumLength: config.authentication.email_password.maximum_password_length,
+ emailVerificationExpiresIn:
+ config.authentication.email_password.verification_link_expires_minutes * 60,
+ passwordResetExpiresIn:
+ config.authentication.email_password.password_reset_link_expires_minutes * 60,
+ compromisedPasswordCheck: config.authentication.email_password.compromised_password_check,
+ deploymentAdminMFARequired: config.authentication.mfa.deployment_admin_required,
+ totpEnabled: config.authentication.mfa.totp_enabled,
+ passkeysEnabled: config.authentication.mfa.passkeys_enabled,
+ recoveryCodesEnabled: config.authentication.mfa.recovery_codes_enabled,
+ mfaTrustedDeviceDays: config.authentication.mfa.trusted_device_days,
+ passkeyRPID: config.authentication.passkeys?.rp_id,
+ passkeyRPName: config.authentication.passkeys?.rp_name,
+ passkeyOrigin: config.authentication.passkeys?.origin,
+ captchaProvider: config.authentication.captcha?.provider,
+ captchaSiteKey: config.authentication.captcha?.site_key,
+ captchaSecretKey: config.authentication.captcha
+ ? requiredSecret(environment, config.authentication.captcha.secret_key)
+ : undefined,
+ captchaAllowedHostnames: config.authentication.captcha?.allowed_hostnames,
+ authTrustedIPHeaders: config.authentication.trusted_proxies.headers,
+ authTrustedProxies: config.authentication.trusted_proxies.addresses,
+ ...authenticationConfig(config, environment),
+ s3Endpoint: config.object_storage.endpoint,
+ s3Region: config.object_storage.region,
+ s3Bucket: config.object_storage.bucket,
+ s3AccessKeyId: requiredSecret(environment, config.object_storage.credentials.access_key_id),
+ s3SecretAccessKey: requiredSecret(
+ environment,
+ config.object_storage.credentials.secret_access_key
+ ),
+ s3SessionToken: environment[config.object_storage.credentials.session_token.from_env],
+ s3ForcePathStyle: config.object_storage.force_path_style,
+ s3ChecksumVerification: config.object_storage.checksum_verification,
+ s3ServerSideEncryption: config.object_storage.server_side_encryption,
+ s3KmsKeyId: config.object_storage.kms_key_id,
+ collaborationURL: config.collaboration?.public_url,
+ collaborationPort: config.collaboration?.port,
+ staticEntitlements: staticEntitlements(config),
+ ...emailConfig(config, environment),
+ ...workerConfig(config),
+ technicalLimits: technicalLimits(config)
+ })
+}
+
+export function parseCloudDeploymentTOML(
+ source: string,
+ environment: CloudEnvironment
+): CloudServerConfig {
+ return parseCloudDeploymentConfig(parseCloudDeploymentSource(source), environment)
+}
diff --git a/packages/cloud/src/server/config/index.ts b/packages/cloud/src/server/config/index.ts
new file mode 100644
index 000000000..be1b03b75
--- /dev/null
+++ b/packages/cloud/src/server/config/index.ts
@@ -0,0 +1,18 @@
+export {
+ cloudDeploymentConfigSchema,
+ parseCloudDeploymentConfig,
+ parseCloudDeploymentSource,
+ parseCloudDeploymentTOML,
+ type CloudDeploymentConfig,
+ type CloudDeploymentInput,
+ type CloudEnvironment,
+ type CloudSecretReference
+} from './deployment'
+export { CLOUD_PROTOCOL_MAX_UPLOAD_BYTES } from '#cloud/contract'
+export {
+ CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES,
+ CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM,
+ type CloudTechnicalLimits
+} from './limits'
+export { cloudDiscoveryFromConfig, configuredSocialProviders } from './public'
+export { CloudConfigError, parseCloudServerConfig, type CloudServerConfig } from './schema'
diff --git a/packages/cloud/src/server/config/limits.ts b/packages/cloud/src/server/config/limits.ts
new file mode 100644
index 000000000..dfea4a394
--- /dev/null
+++ b/packages/cloud/src/server/config/limits.ts
@@ -0,0 +1,8 @@
+export const CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES = 1024 * 1024
+export const CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM = 1000
+
+export type CloudTechnicalLimits = {
+ maximumUploadBytes: number
+ maximumCollaborationMessageBytes: number
+ maximumConnectionsPerRoom: number
+}
diff --git a/packages/cloud/src/server/config/public.ts b/packages/cloud/src/server/config/public.ts
new file mode 100644
index 000000000..fc8574aa5
--- /dev/null
+++ b/packages/cloud/src/server/config/public.ts
@@ -0,0 +1,56 @@
+import { CLOUD_PROTOCOL_VERSION, parseCloudDiscovery, type CloudDiscovery } from '#cloud/contract'
+
+import type { CloudServerConfig } from './schema'
+
+export function configuredSocialProviders(config: CloudServerConfig): Array<'apple' | 'google'> {
+ return [
+ ...(config.appleClientId ? (['apple'] as const) : []),
+ ...(config.googleClientId ? (['google'] as const) : [])
+ ]
+}
+
+export function cloudDiscoveryFromConfig(config: CloudServerConfig): CloudDiscovery {
+ const authentication: CloudDiscovery['authentication'] = {
+ socialProviders: configuredSocialProviders(config),
+ enterpriseSSO: false,
+ enrollmentMode: config.enrollmentMode
+ }
+ if (config.emailPasswordEnabled) {
+ authentication.emailPassword = {
+ signIn: true,
+ signUp: config.emailPasswordSignUpEnabled,
+ minimumPasswordLength: config.emailPasswordMinimumLength
+ }
+ if (config.captchaProvider && config.captchaSiteKey) {
+ authentication.emailPassword.captcha = {
+ provider: config.captchaProvider,
+ siteKey: config.captchaSiteKey
+ }
+ }
+ }
+ if (config.totpEnabled || config.passkeysEnabled) {
+ authentication.mfa = {
+ deploymentAdminRequired: config.deploymentAdminMFARequired,
+ totp: config.totpEnabled,
+ passkeys: config.passkeysEnabled,
+ recoveryCodes: config.totpEnabled && config.recoveryCodesEnabled
+ }
+ }
+
+ return parseCloudDiscovery({
+ protocolVersion: CLOUD_PROTOCOL_VERSION,
+ deployment: config.deployment,
+ apiURL: new URL('/api', config.publicURL).href.replace(/\/$/, ''),
+ authURL: new URL('/api/auth', config.publicURL).href.replace(/\/$/, ''),
+ appURL: config.appURL ?? config.publicURL,
+ authentication,
+ capabilities: {
+ documents: true,
+ workspaces: true,
+ collaboration: true
+ },
+ listing: config.listingMinimumEditorVersion
+ ? { minimumEditorVersion: config.listingMinimumEditorVersion }
+ : undefined
+ })
+}
diff --git a/packages/cloud/src/server/config/schema.ts b/packages/cloud/src/server/config/schema.ts
new file mode 100644
index 000000000..d7695032c
--- /dev/null
+++ b/packages/cloud/src/server/config/schema.ts
@@ -0,0 +1,255 @@
+import { CLOUD_PROTOCOL_MAX_UPLOAD_BYTES, cloudEditorVersionSchema } from '#cloud/contract'
+import { staticEntitlementsSchema } from '#cloud/server/policy/static'
+import * as v from 'valibot'
+
+import {
+ CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES,
+ CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM
+} from './limits'
+
+const httpURLSchema = v.pipe(
+ v.string(),
+ v.url(),
+ v.check((value) => {
+ const protocol = new URL(value).protocol
+ return protocol === 'https:' || protocol === 'http:'
+ }, 'URL must use HTTP or HTTPS')
+)
+
+const websocketURLSchema = v.pipe(
+ v.string(),
+ v.url(),
+ v.check((value) => {
+ const protocol = new URL(value).protocol
+ return protocol === 'ws:' || protocol === 'wss:'
+ }, 'URL must use WS or WSS')
+)
+
+const optionalTextSchema = v.optional(v.pipe(v.string(), v.trim(), v.minLength(1)))
+
+const rawCloudServerConfigSchema = v.object({
+ deployment: v.picklist(['official', 'self-hosted']),
+ publicURL: httpURLSchema,
+ appURL: v.optional(httpURLSchema),
+ listingMinimumEditorVersion: v.optional(cloudEditorVersionSchema),
+ collaborationURL: v.optional(websocketURLSchema),
+ collaborationPort: v.optional(
+ v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(65_535)),
+ 1234
+ ),
+ technicalLimits: v.optional(
+ v.object({
+ maximumUploadBytes: v.optional(
+ v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES)),
+ CLOUD_PROTOCOL_MAX_UPLOAD_BYTES
+ ),
+ maximumCollaborationMessageBytes: v.optional(
+ v.pipe(v.number(), v.integer(), v.minValue(1024)),
+ CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES
+ ),
+ maximumConnectionsPerRoom: v.optional(
+ v.pipe(v.number(), v.integer(), v.minValue(1)),
+ CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM
+ )
+ }),
+ {
+ maximumUploadBytes: CLOUD_PROTOCOL_MAX_UPLOAD_BYTES,
+ maximumCollaborationMessageBytes: CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES,
+ maximumConnectionsPerRoom: CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM
+ }
+ ),
+ staticEntitlements: v.optional(staticEntitlementsSchema),
+ databaseURL: v.pipe(v.string(), v.url()),
+ authSecret: v.pipe(v.string(), v.minLength(32)),
+ trustedOrigins: v.optional(v.array(httpURLSchema), []),
+ authTrustedIPHeaders: v.optional(v.array(v.pipe(v.string(), v.trim(), v.minLength(1))), []),
+ authTrustedProxies: v.optional(v.array(v.pipe(v.string(), v.trim(), v.minLength(1))), []),
+ enrollmentMode: v.optional(v.picklist(['open', 'approval', 'closed']), 'open'),
+ indexingPolicy: v.optional(v.picklist(['allow', 'deny']), 'deny'),
+ enrollmentAdminNotificationEmails: v.optional(
+ v.array(v.pipe(v.string(), v.trim(), v.email())),
+ []
+ ),
+ deploymentAdminUserIds: v.optional(v.array(v.pipe(v.string(), v.trim(), v.minLength(1))), []),
+ emailPasswordEnabled: v.optional(v.boolean(), false),
+ emailPasswordSignUpEnabled: v.optional(v.boolean(), true),
+ emailPasswordMinimumLength: v.optional(
+ v.pipe(v.number(), v.integer(), v.minValue(8), v.maxValue(128)),
+ 8
+ ),
+ emailPasswordMaximumLength: v.optional(
+ v.pipe(v.number(), v.integer(), v.minValue(15), v.maxValue(128)),
+ 128
+ ),
+ emailVerificationExpiresIn: v.optional(v.pipe(v.number(), v.integer(), v.minValue(60)), 3600),
+ passwordResetExpiresIn: v.optional(v.pipe(v.number(), v.integer(), v.minValue(60)), 3600),
+ compromisedPasswordCheck: v.optional(v.boolean(), false),
+ deploymentAdminMFARequired: v.optional(v.boolean(), false),
+ totpEnabled: v.optional(v.boolean(), false),
+ passkeysEnabled: v.optional(v.boolean(), false),
+ recoveryCodesEnabled: v.optional(v.boolean(), false),
+ mfaTrustedDeviceDays: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0)), 14),
+ passkeyRPID: optionalTextSchema,
+ passkeyRPName: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1)), 'OpenPencil Cloud'),
+ passkeyOrigin: v.optional(httpURLSchema),
+ captchaProvider: v.optional(v.literal('cloudflare-turnstile')),
+ captchaSiteKey: optionalTextSchema,
+ captchaSecretKey: optionalTextSchema,
+ captchaAllowedHostnames: v.optional(v.array(v.pipe(v.string(), v.trim(), v.minLength(1))), []),
+ googleClientId: optionalTextSchema,
+ googleClientSecret: optionalTextSchema,
+ appleClientId: optionalTextSchema,
+ appleTeamId: optionalTextSchema,
+ appleKeyId: optionalTextSchema,
+ applePrivateKey: optionalTextSchema,
+ appleAppBundleIdentifier: optionalTextSchema,
+ s3Endpoint: httpURLSchema,
+ s3Region: v.pipe(v.string(), v.trim(), v.minLength(1)),
+ s3Bucket: v.pipe(v.string(), v.trim(), v.minLength(1)),
+ s3AccessKeyId: v.pipe(v.string(), v.trim(), v.minLength(1)),
+ s3SecretAccessKey: v.pipe(v.string(), v.minLength(1)),
+ s3SessionToken: optionalTextSchema,
+ s3ForcePathStyle: v.optional(v.boolean(), true),
+ s3ChecksumVerification: v.optional(v.picklist(['native', 'metadata']), 'native'),
+ s3ServerSideEncryption: v.optional(v.picklist(['AES256', 'aws:kms'])),
+ s3KmsKeyId: optionalTextSchema,
+ smtpHost: optionalTextSchema,
+ smtpPort: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(65_535))),
+ smtpSecure: v.optional(v.boolean()),
+ smtpUser: optionalTextSchema,
+ smtpPassword: optionalTextSchema,
+ emailFrom: optionalTextSchema,
+ emailTransport: v.optional(v.picklist(['none', 'smtp', 'cloudflare']), 'none'),
+ emailBatchSize: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1000)), 50),
+ emailIntervalMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1000)), 30_000),
+ emailLeaseDurationMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1000)), 5 * 60_000),
+ emailMaximumAttempts: v.optional(
+ v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(20)),
+ 5
+ ),
+ cleanupEnabled: v.optional(v.boolean(), true),
+ cleanupBatchSize: v.optional(
+ v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1000)),
+ 100
+ ),
+ cleanupIntervalMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1000)), 60_000),
+ cleanupLeaseDurationMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1000)), 5 * 60_000),
+ documentRetentionMs: v.optional(
+ v.pipe(v.number(), v.integer(), v.minValue(0)),
+ 30 * 24 * 60 * 60_000
+ )
+})
+
+export type CloudServerConfig = v.InferOutput<typeof rawCloudServerConfigSchema>
+
+export class CloudConfigError extends Error {
+ constructor(message: string) {
+ super(message)
+ this.name = 'CloudConfigError'
+ }
+}
+
+function requireTogether(
+ config: CloudServerConfig,
+ label: string,
+ fields: Array<keyof CloudServerConfig>
+): void {
+ const configured = fields.filter((field) => Boolean(config[field]))
+ if (configured.length !== 0 && configured.length !== fields.length) {
+ throw new CloudConfigError(`${label} configuration must provide ${fields.join(', ')}`)
+ }
+}
+
+function validateAuthenticationConfig(config: CloudServerConfig): void {
+ if (config.emailPasswordMinimumLength > config.emailPasswordMaximumLength) {
+ throw new CloudConfigError('Minimum password length cannot exceed maximum password length')
+ }
+ if (config.emailPasswordEnabled && config.emailTransport === 'none') {
+ throw new CloudConfigError(
+ 'Email and password authentication requires transactional email delivery'
+ )
+ }
+ if (config.deploymentAdminMFARequired && !config.totpEnabled && !config.passkeysEnabled) {
+ throw new CloudConfigError('Deployment administrator MFA requires TOTP or passkeys')
+ }
+ if (config.recoveryCodesEnabled && !config.totpEnabled) {
+ throw new CloudConfigError('MFA recovery codes require TOTP')
+ }
+ if (config.passkeysEnabled) {
+ const publicURL = new URL(config.publicURL)
+ if (config.passkeyOrigin && new URL(config.passkeyOrigin).origin !== publicURL.origin) {
+ throw new CloudConfigError('Passkey origin must match the Cloud public URL origin')
+ }
+ if (config.passkeyRPID && config.passkeyRPID !== publicURL.hostname) {
+ throw new CloudConfigError('Passkey RP ID must match the Cloud public URL hostname')
+ }
+ }
+ requireTogether(config, 'CAPTCHA', ['captchaProvider', 'captchaSiteKey', 'captchaSecretKey'])
+ if (
+ config.deployment === 'official' &&
+ config.emailPasswordEnabled &&
+ config.emailPasswordSignUpEnabled &&
+ (!config.compromisedPasswordCheck || !config.captchaProvider)
+ ) {
+ throw new CloudConfigError(
+ 'Official email and password sign-up requires compromised-password checks and CAPTCHA'
+ )
+ }
+ requireTogether(config, 'Google', ['googleClientId', 'googleClientSecret'])
+ requireTogether(config, 'Apple', [
+ 'appleClientId',
+ 'appleTeamId',
+ 'appleKeyId',
+ 'applePrivateKey'
+ ])
+}
+
+function validateEmailConfig(config: CloudServerConfig): void {
+ requireTogether(config, 'SMTP', ['smtpHost', 'smtpPort'])
+ requireTogether(config, 'SMTP authentication', ['smtpUser', 'smtpPassword'])
+ if (config.emailTransport === 'smtp' && !config.smtpHost) {
+ throw new CloudConfigError('SMTP email transport requires SMTP configuration')
+ }
+ if (config.smtpHost && config.emailTransport !== 'smtp') {
+ throw new CloudConfigError('SMTP configuration requires the smtp email transport')
+ }
+ if (config.emailTransport !== 'none' && !config.emailFrom) {
+ throw new CloudConfigError('Transactional email delivery requires an email from address')
+ }
+ if (config.deployment === 'official' && config.smtpHost && config.smtpSecure === false) {
+ throw new CloudConfigError('Official SMTP delivery must use a secure connection')
+ }
+}
+
+function validateObjectStorageConfig(config: CloudServerConfig): void {
+ if (config.s3KmsKeyId && config.s3ServerSideEncryption !== 'aws:kms') {
+ throw new CloudConfigError('S3 KMS key ID requires aws:kms server-side encryption')
+ }
+ const endpointHost = new URL(config.s3Endpoint).hostname
+ if (!endpointHost.endsWith('.r2.cloudflarestorage.com')) return
+ if (config.s3Region !== 'auto') {
+ throw new CloudConfigError('Cloudflare R2 S3 region must be auto')
+ }
+ if (config.s3ForcePathStyle) {
+ throw new CloudConfigError('Cloudflare R2 S3 endpoint must disable path-style requests')
+ }
+ if (config.s3ChecksumVerification !== 'metadata') {
+ throw new CloudConfigError('Cloudflare R2 checksum verification must use metadata')
+ }
+}
+
+export function parseCloudServerConfig(input: unknown): CloudServerConfig {
+ const config = v.parse(rawCloudServerConfigSchema, input)
+ if (
+ config.appURL &&
+ !config.trustedOrigins.some(
+ (origin) => new URL(origin).origin === new URL(config.appURL ?? '').origin
+ )
+ ) {
+ throw new CloudConfigError('Cloud app URL must be included in trusted origins')
+ }
+ validateAuthenticationConfig(config)
+ validateEmailConfig(config)
+ validateObjectStorageConfig(config)
+ return config
+}
diff --git a/packages/cloud/src/server/db/database.ts b/packages/cloud/src/server/db/database.ts
new file mode 100644
index 000000000..906497ec6
--- /dev/null
+++ b/packages/cloud/src/server/db/database.ts
@@ -0,0 +1,15 @@
+import type { Dialect } from 'kysely'
+import { CamelCasePlugin, Kysely } from 'kysely'
+
+import type { CloudDatabase } from './schema'
+
+export type CloudDatabaseOptions = {
+ dialect: Dialect
+}
+
+export function createCloudDatabase(options: CloudDatabaseOptions): Kysely<CloudDatabase> {
+ return new Kysely<CloudDatabase>({
+ dialect: options.dialect,
+ plugins: [new CamelCasePlugin()]
+ })
+}
diff --git a/packages/cloud/src/server/db/expressions.ts b/packages/cloud/src/server/db/expressions.ts
new file mode 100644
index 000000000..8e1821619
--- /dev/null
+++ b/packages/cloud/src/server/db/expressions.ts
@@ -0,0 +1,13 @@
+import { sql, type Expression } from 'kysely'
+
+export const CURRENT_TIMESTAMP = sql<Date>`current_timestamp`
+export const EMPTY_JSON_OBJECT = sql`'{}'::jsonb`
+
+const CHECK_VALUE_PATTERN = /^[a-z][a-z0-9-]*$/
+
+export function checkColumnIn(column: string, values: readonly string[]): Expression<boolean> {
+ if (values.length === 0 || values.some((value) => !CHECK_VALUE_PATTERN.test(value))) {
+ throw new Error('Check constraint values must be non-empty lowercase identifiers')
+ }
+ return sql<boolean>`${sql.ref(column)} in (${sql.join(values.map((value) => sql.lit(value)))})`
+}
diff --git a/packages/cloud/src/server/db/index.ts b/packages/cloud/src/server/db/index.ts
new file mode 100644
index 000000000..10a42329d
--- /dev/null
+++ b/packages/cloud/src/server/db/index.ts
@@ -0,0 +1,20 @@
+export { createCloudDatabase, type CloudDatabaseOptions } from './database'
+export { migrateCloudDatabase } from './migrate'
+export type {
+ CloudDatabase,
+ Document,
+ DocumentRevision,
+ NewDocument,
+ NewDocumentRevision,
+ NewStorageObject,
+ NewTransactionalEmail,
+ NewUpload,
+ NewWorkspace,
+ StorageObject,
+ TransactionalEmail,
+ TransactionalEmailStatus,
+ Upload,
+ UploadStatus,
+ Workspace,
+ WorkspaceUpdate
+} from './schema'
diff --git a/packages/cloud/src/server/db/migrate.ts b/packages/cloud/src/server/db/migrate.ts
new file mode 100644
index 000000000..ec6b8020a
--- /dev/null
+++ b/packages/cloud/src/server/db/migrate.ts
@@ -0,0 +1,159 @@
+import type { Kysely } from 'kysely'
+import { Migrator, type Migration, type MigrationProvider } from 'kysely/migration'
+
+import * as foundation from './migrations/001_foundation'
+import * as cleanupClaims from './migrations/002_upload_cleanup_claims'
+import * as documentCleanupClaims from './migrations/003_document_cleanup_claims'
+import * as documentSharing from './migrations/004_document_sharing'
+import * as documentCollaborationEpoch from './migrations/005_document_collaboration_epoch'
+import * as invitationContinuation from './migrations/006_invitation_continuation'
+import * as collaborationState from './migrations/007_collaboration_state'
+import * as storageReservations from './migrations/008_storage_reservations'
+import * as workspaceEntitlements from './migrations/009_workspace_entitlements'
+import * as uploadFinalization from './migrations/010_upload_finalization'
+import * as uploadFinalizationLease from './migrations/011_upload_finalization_lease'
+import * as transactionalEmail from './migrations/012_transactional_email'
+import * as adminEnrollment from './migrations/013_admin_enrollment'
+import * as enrollmentEmailKinds from './migrations/014_enrollment_email_kinds'
+import * as cloudRateLimit from './migrations/015_cloud_rate_limit'
+import * as authSchema from './migrations/016_auth_schema'
+import * as authenticationEmailKinds from './migrations/017_authentication_email_kinds'
+import * as authenticationMFA from './migrations/018_authentication_mfa'
+import * as betterAuthAccountIssuer from './migrations/019_better_auth_account_issuer'
+import * as workspaceInvitations from './migrations/020_workspace_invitations'
+import type { CloudDatabase } from './schema'
+
+const migrations: Record<string, Migration> = {
+ '001_foundation': foundation,
+ '002_upload_cleanup_claims': cleanupClaims,
+ '003_document_cleanup_claims': documentCleanupClaims,
+ '004_document_sharing': documentSharing,
+ '005_document_collaboration_epoch': documentCollaborationEpoch,
+ '006_invitation_continuation': invitationContinuation,
+ '007_collaboration_state': collaborationState,
+ '008_storage_reservations': storageReservations,
+ '009_workspace_entitlements': workspaceEntitlements,
+ '010_upload_finalization': uploadFinalization,
+ '011_upload_finalization_lease': uploadFinalizationLease,
+ '012_transactional_email': transactionalEmail,
+ '013_admin_enrollment': adminEnrollment,
+ '014_enrollment_email_kinds': enrollmentEmailKinds,
+ '015_cloud_rate_limit': cloudRateLimit,
+ '016_auth_schema': authSchema,
+ '017_authentication_email_kinds': authenticationEmailKinds,
+ '018_authentication_mfa': authenticationMFA,
+ '019_better_auth_account_issuer': betterAuthAccountIssuer,
+ '020_workspace_invitations': workspaceInvitations
+}
+
+class CloudMigrationProvider implements MigrationProvider {
+ async getMigrations(): Promise<Record<string, Migration>> {
+ return migrations
+ }
+}
+
+export type CloudAuthMigration = {
+ run(): Promise<void>
+ schemaVersion: string
+}
+
+const REQUIRED_AUTH_SCHEMA: Record<string, string[]> = {
+ user: [
+ 'id',
+ 'name',
+ 'email',
+ 'email_verified',
+ 'created_at',
+ 'updated_at',
+ 'role',
+ 'banned',
+ 'two_factor_enabled'
+ ],
+ session: ['id', 'expires_at', 'token', 'user_id', 'impersonated_by'],
+ account: ['id', 'account_id', 'provider_id', 'user_id'],
+ verification: ['id', 'identifier', 'value', 'expires_at'],
+ device_code: ['id', 'device_code', 'user_code', 'status', 'client_id'],
+ rate_limit: ['id', 'key', 'count', 'last_request'],
+ two_factor: [
+ 'id',
+ 'secret',
+ 'backup_codes',
+ 'user_id',
+ 'verified',
+ 'failed_verification_count',
+ 'locked_until'
+ ],
+ passkey: ['id', 'public_key', 'user_id', 'credential_id', 'counter', 'device_type', 'backed_up']
+}
+
+async function existingAuthSchema(
+ database: Kysely<CloudDatabase>
+): Promise<Map<string, Set<string>>> {
+ const tables = await database.introspection.getTables()
+ return new Map(
+ tables
+ .filter((table) => Object.hasOwn(REQUIRED_AUTH_SCHEMA, table.name))
+ .map((table) => [table.name, new Set(table.columns.map((column) => column.name))])
+ )
+}
+
+async function migrateAuthSchema(
+ database: Kysely<CloudDatabase>,
+ migration: CloudAuthMigration
+): Promise<void> {
+ const recorded = await database
+ .selectFrom('cloudAuthSchema')
+ .select('version')
+ .where('id', '=', 'better-auth')
+ .executeTakeFirst()
+ if (recorded) {
+ if (recorded.version !== migration.schemaVersion) {
+ throw new Error(
+ `Better Auth schema ${recorded.version} requires an explicit migration to ${migration.schemaVersion}`
+ )
+ }
+ return
+ }
+
+ const existing = await existingAuthSchema(database)
+ if (existing.size === 0) {
+ await migration.run()
+ } else {
+ const missing = Object.entries(REQUIRED_AUTH_SCHEMA).flatMap(([table, requiredColumns]) => {
+ const columns = existing.get(table)
+ if (!columns) return [table]
+ return requiredColumns
+ .filter((column) => !columns.has(column))
+ .map((column) => `${table}.${column}`)
+ })
+ if (missing.length > 0) {
+ throw new Error(`Existing Better Auth schema is incomplete: ${missing.join(', ')}`)
+ }
+ }
+
+ await database
+ .insertInto('cloudAuthSchema')
+ .values({ id: 'better-auth', version: migration.schemaVersion, updatedAt: new Date() })
+ .execute()
+}
+
+export async function migrateCloudDatabase(
+ database: Kysely<CloudDatabase>,
+ authMigration?: CloudAuthMigration
+): Promise<void> {
+ const migrator = new Migrator({
+ db: database,
+ provider: new CloudMigrationProvider()
+ })
+ const result = await migrator.migrateToLatest()
+ const failed = result.results?.find((migration) => migration.status === 'Error')
+ if (result.error || failed) {
+ throw new AggregateError(
+ [result.error, failed ? new Error(`Migration failed: ${failed.migrationName}`) : null].filter(
+ (error): error is Error => error instanceof Error
+ ),
+ 'OpenPencil Cloud database migration failed'
+ )
+ }
+ if (authMigration) await migrateAuthSchema(database, authMigration)
+}
diff --git a/packages/cloud/src/server/db/migrations/001_foundation.ts b/packages/cloud/src/server/db/migrations/001_foundation.ts
new file mode 100644
index 000000000..c6ec8513f
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/001_foundation.ts
@@ -0,0 +1,164 @@
+import { checkColumnIn, CURRENT_TIMESTAMP } from '#cloud/server/db/expressions'
+import { type Kysely, sql } from 'kysely'
+
+import { addCurrentTimestampColumns } from './helpers'
+
+const UPDATED_AT_TRIGGER = 'openpencil_set_updated_at'
+
+export async function up(database: Kysely<unknown>): Promise<void> {
+ await database.schema
+ .createTable('workspace')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('name', 'text', (column) => column.notNull())
+ .addColumn('slug', 'text', (column) => column.notNull().unique())
+ .addColumn('created_by', 'text', (column) => column.notNull())
+ .execute()
+ await addCurrentTimestampColumns(database, 'workspace', ['created_at', 'updated_at'])
+
+ await database.schema
+ .createTable('workspace_member')
+ .addColumn('workspace_id', 'uuid', (column) =>
+ column.references('workspace.id').onDelete('cascade').notNull()
+ )
+ .addColumn('user_id', 'text', (column) => column.notNull())
+ .addColumn('role', 'text', (column) => column.notNull())
+ .addPrimaryKeyConstraint('workspace_member_primary', ['workspace_id', 'user_id'])
+ .addCheckConstraint(
+ 'workspace_member_role_check',
+ checkColumnIn('role', ['admin', 'editor', 'viewer'])
+ )
+ .execute()
+ await addCurrentTimestampColumns(database, 'workspace_member', ['created_at'])
+
+ await database.schema
+ .createTable('document')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('workspace_id', 'uuid', (column) =>
+ column.references('workspace.id').onDelete('cascade').notNull()
+ )
+ .addColumn('name', 'text', (column) => column.notNull())
+ .addColumn('current_revision_id', 'uuid')
+ .addColumn('version', 'integer', (column) => column.notNull().defaultTo(0))
+ .addColumn('created_by', 'text', (column) => column.notNull())
+ .addColumn('deleted_at', 'timestamptz')
+ .execute()
+ await addCurrentTimestampColumns(database, 'document', ['created_at', 'updated_at'])
+
+ await database.schema
+ .createTable('storage_object')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('object_key', 'text', (column) => column.notNull().unique())
+ .addColumn('checksum', 'text', (column) => column.notNull())
+ .addColumn('byte_size', 'bigint', (column) => column.notNull())
+ .addColumn('content_type', 'text', (column) => column.notNull())
+ .addColumn('created_at', 'timestamptz', (column) =>
+ column.notNull().defaultTo(CURRENT_TIMESTAMP)
+ )
+ .execute()
+
+ await database.schema
+ .createTable('document_revision')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('document_id', 'uuid', (column) =>
+ column.references('document.id').onDelete('cascade').notNull()
+ )
+ .addColumn('parent_revision_id', 'uuid', (column) =>
+ column.references('document_revision.id').onDelete('set null')
+ )
+ .addColumn('storage_object_id', 'uuid', (column) =>
+ column.references('storage_object.id').onDelete('restrict').notNull()
+ )
+ .addColumn('created_by', 'text', (column) => column.notNull())
+ .addColumn('created_at', 'timestamptz', (column) =>
+ column.notNull().defaultTo(CURRENT_TIMESTAMP)
+ )
+ .execute()
+
+ await database.schema
+ .alterTable('document')
+ .addForeignKeyConstraint(
+ 'document_current_revision_foreign',
+ ['current_revision_id'],
+ 'document_revision',
+ ['id'],
+ (constraint) => constraint.onDelete('set null')
+ )
+ .execute()
+
+ await database.schema
+ .createTable('upload')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('document_id', 'uuid', (column) =>
+ column.references('document.id').onDelete('cascade').notNull()
+ )
+ .addColumn('base_revision_id', 'uuid', (column) =>
+ column.references('document_revision.id').onDelete('set null')
+ )
+ .addColumn('object_key', 'text', (column) => column.notNull().unique())
+ .addColumn('status', 'text', (column) => column.notNull())
+ .addColumn('checksum', 'text', (column) => column.notNull())
+ .addColumn('created_by', 'text', (column) => column.notNull())
+ .addColumn('byte_size', 'bigint', (column) => column.notNull())
+ .addColumn('created_at', 'timestamptz', (column) =>
+ column.notNull().defaultTo(CURRENT_TIMESTAMP)
+ )
+ .addColumn('content_type', 'text', (column) => column.notNull())
+ .addColumn('multipart_upload_id', 'text')
+ .addColumn('expires_at', 'timestamptz', (column) => column.notNull())
+ .addCheckConstraint(
+ 'upload_status_check',
+ checkColumnIn('status', ['pending', 'committed', 'abandoned'])
+ )
+ .execute()
+
+ await database.schema
+ .createIndex('workspace_member_user_index')
+ .on('workspace_member')
+ .column('user_id')
+ .execute()
+ await database.schema
+ .createIndex('document_workspace_index')
+ .on('document')
+ .columns(['workspace_id', 'updated_at'])
+ .execute()
+ await database.schema
+ .createIndex('document_revision_document_index')
+ .on('document_revision')
+ .columns(['document_id', 'created_at'])
+ .execute()
+ await database.schema
+ .createIndex('upload_expiration_index')
+ .on('upload')
+ .columns(['status', 'expires_at'])
+ .execute()
+
+ await sql`
+ create function ${sql.id(UPDATED_AT_TRIGGER)}() returns trigger as $$
+ begin
+ new.updated_at = now();
+ return new;
+ end;
+ $$ language plpgsql
+ `.execute(database)
+ for (const table of ['workspace', 'document']) {
+ await sql`
+ create trigger ${sql.id(`${table}_updated_at`)}
+ before update on ${sql.table(table)}
+ for each row execute function ${sql.id(UPDATED_AT_TRIGGER)}()
+ `.execute(database)
+ }
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await database.schema.dropTable('upload').ifExists().execute()
+ await database.schema
+ .alterTable('document')
+ .dropConstraint('document_current_revision_foreign')
+ .execute()
+ await database.schema.dropTable('document_revision').ifExists().execute()
+ await database.schema.dropTable('storage_object').ifExists().execute()
+ await database.schema.dropTable('document').ifExists().execute()
+ await database.schema.dropTable('workspace_member').ifExists().execute()
+ await database.schema.dropTable('workspace').ifExists().execute()
+ await sql`drop function if exists ${sql.id(UPDATED_AT_TRIGGER)}()`.execute(database)
+}
diff --git a/packages/cloud/src/server/db/migrations/002_upload_cleanup_claims.ts b/packages/cloud/src/server/db/migrations/002_upload_cleanup_claims.ts
new file mode 100644
index 000000000..160beae70
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/002_upload_cleanup_claims.ts
@@ -0,0 +1,34 @@
+import { checkColumnIn } from '#cloud/server/db/expressions'
+import type { Kysely } from 'kysely'
+
+export async function up(database: Kysely<unknown>): Promise<void> {
+ await database.schema
+ .alterTable('upload')
+ .addColumn('cleanup_claim_id', 'uuid')
+ .addColumn('cleanup_claimed_at', 'timestamptz')
+ .execute()
+ await database.schema.alterTable('upload').dropConstraint('upload_status_check').execute()
+ await database.schema
+ .alterTable('upload')
+ .addCheckConstraint(
+ 'upload_status_check',
+ checkColumnIn('status', ['pending', 'cleaning', 'committed', 'abandoned'])
+ )
+ .execute()
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await database.schema.alterTable('upload').dropConstraint('upload_status_check').execute()
+ await database.schema
+ .alterTable('upload')
+ .addCheckConstraint(
+ 'upload_status_check',
+ checkColumnIn('status', ['pending', 'committed', 'abandoned'])
+ )
+ .execute()
+ await database.schema
+ .alterTable('upload')
+ .dropColumn('cleanup_claimed_at')
+ .dropColumn('cleanup_claim_id')
+ .execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/003_document_cleanup_claims.ts b/packages/cloud/src/server/db/migrations/003_document_cleanup_claims.ts
new file mode 100644
index 000000000..f7bb0b8e6
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/003_document_cleanup_claims.ts
@@ -0,0 +1,23 @@
+import type { Kysely } from 'kysely'
+
+export async function up(database: Kysely<unknown>): Promise<void> {
+ await database.schema
+ .alterTable('document')
+ .addColumn('cleanup_claim_id', 'uuid')
+ .addColumn('cleanup_claimed_at', 'timestamptz')
+ .execute()
+ await database.schema
+ .createIndex('document_cleanup_index')
+ .on('document')
+ .columns(['deleted_at', 'cleanup_claimed_at'])
+ .execute()
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await database.schema.dropIndex('document_cleanup_index').ifExists().execute()
+ await database.schema
+ .alterTable('document')
+ .dropColumn('cleanup_claimed_at')
+ .dropColumn('cleanup_claim_id')
+ .execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/004_document_sharing.ts b/packages/cloud/src/server/db/migrations/004_document_sharing.ts
new file mode 100644
index 000000000..744982554
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/004_document_sharing.ts
@@ -0,0 +1,82 @@
+import { checkColumnIn } from '#cloud/server/db/expressions'
+import type { Kysely } from 'kysely'
+
+import { addCurrentTimestampColumns, addInvitationColumns } from './helpers'
+
+export async function up(database: Kysely<unknown>): Promise<void> {
+ await database.schema
+ .createTable('document_share')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('document_id', 'uuid', (column) =>
+ column.references('document.id').onDelete('cascade').notNull()
+ )
+ .addColumn('permission', 'text', (column) => column.notNull())
+ .addColumn('secret_hash', 'text', (column) => column.notNull())
+ .addColumn('room_epoch', 'integer', (column) => column.notNull().defaultTo(0))
+ .addColumn('created_by', 'text', (column) => column.notNull())
+ .addColumn('expires_at', 'timestamptz')
+ .addColumn('revoked_at', 'timestamptz')
+ .addColumn('last_used_at', 'timestamptz')
+ .addCheckConstraint(
+ 'document_share_permission_check',
+ checkColumnIn('permission', ['view', 'edit'])
+ )
+ .execute()
+ await addCurrentTimestampColumns(database, 'document_share', ['created_at', 'updated_at'])
+
+ await database.schema
+ .createTable('document_grant')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('document_id', 'uuid', (column) =>
+ column.references('document.id').onDelete('cascade').notNull()
+ )
+ .addColumn('user_id', 'text', (column) => column.notNull())
+ .addColumn('permission', 'text', (column) => column.notNull())
+ .addColumn('created_by', 'text', (column) => column.notNull())
+ .addColumn('revoked_at', 'timestamptz')
+ .addUniqueConstraint('document_grant_document_user_unique', ['document_id', 'user_id'])
+ .addCheckConstraint(
+ 'document_grant_permission_check',
+ checkColumnIn('permission', ['view', 'edit'])
+ )
+ .execute()
+ await addCurrentTimestampColumns(database, 'document_grant', ['created_at', 'updated_at'])
+
+ await addInvitationColumns(
+ database.schema
+ .createTable('document_invitation')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('document_id', 'uuid', (column) =>
+ column.references('document.id').onDelete('cascade').notNull()
+ ),
+ 'permission'
+ )
+ .addCheckConstraint(
+ 'document_invitation_permission_check',
+ checkColumnIn('permission', ['view', 'edit'])
+ )
+ .execute()
+ await addCurrentTimestampColumns(database, 'document_invitation', ['invited_at'])
+
+ await database.schema
+ .createIndex('document_share_document_index')
+ .on('document_share')
+ .columns(['document_id', 'revoked_at'])
+ .execute()
+ await database.schema
+ .createIndex('document_grant_user_index')
+ .on('document_grant')
+ .columns(['user_id', 'document_id'])
+ .execute()
+ await database.schema
+ .createIndex('document_invitation_document_index')
+ .on('document_invitation')
+ .columns(['document_id', 'revoked_at'])
+ .execute()
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await database.schema.dropTable('document_invitation').ifExists().execute()
+ await database.schema.dropTable('document_grant').ifExists().execute()
+ await database.schema.dropTable('document_share').ifExists().execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/005_document_collaboration_epoch.ts b/packages/cloud/src/server/db/migrations/005_document_collaboration_epoch.ts
new file mode 100644
index 000000000..a06b89c9c
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/005_document_collaboration_epoch.ts
@@ -0,0 +1,13 @@
+import type { CloudDatabase } from '#cloud/server/db/schema'
+import type { Kysely } from 'kysely'
+
+export async function up(database: Kysely<CloudDatabase>): Promise<void> {
+ await database.schema
+ .alterTable('document')
+ .addColumn('collaborationEpoch', 'integer', (column) => column.notNull().defaultTo(0))
+ .execute()
+}
+
+export async function down(database: Kysely<CloudDatabase>): Promise<void> {
+ await database.schema.alterTable('document').dropColumn('collaborationEpoch').execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/006_invitation_continuation.ts b/packages/cloud/src/server/db/migrations/006_invitation_continuation.ts
new file mode 100644
index 000000000..8290d05ec
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/006_invitation_continuation.ts
@@ -0,0 +1,27 @@
+import type { CloudDatabase } from '#cloud/server/db/schema'
+import type { Kysely } from 'kysely'
+
+export async function up(database: Kysely<CloudDatabase>): Promise<void> {
+ await database.schema
+ .createTable('invitationContinuation')
+ .addColumn('id', 'text', (column) => column.primaryKey())
+ .addColumn('invitationId', 'uuid', (column) =>
+ column.notNull().references('documentInvitation.id').onDelete('cascade')
+ )
+ .addColumn('tokenEncrypted', 'text', (column) => column.notNull())
+ .addColumn('expiresAt', 'timestamptz', (column) => column.notNull())
+ .addColumn('consumedAt', 'timestamptz')
+ .addColumn('createdAt', 'timestamptz', (column) =>
+ column.notNull().defaultTo(database.fn('now'))
+ )
+ .execute()
+ await database.schema
+ .createIndex('invitationContinuationExpiryIndex')
+ .on('invitationContinuation')
+ .column('expiresAt')
+ .execute()
+}
+
+export async function down(database: Kysely<CloudDatabase>): Promise<void> {
+ await database.schema.dropTable('invitationContinuation').execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/007_collaboration_state.ts b/packages/cloud/src/server/db/migrations/007_collaboration_state.ts
new file mode 100644
index 000000000..3bf4b7906
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/007_collaboration_state.ts
@@ -0,0 +1,25 @@
+import type { CloudDatabase } from '#cloud/server/db/schema'
+import type { Kysely } from 'kysely'
+
+export async function up(database: Kysely<CloudDatabase>): Promise<void> {
+ await database.schema
+ .createTable('documentCollaborationState')
+ .addColumn('documentId', 'uuid', (column) =>
+ column.notNull().references('document.id').onDelete('cascade')
+ )
+ .addColumn('roomEpoch', 'integer', (column) => column.notNull())
+ .addColumn('state', 'bytea', (column) => column.notNull())
+ .addColumn('version', 'integer', (column) => column.notNull().defaultTo(1))
+ .addColumn('createdAt', 'timestamptz', (column) =>
+ column.notNull().defaultTo(database.fn('now'))
+ )
+ .addColumn('updatedAt', 'timestamptz', (column) =>
+ column.notNull().defaultTo(database.fn('now'))
+ )
+ .addPrimaryKeyConstraint('documentCollaborationStatePrimary', ['documentId', 'roomEpoch'])
+ .execute()
+}
+
+export async function down(database: Kysely<CloudDatabase>): Promise<void> {
+ await database.schema.dropTable('documentCollaborationState').execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/008_storage_reservations.ts b/packages/cloud/src/server/db/migrations/008_storage_reservations.ts
new file mode 100644
index 000000000..2d1f7a6e3
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/008_storage_reservations.ts
@@ -0,0 +1,37 @@
+import type { CloudDatabase } from '#cloud/server/db/schema'
+import type { Kysely } from 'kysely'
+
+export async function up(database: Kysely<CloudDatabase>): Promise<void> {
+ await database.schema
+ .createTable('workspaceStorageUsage')
+ .addColumn('workspaceId', 'uuid', (column) =>
+ column.primaryKey().references('workspace.id').onDelete('cascade')
+ )
+ .addColumn('committedBytes', 'bigint', (column) => column.notNull().defaultTo(0))
+ .addColumn('updatedAt', 'timestamptz', (column) =>
+ column.notNull().defaultTo(database.fn('now'))
+ )
+ .execute()
+ await database.schema
+ .createTable('uploadStorageReservation')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('workspaceId', 'uuid', (column) =>
+ column.notNull().references('workspace.id').onDelete('cascade')
+ )
+ .addColumn('uploadId', 'uuid', (column) =>
+ column.notNull().unique().references('upload.id').onDelete('cascade')
+ )
+ .addColumn('bytes', 'bigint', (column) => column.notNull())
+ .addColumn('expiresAt', 'timestamptz', (column) => column.notNull())
+ .addColumn('committedAt', 'timestamptz')
+ .addColumn('releasedAt', 'timestamptz')
+ .addColumn('createdAt', 'timestamptz', (column) =>
+ column.notNull().defaultTo(database.fn('now'))
+ )
+ .execute()
+}
+
+export async function down(database: Kysely<CloudDatabase>): Promise<void> {
+ await database.schema.dropTable('uploadStorageReservation').execute()
+ await database.schema.dropTable('workspaceStorageUsage').execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/009_workspace_entitlements.ts b/packages/cloud/src/server/db/migrations/009_workspace_entitlements.ts
new file mode 100644
index 000000000..8b3cecda9
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/009_workspace_entitlements.ts
@@ -0,0 +1,22 @@
+import { CURRENT_TIMESTAMP } from '#cloud/server/db/expressions'
+import type { CloudDatabase } from '#cloud/server/db/schema'
+import type { Kysely } from 'kysely'
+
+export async function up(database: Kysely<CloudDatabase>): Promise<void> {
+ await database.schema
+ .createTable('workspaceEntitlement')
+ .addColumn('workspaceId', 'uuid', (column) =>
+ column.primaryKey().references('workspace.id').onDelete('cascade')
+ )
+ .addColumn('values', 'jsonb', (column) => column.notNull())
+ .addColumn('source', 'text', (column) => column.notNull())
+ .addColumn('revision', 'integer', (column) => column.notNull().defaultTo(1))
+ .addColumn('updatedAt', 'timestamptz', (column) =>
+ column.notNull().defaultTo(CURRENT_TIMESTAMP)
+ )
+ .execute()
+}
+
+export async function down(database: Kysely<CloudDatabase>): Promise<void> {
+ await database.schema.dropTable('workspaceEntitlement').execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/010_upload_finalization.ts b/packages/cloud/src/server/db/migrations/010_upload_finalization.ts
new file mode 100644
index 000000000..39d3634d5
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/010_upload_finalization.ts
@@ -0,0 +1,22 @@
+import type { Kysely } from 'kysely'
+
+import { replaceCheckConstraint } from './helpers'
+
+export async function up(database: Kysely<unknown>): Promise<void> {
+ await replaceCheckConstraint(database, 'upload', 'upload_status_check', 'status', [
+ 'pending',
+ 'finalizing',
+ 'cleaning',
+ 'committed',
+ 'abandoned'
+ ])
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await replaceCheckConstraint(database, 'upload', 'upload_status_check', 'status', [
+ 'pending',
+ 'cleaning',
+ 'committed',
+ 'abandoned'
+ ])
+}
diff --git a/packages/cloud/src/server/db/migrations/011_upload_finalization_lease.ts b/packages/cloud/src/server/db/migrations/011_upload_finalization_lease.ts
new file mode 100644
index 000000000..0c9a9b869
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/011_upload_finalization_lease.ts
@@ -0,0 +1,12 @@
+import { type Kysely } from 'kysely'
+
+export async function up(database: Kysely<unknown>): Promise<void> {
+ await database.schema
+ .alterTable('upload')
+ .addColumn('finalization_started_at', 'timestamptz')
+ .execute()
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await database.schema.alterTable('upload').dropColumn('finalization_started_at').execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/012_transactional_email.ts b/packages/cloud/src/server/db/migrations/012_transactional_email.ts
new file mode 100644
index 000000000..f3ff0ae61
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/012_transactional_email.ts
@@ -0,0 +1,48 @@
+import { checkColumnIn, CURRENT_TIMESTAMP } from '#cloud/server/db/expressions'
+import type { Kysely } from 'kysely'
+
+export async function up(database: Kysely<unknown>): Promise<void> {
+ await database.schema
+ .createTable('transactional_email')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('idempotency_key', 'text', (column) => column.notNull().unique())
+ .addColumn('kind', 'text', (column) => column.notNull())
+ .addColumn('recipient_email_normalized', 'text', (column) => column.notNull())
+ .addColumn('payload_encrypted', 'text')
+ .addColumn('status', 'text', (column) => column.notNull().defaultTo('pending'))
+ .addColumn('attempt_count', 'integer', (column) => column.notNull().defaultTo(0))
+ .addColumn('next_attempt_at', 'timestamptz', (column) =>
+ column.notNull().defaultTo(CURRENT_TIMESTAMP)
+ )
+ .addColumn('claim_id', 'uuid')
+ .addColumn('claimed_at', 'timestamptz')
+ .addColumn('transport', 'text')
+ .addColumn('transport_message_id', 'text')
+ .addColumn('last_error_code', 'text')
+ .addColumn('created_at', 'timestamptz', (column) =>
+ column.notNull().defaultTo(CURRENT_TIMESTAMP)
+ )
+ .addColumn('updated_at', 'timestamptz', (column) =>
+ column.notNull().defaultTo(CURRENT_TIMESTAMP)
+ )
+ .addColumn('accepted_at', 'timestamptz')
+ .addCheckConstraint(
+ 'transactional_email_kind_check',
+ checkColumnIn('kind', ['document-invitation'])
+ )
+ .addCheckConstraint(
+ 'transactional_email_status_check',
+ checkColumnIn('status', ['pending', 'sending', 'accepted', 'failed', 'suppressed'])
+ )
+ .execute()
+
+ await database.schema
+ .createIndex('transactional_email_delivery_index')
+ .on('transactional_email')
+ .columns(['status', 'next_attempt_at'])
+ .execute()
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await database.schema.dropTable('transactional_email').ifExists().execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/013_admin_enrollment.ts b/packages/cloud/src/server/db/migrations/013_admin_enrollment.ts
new file mode 100644
index 000000000..42e5d4944
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/013_admin_enrollment.ts
@@ -0,0 +1,54 @@
+import { checkColumnIn, CURRENT_TIMESTAMP, EMPTY_JSON_OBJECT } from '#cloud/server/db/expressions'
+import type { Kysely } from 'kysely'
+
+export async function up(database: Kysely<unknown>): Promise<void> {
+ await database.schema
+ .createTable('cloud_enrollment')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('email_normalized', 'text', (column) => column.notNull().unique())
+ .addColumn('name', 'text')
+ .addColumn('reason', 'text')
+ .addColumn('status', 'text', (column) => column.notNull().defaultTo('pending'))
+ .addColumn('requested_at', 'timestamptz', (column) =>
+ column.notNull().defaultTo(CURRENT_TIMESTAMP)
+ )
+ .addColumn('reviewed_at', 'timestamptz')
+ .addColumn('reviewed_by', 'text')
+ .addColumn('review_note', 'text')
+ .addColumn('approved_user_id', 'text')
+ .addCheckConstraint(
+ 'cloud_enrollment_status_check',
+ checkColumnIn('status', ['pending', 'approved', 'rejected', 'revoked'])
+ )
+ .execute()
+
+ await database.schema
+ .createIndex('cloud_enrollment_status_index')
+ .on('cloud_enrollment')
+ .columns(['status', 'requested_at'])
+ .execute()
+
+ await database.schema
+ .createTable('cloud_admin_audit_event')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('actor_user_id', 'text', (column) => column.notNull())
+ .addColumn('action', 'text', (column) => column.notNull())
+ .addColumn('subject_type', 'text', (column) => column.notNull())
+ .addColumn('subject_id', 'text', (column) => column.notNull())
+ .addColumn('metadata', 'jsonb', (column) => column.notNull().defaultTo(EMPTY_JSON_OBJECT))
+ .addColumn('created_at', 'timestamptz', (column) =>
+ column.notNull().defaultTo(CURRENT_TIMESTAMP)
+ )
+ .execute()
+
+ await database.schema
+ .createIndex('cloud_admin_audit_created_index')
+ .on('cloud_admin_audit_event')
+ .column('created_at')
+ .execute()
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await database.schema.dropTable('cloud_admin_audit_event').ifExists().execute()
+ await database.schema.dropTable('cloud_enrollment').ifExists().execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/014_enrollment_email_kinds.ts b/packages/cloud/src/server/db/migrations/014_enrollment_email_kinds.ts
new file mode 100644
index 000000000..074c85c5c
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/014_enrollment_email_kinds.ts
@@ -0,0 +1,30 @@
+import type { Kysely } from 'kysely'
+
+import { replaceCheckConstraint } from './helpers'
+
+export async function up(database: Kysely<unknown>): Promise<void> {
+ await replaceCheckConstraint(
+ database,
+ 'transactional_email',
+ 'transactional_email_kind_check',
+ 'kind',
+ [
+ 'document-invitation',
+ 'enrollment-requested',
+ 'admin-enrollment-notification',
+ 'enrollment-approved',
+ 'enrollment-rejected',
+ 'enrollment-revoked'
+ ]
+ )
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await replaceCheckConstraint(
+ database,
+ 'transactional_email',
+ 'transactional_email_kind_check',
+ 'kind',
+ ['document-invitation']
+ )
+}
diff --git a/packages/cloud/src/server/db/migrations/015_cloud_rate_limit.ts b/packages/cloud/src/server/db/migrations/015_cloud_rate_limit.ts
new file mode 100644
index 000000000..babc30d3a
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/015_cloud_rate_limit.ts
@@ -0,0 +1,22 @@
+import type { Kysely } from 'kysely'
+
+import { addCurrentTimestampColumns } from './helpers'
+
+export async function up(database: Kysely<unknown>): Promise<void> {
+ await database.schema
+ .alterTable('cloud_enrollment')
+ .addColumn('request_revision', 'integer', (column) => column.notNull().defaultTo(1))
+ .execute()
+ await database.schema
+ .createTable('cloud_rate_limit')
+ .addColumn('key_hash', 'text', (column) => column.primaryKey())
+ .addColumn('window_started_at', 'timestamptz', (column) => column.notNull())
+ .addColumn('request_count', 'integer', (column) => column.notNull().defaultTo(1))
+ .execute()
+ await addCurrentTimestampColumns(database, 'cloud_rate_limit', ['updated_at'])
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await database.schema.dropTable('cloud_rate_limit').ifExists().execute()
+ await database.schema.alterTable('cloud_enrollment').dropColumn('request_revision').execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/016_auth_schema.ts b/packages/cloud/src/server/db/migrations/016_auth_schema.ts
new file mode 100644
index 000000000..0757a47f5
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/016_auth_schema.ts
@@ -0,0 +1,16 @@
+import type { Kysely } from 'kysely'
+
+import { addCurrentTimestampColumns } from './helpers'
+
+export async function up(database: Kysely<unknown>): Promise<void> {
+ await database.schema
+ .createTable('cloud_auth_schema')
+ .addColumn('id', 'text', (column) => column.primaryKey())
+ .addColumn('version', 'text', (column) => column.notNull())
+ .execute()
+ await addCurrentTimestampColumns(database, 'cloud_auth_schema', ['updated_at'])
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await database.schema.dropTable('cloud_auth_schema').ifExists().execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/017_authentication_email_kinds.ts b/packages/cloud/src/server/db/migrations/017_authentication_email_kinds.ts
new file mode 100644
index 000000000..c1b96342d
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/017_authentication_email_kinds.ts
@@ -0,0 +1,32 @@
+import type { Kysely } from 'kysely'
+
+import { replaceCheckConstraint } from './helpers'
+
+const kinds = [
+ 'document-invitation',
+ 'enrollment-requested',
+ 'admin-enrollment-notification',
+ 'enrollment-approved',
+ 'enrollment-rejected',
+ 'enrollment-revoked'
+]
+
+export async function up(database: Kysely<unknown>): Promise<void> {
+ await replaceCheckConstraint(
+ database,
+ 'transactional_email',
+ 'transactional_email_kind_check',
+ 'kind',
+ [...kinds, 'email-verification', 'password-reset', 'password-changed']
+ )
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await replaceCheckConstraint(
+ database,
+ 'transactional_email',
+ 'transactional_email_kind_check',
+ 'kind',
+ kinds
+ )
+}
diff --git a/packages/cloud/src/server/db/migrations/018_authentication_mfa.ts b/packages/cloud/src/server/db/migrations/018_authentication_mfa.ts
new file mode 100644
index 000000000..5c92cf757
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/018_authentication_mfa.ts
@@ -0,0 +1,77 @@
+import { CURRENT_TIMESTAMP } from '#cloud/server/db/expressions'
+import type { CloudDatabase } from '#cloud/server/db/schema'
+import type { Kysely } from 'kysely'
+
+async function tableNames(database: Kysely<unknown>): Promise<Set<string>> {
+ return new Set((await database.introspection.getTables()).map((table) => table.name))
+}
+
+export async function up(database: Kysely<unknown>): Promise<void> {
+ const cloud = database as Kysely<CloudDatabase>
+ const tables = await tableNames(database)
+ await database.schema
+ .createTable('cloud_mfa_assurance')
+ .addColumn('session_id', 'uuid', (column) => column.primaryKey())
+ .addColumn('user_id', 'uuid', (column) => column.notNull())
+ .addColumn('method', 'text', (column) => column.notNull())
+ .addColumn('verified_at', 'timestamptz', (column) => column.notNull())
+ .execute()
+ if (!tables.has('user')) return
+
+ await database.schema
+ .alterTable('user')
+ .addColumn('two_factor_enabled', 'boolean', (column) => column.notNull().defaultTo(false))
+ .execute()
+ await database.schema
+ .createTable('two_factor')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('secret', 'text', (column) => column.notNull().unique())
+ .addColumn('backup_codes', 'text', (column) => column.notNull())
+ .addColumn('user_id', 'uuid', (column) =>
+ column.notNull().references('user.id').onDelete('cascade')
+ )
+ .addColumn('verified', 'boolean', (column) => column.notNull().defaultTo(true))
+ .addColumn('failed_verification_count', 'integer', (column) => column.notNull().defaultTo(0))
+ .addColumn('locked_until', 'timestamptz')
+ .execute()
+ await database.schema
+ .createIndex('two_factor_user_index')
+ .on('two_factor')
+ .column('user_id')
+ .execute()
+ await database.schema
+ .createTable('passkey')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('name', 'text')
+ .addColumn('public_key', 'text', (column) => column.notNull())
+ .addColumn('user_id', 'uuid', (column) =>
+ column.notNull().references('user.id').onDelete('cascade')
+ )
+ .addColumn('credential_id', 'text', (column) => column.notNull().unique())
+ .addColumn('counter', 'integer', (column) => column.notNull())
+ .addColumn('device_type', 'text', (column) => column.notNull())
+ .addColumn('backed_up', 'boolean', (column) => column.notNull())
+ .addColumn('transports', 'text')
+ .addColumn('created_at', 'timestamptz', (column) =>
+ column.notNull().defaultTo(CURRENT_TIMESTAMP)
+ )
+ .addColumn('aaguid', 'text')
+ .execute()
+ await database.schema.createIndex('passkey_user_index').on('passkey').column('user_id').execute()
+ await cloud
+ .updateTable('cloudAuthSchema')
+ .set({ version: '1.7.2+mfa.1', updatedAt: new Date() })
+ .where('id', '=', 'better-auth')
+ .where('version', '=', '1.7.2')
+ .execute()
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await database.schema.dropTable('cloud_mfa_assurance').ifExists().execute()
+ await database.schema.dropTable('passkey').ifExists().execute()
+ await database.schema.dropTable('two_factor').ifExists().execute()
+ const tables = await tableNames(database)
+ if (tables.has('user')) {
+ await database.schema.alterTable('user').dropColumn('two_factor_enabled').execute()
+ }
+}
diff --git a/packages/cloud/src/server/db/migrations/019_better_auth_account_issuer.ts b/packages/cloud/src/server/db/migrations/019_better_auth_account_issuer.ts
new file mode 100644
index 000000000..2d8959476
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/019_better_auth_account_issuer.ts
@@ -0,0 +1,41 @@
+import type { CloudDatabase } from '#cloud/server/db/schema'
+import type { Kysely } from 'kysely'
+
+/** The unique index Better Auth 1.7.0 through 1.7.2 created on `account (issuer, accountId)`. */
+const ISSUER_INDEX = 'account_issuer_accountId_uidx'
+
+/**
+ * Better Auth 1.7.3 dropped the required `account.issuer` column that 1.7.0 through 1.7.2 added,
+ * and no longer writes it, so a schema created on 1.7.2 would refuse every new account. Following
+ * Better Auth's 1.7 upgrade guide, the column becomes optional and its unique index goes; the
+ * column itself is left for a later cleanup.
+ */
+export async function up(database: Kysely<unknown>): Promise<void> {
+ const cloud = database as Kysely<CloudDatabase>
+ const account = (await database.introspection.getTables()).find(
+ (table) => table.name === 'account'
+ )
+ if (account?.columns.some((column) => column.name === 'issuer')) {
+ await database.schema.dropIndex(ISSUER_INDEX).ifExists().execute()
+ await database.schema
+ .alterTable('account')
+ .alterColumn('issuer', (column) => column.dropNotNull())
+ .execute()
+ }
+ await cloud
+ .updateTable('cloudAuthSchema')
+ .set({ version: '1.7.7+mfa.1', updatedAt: new Date() })
+ .where('id', '=', 'better-auth')
+ .where('version', '=', '1.7.2+mfa.1')
+ .execute()
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ const cloud = database as Kysely<CloudDatabase>
+ await cloud
+ .updateTable('cloudAuthSchema')
+ .set({ version: '1.7.2+mfa.1', updatedAt: new Date() })
+ .where('id', '=', 'better-auth')
+ .where('version', '=', '1.7.7+mfa.1')
+ .execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/020_workspace_invitations.ts b/packages/cloud/src/server/db/migrations/020_workspace_invitations.ts
new file mode 100644
index 000000000..97e654ad4
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/020_workspace_invitations.ts
@@ -0,0 +1,57 @@
+import { checkColumnIn } from '#cloud/server/db/expressions'
+import type { Kysely } from 'kysely'
+
+import { addCurrentTimestampColumns, addInvitationColumns, replaceCheckConstraint } from './helpers'
+
+const emailKinds = [
+ 'document-invitation',
+ 'enrollment-requested',
+ 'admin-enrollment-notification',
+ 'enrollment-approved',
+ 'enrollment-rejected',
+ 'enrollment-revoked',
+ 'email-verification',
+ 'password-reset',
+ 'password-changed'
+]
+
+export async function up(database: Kysely<unknown>): Promise<void> {
+ await addInvitationColumns(
+ database.schema
+ .createTable('workspace_invitation')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('workspace_id', 'uuid', (column) =>
+ column.references('workspace.id').onDelete('cascade').notNull()
+ ),
+ 'role'
+ )
+ .addCheckConstraint(
+ 'workspace_invitation_role_check',
+ checkColumnIn('role', ['admin', 'editor', 'viewer'])
+ )
+ .execute()
+ await addCurrentTimestampColumns(database, 'workspace_invitation', ['invited_at'])
+ await database.schema
+ .createIndex('workspace_invitation_workspace_index')
+ .on('workspace_invitation')
+ .columns(['workspace_id', 'revoked_at'])
+ .execute()
+ await replaceCheckConstraint(
+ database,
+ 'transactional_email',
+ 'transactional_email_kind_check',
+ 'kind',
+ [...emailKinds, 'workspace-invitation']
+ )
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await replaceCheckConstraint(
+ database,
+ 'transactional_email',
+ 'transactional_email_kind_check',
+ 'kind',
+ emailKinds
+ )
+ await database.schema.dropTable('workspace_invitation').execute()
+}
diff --git a/packages/cloud/src/server/db/migrations/helpers.ts b/packages/cloud/src/server/db/migrations/helpers.ts
new file mode 100644
index 000000000..5a9325cbc
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/helpers.ts
@@ -0,0 +1,71 @@
+import { checkColumnIn, CURRENT_TIMESTAMP } from '#cloud/server/db/expressions'
+import type { CreateTableBuilder, Kysely } from 'kysely'
+
+export async function addCheckConstraint(
+ database: Kysely<unknown>,
+ table: string,
+ constraint: string,
+ column: string,
+ values: readonly string[]
+): Promise<void> {
+ await database.schema
+ .alterTable(table)
+ .addCheckConstraint(constraint, checkColumnIn(column, values))
+ .execute()
+}
+
+export async function replaceCheckConstraint(
+ database: Kysely<unknown>,
+ table: string,
+ constraint: string,
+ column: string,
+ values: readonly string[]
+): Promise<void> {
+ await database.schema.alterTable(table).dropConstraint(constraint).execute()
+ await addCheckConstraint(database, table, constraint, column, values)
+}
+
+export async function addCurrentTimestampColumns(
+ database: Kysely<unknown>,
+ table: string,
+ columns: readonly string[]
+): Promise<void> {
+ for (const column of columns) {
+ await database.schema
+ .alterTable(table)
+ .addColumn(column, 'timestamptz', (definition) =>
+ definition.notNull().defaultTo(CURRENT_TIMESTAMP)
+ )
+ .execute()
+ }
+}
+
+type InvitationColumn =
+ | 'email_normalized'
+ | 'token_hash'
+ | 'invited_by'
+ | 'expires_at'
+ | 'accepted_at'
+ | 'revoked_at'
+
+/**
+ * What every emailed invitation keeps: whom it went to, the access it grants (`permission` on a
+ * document, `role` in a workspace), its hashed secret, and its lifecycle.
+ */
+export function addInvitationColumns<
+ Table extends string,
+ Column extends string,
+ Access extends 'permission' | 'role'
+>(
+ table: CreateTableBuilder<Table, Column>,
+ access: Access
+): CreateTableBuilder<Table, Column | InvitationColumn | Access> {
+ return table
+ .addColumn('email_normalized', 'text', (column) => column.notNull())
+ .addColumn(access, 'text', (column) => column.notNull())
+ .addColumn('token_hash', 'text', (column) => column.notNull())
+ .addColumn('invited_by', 'text', (column) => column.notNull())
+ .addColumn('expires_at', 'timestamptz', (column) => column.notNull())
+ .addColumn('accepted_at', 'timestamptz')
+ .addColumn('revoked_at', 'timestamptz')
+}
diff --git a/packages/cloud/src/server/db/schema.ts b/packages/cloud/src/server/db/schema.ts
new file mode 100644
index 000000000..cba542cb0
--- /dev/null
+++ b/packages/cloud/src/server/db/schema.ts
@@ -0,0 +1,325 @@
+import type { EnrollmentStatus } from '#cloud/admin/enrollment/service'
+import type { DocumentPermission, WorkspaceRole } from '#cloud/contract'
+import type { TransactionalEmailKind, TransactionalEmailPayloadByKind } from '#cloud/email'
+import type { Account, Session } from 'better-auth'
+import type { ColumnType, Generated, Insertable, Selectable, Updateable } from 'kysely'
+
+export type TimestampColumn = ColumnType<Date, Date | string | undefined, Date | string | null>
+
+export type UploadStatus = 'pending' | 'finalizing' | 'cleaning' | 'committed' | 'abandoned'
+
+export interface DocumentShareTable {
+ id: string
+ documentId: string
+ permission: DocumentPermission
+ secretHash: string
+ roomEpoch: Generated<number>
+ createdBy: string
+ createdAt: TimestampColumn
+ updatedAt: TimestampColumn
+ expiresAt: TimestampColumn | null
+ revokedAt: TimestampColumn | null
+ lastUsedAt: TimestampColumn | null
+}
+
+export interface DocumentGrantTable {
+ id: string
+ documentId: string
+ userId: string
+ permission: DocumentPermission
+ createdBy: string
+ createdAt: TimestampColumn
+ updatedAt: TimestampColumn
+ revokedAt: TimestampColumn | null
+}
+
+export interface DocumentInvitationTable {
+ id: string
+ documentId: string
+ emailNormalized: string
+ permission: DocumentPermission
+ tokenHash: string
+ invitedBy: string
+ invitedAt: TimestampColumn
+ expiresAt: TimestampColumn
+ acceptedAt: TimestampColumn | null
+ revokedAt: TimestampColumn | null
+}
+
+export interface WorkspaceTable {
+ id: string
+ name: string
+ slug: string
+ createdBy: string
+ createdAt: TimestampColumn
+ updatedAt: TimestampColumn
+}
+
+export interface WorkspaceMemberTable {
+ workspaceId: string
+ userId: string
+ role: WorkspaceRole
+ createdAt: TimestampColumn
+}
+
+export interface WorkspaceInvitationTable {
+ id: string
+ workspaceId: string
+ emailNormalized: string
+ role: WorkspaceRole
+ tokenHash: string
+ invitedBy: string
+ invitedAt: TimestampColumn
+ expiresAt: TimestampColumn
+ acceptedAt: TimestampColumn | null
+ revokedAt: TimestampColumn | null
+}
+
+export interface DocumentTable {
+ id: string
+ workspaceId: string
+ name: string
+ currentRevisionId: string | null
+ collaborationEpoch: Generated<number>
+ version: Generated<number>
+ createdBy: string
+ createdAt: TimestampColumn
+ updatedAt: TimestampColumn
+ deletedAt: TimestampColumn | null
+ cleanupClaimId: Generated<string | null>
+ cleanupClaimedAt: TimestampColumn | null
+}
+
+export interface StorageObjectTable {
+ id: string
+ objectKey: string
+ checksum: string
+ byteSize: number
+ contentType: string
+ createdAt: TimestampColumn
+}
+
+export interface DocumentRevisionTable {
+ id: string
+ documentId: string
+ parentRevisionId: string | null
+ storageObjectId: string
+ createdBy: string
+ createdAt: TimestampColumn
+}
+
+export interface UploadTable {
+ id: string
+ documentId: string
+ baseRevisionId: string | null
+ objectKey: string
+ checksum: string
+ byteSize: number
+ contentType: string
+ multipartUploadId: string | null
+ status: UploadStatus
+ finalizationStartedAt: TimestampColumn | null
+ cleanupClaimId: Generated<string | null>
+ cleanupClaimedAt: TimestampColumn | null
+ createdBy: string
+ createdAt: TimestampColumn
+ expiresAt: TimestampColumn
+}
+
+export interface AuthUserTable {
+ id: string
+ name: string
+ email: string
+ emailVerified: boolean
+ image: string | null
+ role: Generated<string | null>
+ banned: Generated<boolean | null>
+ banReason: Generated<string | null>
+ banExpires: TimestampColumn | null
+ twoFactorEnabled: Generated<boolean>
+ createdAt: TimestampColumn
+ updatedAt: TimestampColumn
+}
+
+export interface TwoFactorTable {
+ id: string
+ secret: string
+ backupCodes: string
+ userId: string
+ verified: Generated<boolean>
+ failedVerificationCount: Generated<number>
+ lockedUntil: TimestampColumn | null
+}
+
+export interface PasskeyTable {
+ id: string
+ name: string | null
+ publicKey: string
+ userId: string
+ credentialID: string
+ counter: number
+ deviceType: string
+ backedUp: boolean
+ transports: string | null
+ createdAt: TimestampColumn
+ aaguid: string | null
+}
+
+export interface CloudMFAAssuranceTable {
+ sessionId: string
+ userId: string
+ method: 'totp' | 'recovery-code' | 'passkey'
+ verifiedAt: TimestampColumn
+}
+
+export interface DocumentCollaborationStateTable {
+ documentId: string
+ roomEpoch: number
+ state: Uint8Array
+ version: Generated<number>
+ createdAt: TimestampColumn
+ updatedAt: TimestampColumn
+}
+
+export interface InvitationContinuationTable {
+ id: string
+ invitationId: string
+ tokenEncrypted: string
+ expiresAt: TimestampColumn
+ consumedAt: TimestampColumn | null
+ createdAt: TimestampColumn
+}
+
+export interface WorkspaceEntitlementTable {
+ workspaceId: string
+ values: unknown
+ source: string
+ revision: Generated<number>
+ updatedAt: TimestampColumn
+}
+
+export interface WorkspaceStorageUsageTable {
+ workspaceId: string
+ committedBytes: number
+ updatedAt: TimestampColumn
+}
+
+export interface UploadStorageReservationTable {
+ id: string
+ workspaceId: string
+ uploadId: string
+ bytes: number
+ expiresAt: TimestampColumn
+ committedAt: TimestampColumn | null
+ releasedAt: TimestampColumn | null
+ createdAt: TimestampColumn
+}
+
+export type TransactionalEmailStatus = 'pending' | 'sending' | 'accepted' | 'failed' | 'suppressed'
+
+export interface TransactionalEmailTable {
+ id: string
+ idempotencyKey: string
+ kind: TransactionalEmailKind
+ recipientEmailNormalized: string
+ payloadEncrypted: string | null
+ status: TransactionalEmailStatus
+ attemptCount: Generated<number>
+ nextAttemptAt: TimestampColumn
+ claimId: string | null
+ claimedAt: TimestampColumn | null
+ transport: string | null
+ transportMessageId: string | null
+ lastErrorCode: string | null
+ createdAt: TimestampColumn
+ updatedAt: TimestampColumn
+ acceptedAt: TimestampColumn | null
+}
+
+export type TransactionalEmailPayload = TransactionalEmailPayloadByKind[TransactionalEmailKind]
+
+export interface CloudEnrollmentTable {
+ id: string
+ emailNormalized: string
+ name: string | null
+ reason: string | null
+ status: EnrollmentStatus
+ requestedAt: TimestampColumn
+ reviewedAt: TimestampColumn | null
+ reviewedBy: string | null
+ reviewNote: string | null
+ requestRevision: Generated<number>
+ approvedUserId: string | null
+}
+
+export interface CloudRateLimitTable {
+ keyHash: string
+ windowStartedAt: TimestampColumn
+ requestCount: Generated<number>
+ updatedAt: TimestampColumn
+}
+
+export interface CloudAdminAuditEventTable {
+ id: string
+ actorUserId: string
+ action: string
+ subjectType: string
+ subjectId: string
+ metadata: unknown
+ createdAt: TimestampColumn
+}
+
+export interface CloudAuthSchemaTable {
+ id: string
+ version: string
+ updatedAt: TimestampColumn
+}
+
+export interface CloudDatabase {
+ account: Account
+ session: Session
+ twoFactor: TwoFactorTable
+ passkey: PasskeyTable
+ cloudMfaAssurance: CloudMFAAssuranceTable
+ user: AuthUserTable
+ cloudAuthSchema: CloudAuthSchemaTable
+ cloudEnrollment: CloudEnrollmentTable
+ cloudRateLimit: CloudRateLimitTable
+ cloudAdminAuditEvent: CloudAdminAuditEventTable
+ workspace: WorkspaceTable
+ workspaceMember: WorkspaceMemberTable
+ workspaceInvitation: WorkspaceInvitationTable
+ document: DocumentTable
+ storageObject: StorageObjectTable
+ documentRevision: DocumentRevisionTable
+ documentShare: DocumentShareTable
+ documentGrant: DocumentGrantTable
+ documentInvitation: DocumentInvitationTable
+ documentCollaborationState: DocumentCollaborationStateTable
+ invitationContinuation: InvitationContinuationTable
+ workspaceEntitlement: WorkspaceEntitlementTable
+ workspaceStorageUsage: WorkspaceStorageUsageTable
+ transactionalEmail: TransactionalEmailTable
+ uploadStorageReservation: UploadStorageReservationTable
+ upload: UploadTable
+}
+
+export type NewTransactionalEmail = Insertable<TransactionalEmailTable>
+export type TransactionalEmail = Selectable<TransactionalEmailTable>
+export type Workspace = Selectable<WorkspaceTable>
+export type NewWorkspace = Insertable<WorkspaceTable>
+export type WorkspaceUpdate = Updateable<WorkspaceTable>
+export type Document = Selectable<DocumentTable>
+export type NewDocument = Insertable<DocumentTable>
+export type DocumentRevision = Selectable<DocumentRevisionTable>
+export type NewDocumentRevision = Insertable<DocumentRevisionTable>
+export type DocumentShare = Selectable<DocumentShareTable>
+export type NewDocumentShare = Insertable<DocumentShareTable>
+export type DocumentGrant = Selectable<DocumentGrantTable>
+export type NewDocumentGrant = Insertable<DocumentGrantTable>
+export type DocumentInvitation = Selectable<DocumentInvitationTable>
+export type NewDocumentInvitation = Insertable<DocumentInvitationTable>
+export type StorageObject = Selectable<StorageObjectTable>
+export type NewStorageObject = Insertable<StorageObjectTable>
+export type Upload = Selectable<UploadTable>
+export type NewUpload = Insertable<UploadTable>
diff --git a/packages/cloud/src/server/documents/access.ts b/packages/cloud/src/server/documents/access.ts
new file mode 100644
index 000000000..e04e2c36a
--- /dev/null
+++ b/packages/cloud/src/server/documents/access.ts
@@ -0,0 +1,103 @@
+import type {
+ DocumentAccess,
+ DocumentAccessSource,
+ DocumentPermission,
+ WorkspaceRole
+} from '#cloud/contract'
+import type { CloudDatabase } from '#cloud/server/db'
+import { maxBy } from 'es-toolkit'
+import type { Kysely, Transaction } from 'kysely'
+
+export type AccessDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>
+
+const PERMISSION_WEIGHT: Record<DocumentPermission, number> = { view: 1, edit: 2 }
+
+function workspacePermission(role: WorkspaceRole): DocumentPermission {
+ return role === 'viewer' ? 'view' : 'edit'
+}
+
+export async function resolveDocumentAccess(
+ database: AccessDatabase,
+ userId: string,
+ documentId: string
+): Promise<DocumentAccess | undefined> {
+ const document = await database
+ .selectFrom('document')
+ .leftJoin('workspaceMember', (join) =>
+ join
+ .onRef('workspaceMember.workspaceId', '=', 'document.workspaceId')
+ .on('workspaceMember.userId', '=', userId)
+ )
+ .leftJoin('documentGrant', (join) =>
+ join
+ .onRef('documentGrant.documentId', '=', 'document.id')
+ .on('documentGrant.userId', '=', userId)
+ .on('documentGrant.revokedAt', 'is', null)
+ )
+ .select([
+ 'document.createdBy',
+ 'workspaceMember.role as workspaceRole',
+ 'documentGrant.permission as grantPermission'
+ ])
+ .where('document.id', '=', documentId)
+ .where('document.deletedAt', 'is', null)
+ .executeTakeFirst()
+ if (!document) return undefined
+
+ const sources: DocumentAccessSource[] = []
+ const candidates: DocumentPermission[] = []
+ const owner = document.createdBy === userId
+ if (owner) {
+ sources.push('owner')
+ candidates.push('edit')
+ }
+ if (document.workspaceRole) {
+ sources.push('workspace')
+ candidates.push(workspacePermission(document.workspaceRole))
+ }
+ if (document.grantPermission) {
+ sources.push('direct-grant')
+ candidates.push(document.grantPermission)
+ }
+ const permission = maxBy(candidates, (candidate) => PERMISSION_WEIGHT[candidate])
+ if (!permission) return undefined
+ const workspaceCanManage =
+ document.workspaceRole === 'admin' || document.workspaceRole === 'editor'
+ return {
+ permission,
+ canManageSharing: owner || workspaceCanManage || document.grantPermission === 'edit',
+ sources
+ }
+}
+
+export function canEditDocument(access: DocumentAccess): boolean {
+ return access.permission === 'edit'
+}
+
+/**
+ * Removing a document belongs to its owner and its workspace's admins and editors. A direct grant
+ * or an accepted invitation lets someone edit, never delete the owner's document.
+ */
+export async function canDeleteDocument(
+ database: AccessDatabase,
+ userId: string,
+ documentId: string
+): Promise<boolean> {
+ const document = await database
+ .selectFrom('document')
+ .leftJoin('workspaceMember', (join) =>
+ join
+ .onRef('workspaceMember.workspaceId', '=', 'document.workspaceId')
+ .on('workspaceMember.userId', '=', userId)
+ )
+ .select(['document.createdBy', 'workspaceMember.role as workspaceRole'])
+ .where('document.id', '=', documentId)
+ .where('document.deletedAt', 'is', null)
+ .executeTakeFirst()
+ if (!document) return false
+ return (
+ document.createdBy === userId ||
+ document.workspaceRole === 'admin' ||
+ document.workspaceRole === 'editor'
+ )
+}
diff --git a/packages/cloud/src/server/documents/index.ts b/packages/cloud/src/server/documents/index.ts
new file mode 100644
index 000000000..4f297e765
--- /dev/null
+++ b/packages/cloud/src/server/documents/index.ts
@@ -0,0 +1,15 @@
+export {
+ canDeleteDocument,
+ canEditDocument,
+ resolveDocumentAccess,
+ type AccessDatabase
+} from './access'
+export { createDocumentRoutes, type DocumentRouteEnvironment } from './routes'
+export {
+ createDocumentService,
+ DocumentConflictError,
+ DocumentForbiddenError,
+ DocumentNotFoundError,
+ UploadInvalidError,
+ type DocumentService
+} from './service'
diff --git a/packages/cloud/src/server/documents/repository.ts b/packages/cloud/src/server/documents/repository.ts
new file mode 100644
index 000000000..7c85ab645
--- /dev/null
+++ b/packages/cloud/src/server/documents/repository.ts
@@ -0,0 +1,131 @@
+import type { DocumentSummary, SharedDocument, WorkspaceRole } from '#cloud/contract'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { CreateDocumentRecord } from '#cloud/server/documents/types'
+import { uniq } from 'es-toolkit'
+import type { Kysely, Transaction } from 'kysely'
+import * as v from 'valibot'
+
+import { resolveDocumentAccess } from './access'
+import { documentSummary, getDocumentSummaryRow } from './summary'
+
+const UUID = v.pipe(v.string(), v.uuid())
+
+export type DocumentDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>
+
+export type DocumentSummaryRow = Omit<DocumentSummary, 'createdAt' | 'updatedAt'> & {
+ createdAt: Date | string
+ updatedAt: Date | string
+}
+
+export async function workspaceRole(
+ database: DocumentDatabase,
+ userId: string,
+ workspaceId: string
+): Promise<WorkspaceRole | undefined> {
+ const member = await database
+ .selectFrom('workspaceMember')
+ .select('role')
+ .where('workspaceId', '=', workspaceId)
+ .where('userId', '=', userId)
+ .executeTakeFirst()
+ return member?.role
+}
+
+export async function listDocuments(
+ database: DocumentDatabase,
+ userId: string,
+ workspaceId: string
+): Promise<DocumentSummary[] | undefined> {
+ if (!(await workspaceRole(database, userId, workspaceId))) return undefined
+ const rows = await database
+ .selectFrom('document')
+ .select(['id', 'workspaceId', 'name', 'currentRevisionId', 'version', 'createdAt', 'updatedAt'])
+ .where('workspaceId', '=', workspaceId)
+ .where('deletedAt', 'is', null)
+ .orderBy('updatedAt', 'desc')
+ .execute()
+ return rows.map(documentSummary)
+}
+
+/** Documents granted to the person directly that live in workspaces they are not a member of. */
+export async function listSharedDocuments(
+ database: DocumentDatabase,
+ userId: string
+): Promise<SharedDocument[]> {
+ const rows = await database
+ .selectFrom('documentGrant')
+ .innerJoin('document', 'document.id', 'documentGrant.documentId')
+ .innerJoin('workspace', 'workspace.id', 'document.workspaceId')
+ .select([
+ 'document.id',
+ 'document.workspaceId',
+ 'document.name',
+ 'document.currentRevisionId',
+ 'document.version',
+ 'document.createdAt',
+ 'document.updatedAt',
+ 'workspace.name as workspaceName',
+ 'documentGrant.permission',
+ 'documentGrant.createdAt as sharedAt',
+ 'documentGrant.createdBy'
+ ])
+ .where('documentGrant.userId', '=', userId)
+ .where('documentGrant.revokedAt', 'is', null)
+ .where('document.deletedAt', 'is', null)
+ .where((expression) =>
+ expression.not(
+ expression.exists(
+ expression
+ .selectFrom('workspaceMember')
+ .select('workspaceMember.userId')
+ .whereRef('workspaceMember.workspaceId', '=', 'document.workspaceId')
+ .where('workspaceMember.userId', '=', userId)
+ )
+ )
+ )
+ .orderBy('document.updatedAt', 'desc')
+ .execute()
+ // Grants can be made by operator tools whose IDs are not accounts, so only UUIDs are looked up.
+ const granters = uniq(rows.map((row) => row.createdBy)).filter((id) => v.is(UUID, id))
+ const names = new Map(
+ granters.length === 0
+ ? []
+ : (
+ await database
+ .selectFrom('user')
+ .select(['id', 'name'])
+ .where('id', 'in', granters)
+ .execute()
+ ).map((user) => [user.id, user.name] as const)
+ )
+ return rows.map(({ workspaceName, permission, sharedAt, createdBy, ...row }) => {
+ const sharedByName = names.get(createdBy)
+ return {
+ ...documentSummary(row),
+ workspaceName,
+ permission,
+ sharedBy: sharedByName === undefined ? null : { name: sharedByName },
+ sharedAt: sharedAt instanceof Date ? sharedAt.toISOString() : sharedAt
+ }
+ })
+}
+
+export async function findDocument(
+ database: DocumentDatabase,
+ userId: string,
+ documentId: string
+): Promise<(DocumentSummary & { role: WorkspaceRole }) | undefined> {
+ const access = await resolveDocumentAccess(database, userId, documentId)
+ if (!access) return undefined
+ const row = await getDocumentSummaryRow(database, documentId)
+ if (!row) return undefined
+ const role: WorkspaceRole = access.permission === 'edit' ? 'editor' : 'viewer'
+ return { ...documentSummary(row), role }
+}
+
+export async function insertDocument(
+ database: DocumentDatabase,
+ input: CreateDocumentRecord
+): Promise<void> {
+ await database.insertInto('document').values(input).execute()
+}
diff --git a/packages/cloud/src/server/documents/routes.ts b/packages/cloud/src/server/documents/routes.ts
new file mode 100644
index 000000000..80cbc068f
--- /dev/null
+++ b/packages/cloud/src/server/documents/routes.ts
@@ -0,0 +1,173 @@
+import { parseCommitUpload, parseCreateDocument, parseCreateUpload } from '#cloud/contract'
+import type { CloudActor } from '#cloud/server/auth'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { DocumentService } from '#cloud/server/documents/service'
+import {
+ DocumentConflictError,
+ DocumentForbiddenError,
+ DocumentNotFoundError,
+ UploadInvalidError
+} from '#cloud/server/documents/service'
+import { StorageQuotaExceededError } from '#cloud/server/quota'
+import { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'
+import { validatedJSON } from '#cloud/server/validation'
+import { Hono, type Context } from 'hono'
+import type { Kysely } from 'kysely'
+
+export type DocumentRouteEnvironment = {
+ Variables: {
+ actor: CloudActor
+ }
+}
+
+function domainError(context: Context, error: unknown): Response | null {
+ if (error instanceof DocumentNotFoundError) {
+ return context.json({ error: { code: 'not_found' as const } }, 404)
+ }
+ if (error instanceof DocumentForbiddenError) {
+ return context.json({ error: { code: 'forbidden' as const } }, 403)
+ }
+ if (error instanceof DocumentConflictError) {
+ return context.json({ error: { code: 'revision_conflict' as const } }, 409)
+ }
+ if (error instanceof StorageQuotaExceededError) {
+ return context.json({ error: { code: 'storage_quota_exceeded' as const } }, 409)
+ }
+ if (error instanceof UploadInvalidError) {
+ return context.json({ error: { code: 'invalid_upload' as const } }, 422)
+ }
+ return null
+}
+
+export function createDocumentRoutes(
+ service: DocumentService,
+ rateLimit?: { database: Kysely<CloudDatabase>; secret: string }
+) {
+ const router = new Hono<DocumentRouteEnvironment>()
+ if (rateLimit) {
+ router.use(
+ '/workspaces/:workspaceId/documents',
+ createActorRateLimiter(
+ rateLimit.database,
+ rateLimit.secret,
+ CLOUD_RATE_LIMITS.documentCreation,
+ (context) => context.req.method !== 'POST',
+ (context) => context.req.param('workspaceId') ?? 'unknown'
+ )
+ )
+ router.use(
+ '/documents/:documentId/uploads',
+ createActorRateLimiter(
+ rateLimit.database,
+ rateLimit.secret,
+ CLOUD_RATE_LIMITS.uploadCreation,
+ (context) => context.req.method !== 'POST',
+ (context) => context.req.param('documentId') ?? 'unknown'
+ )
+ )
+ }
+ return router
+ .get('/shared-documents', async (context) =>
+ context.json({ documents: await service.listShared(context.get('actor').userId) })
+ )
+ .get('/workspaces/:workspaceId/documents', async (context) => {
+ const documents = await service.list(
+ context.get('actor').userId,
+ context.req.param('workspaceId')
+ )
+ if (!documents) return context.json({ error: { code: 'not_found' as const } }, 404)
+ return context.json({ documents })
+ })
+ .get('/workspaces/:workspaceId/usage', async (context) => {
+ try {
+ return context.json({
+ usage: await service.usage(context.get('actor').userId, context.req.param('workspaceId'))
+ })
+ } catch (error) {
+ const response = domainError(context, error)
+ if (response) return response
+ throw error
+ }
+ })
+ .post(
+ '/workspaces/:workspaceId/documents',
+ validatedJSON(parseCreateDocument),
+ async (context) => {
+ try {
+ const document = await service.create(
+ context.get('actor').userId,
+ context.req.param('workspaceId'),
+ context.req.valid('json')
+ )
+ return context.json({ document }, 201)
+ } catch (error) {
+ const response = domainError(context, error)
+ if (response) return response
+ throw error
+ }
+ }
+ )
+ .delete('/documents/:documentId', async (context) => {
+ try {
+ await service.remove(context.get('actor').userId, context.req.param('documentId'))
+ return context.body(null, 204)
+ } catch (error) {
+ const response = domainError(context, error)
+ if (response) return response
+ throw error
+ }
+ })
+ .get('/documents/:documentId/access', async (context) => {
+ try {
+ return context.json({
+ access: await service.access(context.get('actor').userId, context.req.param('documentId'))
+ })
+ } catch (error) {
+ const response = domainError(context, error)
+ if (response) return response
+ throw error
+ }
+ })
+ .get('/documents/:documentId', async (context) => {
+ try {
+ return context.json({
+ document: await service.download(
+ context.get('actor').userId,
+ context.req.param('documentId')
+ )
+ })
+ } catch (error) {
+ const response = domainError(context, error)
+ if (response) return response
+ throw error
+ }
+ })
+ .post('/documents/:documentId/uploads', validatedJSON(parseCreateUpload), async (context) => {
+ try {
+ const result = await service.createUpload(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.valid('json')
+ )
+ return context.json(result, 201)
+ } catch (error) {
+ const response = domainError(context, error)
+ if (response) return response
+ throw error
+ }
+ })
+ .post('/uploads/:uploadId/commit', validatedJSON(parseCommitUpload), async (context) => {
+ try {
+ const document = await service.commitUpload(
+ context.get('actor').userId,
+ context.req.param('uploadId'),
+ context.req.valid('json')
+ )
+ return context.json({ document })
+ } catch (error) {
+ const response = domainError(context, error)
+ if (response) return response
+ throw error
+ }
+ })
+}
diff --git a/packages/cloud/src/server/documents/service.ts b/packages/cloud/src/server/documents/service.ts
new file mode 100644
index 000000000..d07fbac52
--- /dev/null
+++ b/packages/cloud/src/server/documents/service.ts
@@ -0,0 +1,417 @@
+import type {
+ CommitUploadInput,
+ CreateDocumentInput,
+ CreateUploadInput,
+ DocumentDownload,
+ DocumentSummary,
+ SharedDocument
+} from '#cloud/contract'
+import { createUploadCleanupService } from '#cloud/server/cleanup'
+import type { CloudDatabase } from '#cloud/server/db'
+import {
+ canDeleteDocument,
+ canEditDocument,
+ resolveDocumentAccess
+} from '#cloud/server/documents/access'
+import {
+ findDocument,
+ insertDocument,
+ listDocuments,
+ listSharedDocuments,
+ workspaceRole
+} from '#cloud/server/documents/repository'
+import { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'
+import type { CreateDocumentUploadResult } from '#cloud/server/documents/types'
+import type { ObjectStore } from '#cloud/server/objects'
+import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'
+import type { CloudPolicy } from '#cloud/server/policy/policy'
+import { createStorageQuotaService } from '#cloud/server/quota'
+import type { Kysely } from 'kysely'
+
+const DOWNLOAD_LIFETIME_MS = 5 * 60 * 1000
+const UPLOAD_LIFETIME_MS = 15 * 60 * 1000
+const WRITABLE_ROLES = new Set(['admin', 'editor'])
+
+export class DocumentNotFoundError extends Error {
+ override readonly name = 'DocumentNotFoundError'
+}
+export class DocumentForbiddenError extends Error {
+ override readonly name = 'DocumentForbiddenError'
+}
+export class DocumentConflictError extends Error {
+ override readonly name = 'DocumentConflictError'
+}
+export class UploadInvalidError extends Error {
+ override readonly name = 'UploadInvalidError'
+}
+
+export type DocumentServiceOptions = {
+ policy?: CloudPolicy
+ technicalMaximumUploadBytes?: number
+}
+
+export function createDocumentService(
+ database: Kysely<CloudDatabase>,
+ objects: ObjectStore,
+ options: DocumentServiceOptions = {}
+) {
+ const cleanup = createUploadCleanupService(database, objects)
+ const quota = createStorageQuotaService(database)
+
+ async function createDownload(documentId: string): Promise<DocumentDownload> {
+ const row = await getDocumentSummaryRow(database, documentId)
+ if (!row?.currentRevisionId) throw new DocumentNotFoundError()
+ const document: DocumentSummary = documentSummary(row)
+ const revision = await database
+ .selectFrom('documentRevision')
+ .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')
+ .select([
+ 'documentRevision.id as revisionId',
+ 'storageObject.objectKey',
+ 'storageObject.byteSize',
+ 'storageObject.checksum',
+ 'storageObject.contentType'
+ ])
+ .where('documentRevision.id', '=', document.currentRevisionId)
+ .where('documentRevision.documentId', '=', documentId)
+ .executeTakeFirst()
+ if (!revision) throw new DocumentNotFoundError()
+ return {
+ document,
+ revisionId: revision.revisionId,
+ byteSize: Number(revision.byteSize),
+ checksum: revision.checksum,
+ contentType: revision.contentType,
+ download: await objects.createDownload({
+ key: revision.objectKey,
+ expiresAt: new Date(Date.now() + DOWNLOAD_LIFETIME_MS)
+ })
+ }
+ }
+
+ return {
+ async cleanupExpiredUploads(now = new Date()): Promise<number> {
+ const result = await cleanup.cleanupExpiredUploads({
+ batchSize: 100,
+ leaseDurationMs: 5 * 60 * 1000,
+ now
+ })
+ if (result.failed > 0) throw new Error('One or more expired uploads could not be cleaned')
+ return result.cleaned
+ },
+
+ list(userId: string, workspaceId: string): Promise<DocumentSummary[] | undefined> {
+ return listDocuments(database, userId, workspaceId)
+ },
+
+ listShared(userId: string): Promise<SharedDocument[]> {
+ return listSharedDocuments(database, userId)
+ },
+
+ async usage(userId: string, workspaceId: string) {
+ const role = await workspaceRole(database, userId, workspaceId)
+ if (!role) throw new DocumentNotFoundError()
+ const result = await database
+ .selectFrom('document')
+ .leftJoin('documentRevision', 'documentRevision.id', 'document.currentRevisionId')
+ .leftJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')
+ .select((expression) => [
+ expression.fn.count('document.id').as('documentCount'),
+ expression.fn.count('storageObject.id').as('objectCount'),
+ expression.fn
+ .coalesce(expression.fn.sum('storageObject.byteSize'), expression.val(0))
+ .as('bytesUsed')
+ ])
+ .where('document.workspaceId', '=', workspaceId)
+ .where('document.deletedAt', 'is', null)
+ .executeTakeFirstOrThrow()
+ return {
+ bytesUsed: Number(result.bytesUsed),
+ objectCount: Number(result.objectCount),
+ documentCount: Number(result.documentCount)
+ }
+ },
+
+ async access(userId: string, documentId: string) {
+ const access = await resolveDocumentAccess(database, userId, documentId)
+ if (!access) throw new DocumentNotFoundError()
+ return access
+ },
+
+ async downloadShared(documentId: string): Promise<DocumentDownload> {
+ return createDownload(documentId)
+ },
+
+ async download(userId: string, documentId: string): Promise<DocumentDownload> {
+ const access = await resolveDocumentAccess(database, userId, documentId)
+ if (!access) throw new DocumentNotFoundError()
+ return createDownload(documentId)
+ },
+
+ async remove(userId: string, documentId: string): Promise<void> {
+ const access = await resolveDocumentAccess(database, userId, documentId)
+ if (!access) throw new DocumentNotFoundError()
+ if (!canEditDocument(access) || !(await canDeleteDocument(database, userId, documentId))) {
+ throw new DocumentForbiddenError()
+ }
+ await database
+ .updateTable('document')
+ .set({ deletedAt: new Date() })
+ .where('id', '=', documentId)
+ .where('deletedAt', 'is', null)
+ .execute()
+ },
+
+ async create(
+ userId: string,
+ workspaceId: string,
+ input: CreateDocumentInput
+ ): Promise<DocumentSummary> {
+ const role = await workspaceRole(database, userId, workspaceId)
+ if (!role) throw new DocumentNotFoundError()
+ if (!WRITABLE_ROLES.has(role)) throw new DocumentForbiddenError()
+ const documentId = input.id ?? crypto.randomUUID()
+ await insertDocument(database, {
+ id: documentId,
+ workspaceId,
+ name: input.name,
+ createdBy: userId
+ })
+ const document = await findDocument(database, userId, documentId)
+ if (!document) throw new DocumentNotFoundError()
+ return document
+ },
+
+ async createUpload(
+ userId: string,
+ documentId: string,
+ input: CreateUploadInput
+ ): Promise<CreateDocumentUploadResult> {
+ const access = await resolveDocumentAccess(database, userId, documentId)
+ if (!access) throw new DocumentNotFoundError()
+ if (!canEditDocument(access)) throw new DocumentForbiddenError()
+ const document = await findDocument(database, userId, documentId)
+ if (!document) throw new DocumentNotFoundError()
+ if (document.currentRevisionId !== input.baseRevisionId) throw new DocumentConflictError()
+ const policyContext = {
+ targetingKey: document.workspaceId,
+ actorId: userId,
+ workspaceId: document.workspaceId,
+ documentId,
+ deploymentMode: 'self-hosted' as const
+ }
+ const technicalMaximum = options.technicalMaximumUploadBytes ?? Number.MAX_SAFE_INTEGER
+ const entitlementMaximum = options.policy
+ ? await options.policy.number(
+ CLOUD_FEATURE_KEYS.maximumFileBytes,
+ technicalMaximum,
+ policyContext
+ )
+ : technicalMaximum
+ if (input.byteSize > Math.min(technicalMaximum, entitlementMaximum)) {
+ throw new UploadInvalidError()
+ }
+ const maximumStorageBytes = options.policy
+ ? await options.policy.number(
+ 'cloud.storage.maximum-bytes',
+ Number.MAX_SAFE_INTEGER,
+ policyContext
+ )
+ : Number.MAX_SAFE_INTEGER
+ const uploadId = crypto.randomUUID()
+ const objectKey = `documents/${document.workspaceId}/${documentId}/uploads/${uploadId}.fig`
+ const expiresAt = new Date(Date.now() + UPLOAD_LIFETIME_MS)
+ await database.transaction().execute(async (transaction) => {
+ await transaction
+ .insertInto('upload')
+ .values({
+ id: uploadId,
+ documentId,
+ baseRevisionId: input.baseRevisionId,
+ objectKey,
+ checksum: input.checksum,
+ byteSize: input.byteSize,
+ contentType: input.contentType,
+ multipartUploadId: null,
+ status: 'pending',
+ finalizationStartedAt: null,
+ createdBy: userId,
+ expiresAt
+ })
+ .execute()
+ await quota.reserveInTransaction(transaction, {
+ workspaceId: document.workspaceId,
+ uploadId,
+ bytes: input.byteSize,
+ expiresAt,
+ maximumBytes: maximumStorageBytes === Number.MAX_SAFE_INTEGER ? null : maximumStorageBytes
+ })
+ })
+ let objectUpload
+ try {
+ objectUpload = await objects.createUpload({
+ key: objectKey,
+ byteSize: input.byteSize,
+ checksum: input.checksum,
+ contentType: input.contentType,
+ expiresAt
+ })
+ } catch (error) {
+ await quota.release(uploadId)
+ await database
+ .updateTable('upload')
+ .set({ status: 'abandoned' })
+ .where('id', '=', uploadId)
+ .execute()
+ throw error
+ }
+ if (objectUpload.kind === 'multipart') {
+ await database
+ .updateTable('upload')
+ .set({ multipartUploadId: objectUpload.uploadId })
+ .where('id', '=', uploadId)
+ .execute()
+ }
+ return { id: uploadId, upload: objectUpload }
+ },
+
+ async commitUpload(
+ userId: string,
+ uploadId: string,
+ input: CommitUploadInput
+ ): Promise<DocumentSummary> {
+ const upload = await database
+ .selectFrom('upload')
+ .innerJoin('document', 'document.id', 'upload.documentId')
+ .select([
+ 'upload.documentId',
+ 'upload.baseRevisionId',
+ 'upload.objectKey',
+ 'upload.checksum',
+ 'upload.byteSize',
+ 'upload.contentType',
+ 'upload.multipartUploadId',
+ 'upload.status',
+ 'upload.expiresAt'
+ ])
+ .where('upload.id', '=', uploadId)
+ .where('upload.createdBy', '=', userId)
+ .executeTakeFirst()
+ if (!upload) throw new DocumentNotFoundError()
+ const access = await resolveDocumentAccess(database, userId, upload.documentId)
+ if (!access) throw new DocumentNotFoundError()
+ if (!canEditDocument(access)) throw new DocumentForbiddenError()
+ if (input.checksum !== upload.checksum) throw new UploadInvalidError()
+ if (upload.status === 'committed') {
+ const document = await findDocument(database, userId, upload.documentId)
+ if (!document) throw new DocumentNotFoundError()
+ return document
+ }
+ if (upload.status !== 'pending' || new Date(upload.expiresAt).getTime() <= Date.now()) {
+ throw new UploadInvalidError()
+ }
+ const claimed = await database
+ .updateTable('upload')
+ .set({ status: 'finalizing', finalizationStartedAt: new Date() })
+ .where('id', '=', uploadId)
+ .where('status', '=', 'pending')
+ .returning('id')
+ .executeTakeFirst()
+ if (!claimed) throw new UploadInvalidError()
+ try {
+ if (input.multipart) {
+ if (
+ !objects.capabilities.multipartUpload ||
+ input.multipart.uploadId !== upload.multipartUploadId
+ ) {
+ throw new UploadInvalidError()
+ }
+ await objects.completeUpload({
+ key: upload.objectKey,
+ uploadId: input.multipart.uploadId,
+ parts: input.multipart.parts
+ })
+ }
+ const stored = await objects.head(upload.objectKey)
+ if (
+ !stored ||
+ stored.checksum !== input.checksum ||
+ stored.checksum !== upload.checksum ||
+ stored.byteSize !== Number(upload.byteSize) ||
+ stored.contentType !== upload.contentType
+ ) {
+ throw new UploadInvalidError()
+ }
+
+ const revisionId = crypto.randomUUID()
+ const storageObjectId = crypto.randomUUID()
+ await database.transaction().execute(async (transaction) => {
+ const lockedUpload = await transaction
+ .selectFrom('upload')
+ .select('status')
+ .where('id', '=', uploadId)
+ .forUpdate()
+ .executeTakeFirstOrThrow()
+ if (lockedUpload.status === 'committed') return
+ if (lockedUpload.status !== 'finalizing') throw new UploadInvalidError()
+ const document = await transaction
+ .selectFrom('document')
+ .select(['currentRevisionId'])
+ .where('id', '=', upload.documentId)
+ .forUpdate()
+ .executeTakeFirstOrThrow()
+ if (document.currentRevisionId !== upload.baseRevisionId) {
+ throw new DocumentConflictError()
+ }
+ await transaction
+ .insertInto('storageObject')
+ .values({
+ id: storageObjectId,
+ objectKey: upload.objectKey,
+ checksum: stored.checksum,
+ byteSize: stored.byteSize,
+ contentType: stored.contentType
+ })
+ .execute()
+ await transaction
+ .insertInto('documentRevision')
+ .values({
+ id: revisionId,
+ documentId: upload.documentId,
+ parentRevisionId: upload.baseRevisionId,
+ storageObjectId,
+ createdBy: userId
+ })
+ .execute()
+ await transaction
+ .updateTable('document')
+ .set({
+ currentRevisionId: revisionId,
+ version: (expression) => expression('version', '+', 1)
+ })
+ .where('id', '=', upload.documentId)
+ .execute()
+ await transaction
+ .updateTable('upload')
+ .set({ status: 'committed', finalizationStartedAt: null })
+ .where('id', '=', uploadId)
+ .execute()
+ await quota.commitInTransaction(transaction, uploadId)
+ })
+ } catch (error) {
+ await database
+ .updateTable('upload')
+ .set({ status: 'pending', finalizationStartedAt: null })
+ .where('id', '=', uploadId)
+ .where('status', '=', 'finalizing')
+ .execute()
+ throw error
+ }
+ const document = await findDocument(database, userId, upload.documentId)
+ if (!document) throw new DocumentNotFoundError()
+ return document
+ }
+ }
+}
+
+export type DocumentService = ReturnType<typeof createDocumentService>
diff --git a/packages/cloud/src/server/documents/summary.ts b/packages/cloud/src/server/documents/summary.ts
new file mode 100644
index 000000000..5e436e8b4
--- /dev/null
+++ b/packages/cloud/src/server/documents/summary.ts
@@ -0,0 +1,36 @@
+import type { DocumentSummary } from '#cloud/contract'
+import type { DocumentDatabase, DocumentSummaryRow } from '#cloud/server/documents/repository'
+
+const SUMMARY_COLUMNS = [
+ 'id',
+ 'workspaceId',
+ 'name',
+ 'currentRevisionId',
+ 'version',
+ 'createdAt',
+ 'updatedAt'
+] as const
+
+function toISOString(value: Date | string): string {
+ return value instanceof Date ? value.toISOString() : value
+}
+
+export function documentSummary(row: DocumentSummaryRow): DocumentSummary {
+ return {
+ ...row,
+ createdAt: toISOString(row.createdAt),
+ updatedAt: toISOString(row.updatedAt)
+ }
+}
+
+export async function getDocumentSummaryRow(
+ database: DocumentDatabase,
+ documentId: string
+): Promise<DocumentSummaryRow | undefined> {
+ return database
+ .selectFrom('document')
+ .select(SUMMARY_COLUMNS)
+ .where('id', '=', documentId)
+ .where('deletedAt', 'is', null)
+ .executeTakeFirst()
+}
diff --git a/packages/cloud/src/server/documents/types.ts b/packages/cloud/src/server/documents/types.ts
new file mode 100644
index 000000000..00c000ad6
--- /dev/null
+++ b/packages/cloud/src/server/documents/types.ts
@@ -0,0 +1,13 @@
+import type { ObjectUpload } from '#cloud/server/objects'
+
+export type CreateDocumentRecord = {
+ id: string
+ workspaceId: string
+ name: string
+ createdBy: string
+}
+
+export type CreateDocumentUploadResult = {
+ id: string
+ upload: ObjectUpload
+}
diff --git a/packages/cloud/src/server/email/crypto.ts b/packages/cloud/src/server/email/crypto.ts
new file mode 100644
index 000000000..75dce9a57
--- /dev/null
+++ b/packages/cloud/src/server/email/crypto.ts
@@ -0,0 +1,57 @@
+import {
+ transactionalEmailContentSchema,
+ type TransactionalEmailContent,
+ type TransactionalEmailKind,
+ type TransactionalEmailPayloadByKind
+} from '#cloud/email'
+import { hkdf } from '@noble/hashes/hkdf.js'
+import { sha256 } from '@noble/hashes/sha2.js'
+import { utf8ToBytes } from '@noble/hashes/utils.js'
+import { compactDecrypt, CompactEncrypt } from 'jose'
+import * as v from 'valibot'
+
+const EMAIL_PAYLOAD_SALT = utf8ToBytes('openpencil-cloud-transactional-email')
+const EMAIL_PAYLOAD_HEADER = { alg: 'dir', enc: 'A256GCM' } as const
+const encoder = new TextEncoder()
+const decoder = new TextDecoder()
+
+function emailPayloadKey(secret: string, id: string, kind: TransactionalEmailKind): Uint8Array {
+ return hkdf(
+ sha256,
+ utf8ToBytes(secret),
+ EMAIL_PAYLOAD_SALT,
+ encoder.encode(`openpencil-cloud-email:${kind}:${id}`),
+ 32
+ )
+}
+
+export async function encryptTransactionalEmailPayload<Kind extends TransactionalEmailKind>(
+ secret: string,
+ id: string,
+ kind: Kind,
+ payload: TransactionalEmailPayloadByKind[Kind]
+): Promise<string> {
+ return new CompactEncrypt(encoder.encode(JSON.stringify(payload)))
+ .setProtectedHeader(EMAIL_PAYLOAD_HEADER)
+ .encrypt(emailPayloadKey(secret, id, kind))
+}
+
+export async function decryptTransactionalEmailPayload(
+ secret: string,
+ id: string,
+ kind: TransactionalEmailKind,
+ value: string
+): Promise<TransactionalEmailContent> {
+ const { plaintext, protectedHeader } = await compactDecrypt(
+ value,
+ emailPayloadKey(secret, id, kind)
+ )
+ if (
+ protectedHeader.alg !== EMAIL_PAYLOAD_HEADER.alg ||
+ protectedHeader.enc !== EMAIL_PAYLOAD_HEADER.enc
+ ) {
+ throw new Error('Unsupported transactional email payload encryption')
+ }
+ const payload = v.parse(v.pipe(v.string(), v.parseJson()), decoder.decode(plaintext))
+ return v.parse(transactionalEmailContentSchema, { kind, payload })
+}
diff --git a/packages/cloud/src/server/email/index.ts b/packages/cloud/src/server/email/index.ts
new file mode 100644
index 000000000..0c3255518
--- /dev/null
+++ b/packages/cloud/src/server/email/index.ts
@@ -0,0 +1,14 @@
+export { createTransactionalEmailService, TransactionalEmailTransportError } from './service'
+export { createInvitationOutbox } from './invitations'
+export { startTransactionalEmailWorker } from './worker'
+export { decryptTransactionalEmailPayload, encryptTransactionalEmailPayload } from './crypto'
+export type {
+ EnqueueTransactionalEmailInput,
+ TransactionalEmailDeliveryOptions,
+ TransactionalEmailDeliveryResult,
+ TransactionalEmailEnvelope,
+ TransactionalEmailSendResult,
+ TransactionalEmailService,
+ TransactionalEmailTransport
+} from './types'
+export type { TransactionalEmailWorker, TransactionalEmailWorkerOptions } from './worker'
diff --git a/packages/cloud/src/server/email/invitations.ts b/packages/cloud/src/server/email/invitations.ts
new file mode 100644
index 000000000..1100ada12
--- /dev/null
+++ b/packages/cloud/src/server/email/invitations.ts
@@ -0,0 +1,30 @@
+import type { CloudDatabase } from '#cloud/server/db'
+import type { DocumentInvitationMessage, InvitationOutbox } from '#cloud/server/invitations'
+import type { Transaction } from 'kysely'
+
+import type { TransactionalEmailService } from './types'
+
+export function createInvitationOutbox(email: TransactionalEmailService): InvitationOutbox {
+ return {
+ enqueueDocumentInvitation(
+ message: DocumentInvitationMessage,
+ transaction?: Transaction<CloudDatabase>
+ ): Promise<string> {
+ return email.enqueue(
+ {
+ idempotencyKey: `document-invitation/${message.deliveryId}`,
+ kind: 'document-invitation',
+ recipientEmail: message.recipientEmail,
+ payload: {
+ inviterName: message.inviterName,
+ documentName: message.documentName,
+ permission: message.permission,
+ expiresAt: message.expiresAt,
+ acceptanceURL: message.acceptanceURL
+ }
+ },
+ transaction
+ )
+ }
+ }
+}
diff --git a/packages/cloud/src/server/email/service.ts b/packages/cloud/src/server/email/service.ts
new file mode 100644
index 000000000..ac4b25671
--- /dev/null
+++ b/packages/cloud/src/server/email/service.ts
@@ -0,0 +1,245 @@
+import { renderTransactionalEmail } from '#cloud/email'
+import type { TransactionalEmailKind } from '#cloud/email'
+import type { CloudDatabase, TransactionalEmailStatus } from '#cloud/server/db'
+import type { Kysely, Transaction } from 'kysely'
+
+import { decryptTransactionalEmailPayload, encryptTransactionalEmailPayload } from './crypto'
+import type {
+ EnqueueTransactionalEmailInput,
+ TransactionalEmailDeliveryOptions,
+ TransactionalEmailDeliveryResult,
+ TransactionalEmailService,
+ TransactionalEmailTransport
+} from './types'
+
+const DEFAULT_MAXIMUM_ATTEMPTS = 5
+const MAXIMUM_RETRY_DELAY_MS = 60 * 60_000
+
+export type TransactionalEmailTransportErrorKind =
+ | 'configuration'
+ | 'suppressed'
+ | 'permanent'
+ | 'rate-limited'
+ | 'transient'
+
+export class TransactionalEmailTransportError extends Error {
+ override readonly name = 'TransactionalEmailTransportError'
+
+ constructor(
+ readonly kind: TransactionalEmailTransportErrorKind,
+ readonly code: string,
+ message: string,
+ options?: ErrorOptions
+ ) {
+ super(message, options)
+ }
+}
+
+type ClaimedTransactionalEmail = {
+ id: string
+ kind: TransactionalEmailKind
+ recipientEmailNormalized: string
+ payloadEncrypted: string
+ attemptCount: number
+}
+
+function normalizedEmail(value: string): string {
+ return value.trim().toLowerCase()
+}
+
+function retryDelayMilliseconds(attemptCount: number): number {
+ return Math.min(MAXIMUM_RETRY_DELAY_MS, 2 ** Math.max(0, attemptCount - 1) * 30_000)
+}
+
+function transportFailure(error: unknown): TransactionalEmailTransportError {
+ return error instanceof TransactionalEmailTransportError
+ ? error
+ : new TransactionalEmailTransportError(
+ 'transient',
+ 'transport_error',
+ 'Transactional email transport failed',
+ { cause: error }
+ )
+}
+
+function failureStatus(
+ error: TransactionalEmailTransportError,
+ attemptCount: number,
+ maximumAttempts: number
+): TransactionalEmailStatus {
+ if (error.kind === 'suppressed') return 'suppressed'
+ if (error.kind === 'configuration' || error.kind === 'permanent') return 'failed'
+ return attemptCount >= maximumAttempts ? 'failed' : 'pending'
+}
+
+export function createTransactionalEmailService(
+ database: Kysely<CloudDatabase>,
+ options: {
+ encryptionSecret: string
+ from: string
+ transport?: TransactionalEmailTransport
+ }
+): TransactionalEmailService {
+ return {
+ async enqueue<Kind extends TransactionalEmailKind>(
+ input: EnqueueTransactionalEmailInput<Kind>,
+ transaction: Transaction<CloudDatabase> | undefined
+ ): Promise<string> {
+ const id = crypto.randomUUID()
+ const payloadEncrypted = await encryptTransactionalEmailPayload(
+ options.encryptionSecret,
+ id,
+ input.kind,
+ input.payload
+ )
+ const executor = transaction ?? database
+ const row = await executor
+ .insertInto('transactionalEmail')
+ .values({
+ id,
+ idempotencyKey: input.idempotencyKey,
+ kind: input.kind,
+ recipientEmailNormalized: normalizedEmail(input.recipientEmail),
+ payloadEncrypted,
+ status: 'pending',
+ nextAttemptAt: new Date(),
+ claimId: null,
+ claimedAt: null,
+ transport: null,
+ transportMessageId: null,
+ lastErrorCode: null,
+ acceptedAt: null
+ })
+ .onConflict((conflict) => conflict.column('idempotencyKey').doNothing())
+ .returning('id')
+ .executeTakeFirst()
+ if (row) return row.id
+ return (
+ await executor
+ .selectFrom('transactionalEmail')
+ .select('id')
+ .where('idempotencyKey', '=', input.idempotencyKey)
+ .executeTakeFirstOrThrow()
+ ).id
+ },
+
+ async deliverPending(
+ deliveryOptions: TransactionalEmailDeliveryOptions
+ ): Promise<TransactionalEmailDeliveryResult> {
+ if (!options.transport) {
+ return { claimed: 0, accepted: 0, retrying: 0, failed: 0, suppressed: 0 }
+ }
+ const now = deliveryOptions.now ?? new Date()
+ const maximumAttempts = deliveryOptions.maximumAttempts ?? DEFAULT_MAXIMUM_ATTEMPTS
+ const staleBefore = new Date(now.getTime() - deliveryOptions.leaseDurationMs)
+ const claimId = crypto.randomUUID()
+ const claimed = await database.transaction().execute(async (transaction) => {
+ const candidates = await transaction
+ .selectFrom('transactionalEmail')
+ .select(['id', 'kind', 'recipientEmailNormalized', 'payloadEncrypted', 'attemptCount'])
+ .where('payloadEncrypted', 'is not', null)
+ .where((expression) =>
+ expression.or([
+ expression.and([
+ expression('status', '=', 'pending'),
+ expression('nextAttemptAt', '<=', now)
+ ]),
+ expression.and([
+ expression('status', '=', 'sending'),
+ expression('claimedAt', '<=', staleBefore)
+ ])
+ ])
+ )
+ .orderBy('nextAttemptAt')
+ .limit(deliveryOptions.batchSize)
+ .forUpdate()
+ .skipLocked()
+ .execute()
+ if (candidates.length === 0) return []
+ await transaction
+ .updateTable('transactionalEmail')
+ .set({ status: 'sending', claimId, claimedAt: now, updatedAt: now })
+ .where(
+ 'id',
+ 'in',
+ candidates.map((candidate) => candidate.id)
+ )
+ .execute()
+ return candidates.filter(
+ (candidate): candidate is ClaimedTransactionalEmail => candidate.payloadEncrypted !== null
+ )
+ })
+
+ const result: TransactionalEmailDeliveryResult = {
+ claimed: claimed.length,
+ accepted: 0,
+ retrying: 0,
+ failed: 0,
+ suppressed: 0
+ }
+ for (const message of claimed) {
+ const attemptCount = message.attemptCount + 1
+ try {
+ const content = await decryptTransactionalEmailPayload(
+ options.encryptionSecret,
+ message.id,
+ message.kind,
+ message.payloadEncrypted
+ )
+ const rendered = await renderTransactionalEmail(content)
+ const sent = await options.transport.send({
+ deliveryId: message.id,
+ from: options.from,
+ to: message.recipientEmailNormalized,
+ subject: rendered.subject,
+ html: rendered.html,
+ text: rendered.text,
+ headers: { 'X-OpenPencil-Delivery-ID': message.id }
+ })
+ await database
+ .updateTable('transactionalEmail')
+ .set({
+ payloadEncrypted: null,
+ status: 'accepted',
+ attemptCount,
+ transport: options.transport.id,
+ transportMessageId: sent.transportMessageId,
+ lastErrorCode: null,
+ acceptedAt: new Date(sent.acceptedAt),
+ claimId: null,
+ claimedAt: null,
+ updatedAt: now
+ })
+ .where('id', '=', message.id)
+ .where('claimId', '=', claimId)
+ .execute()
+ result.accepted++
+ } catch (unknownError) {
+ const error = transportFailure(unknownError)
+ const status = failureStatus(error, attemptCount, maximumAttempts)
+ const terminal = status === 'failed' || status === 'suppressed'
+ await database
+ .updateTable('transactionalEmail')
+ .set({
+ payloadEncrypted: terminal ? null : message.payloadEncrypted,
+ status,
+ attemptCount,
+ nextAttemptAt: new Date(now.getTime() + retryDelayMilliseconds(attemptCount)),
+ transport: options.transport.id,
+ lastErrorCode: error.code,
+ claimId: null,
+ claimedAt: null,
+ updatedAt: now
+ })
+ .where('id', '=', message.id)
+ .where('claimId', '=', claimId)
+ .execute()
+ if (status === 'suppressed') result.suppressed++
+ else if (status === 'failed') result.failed++
+ else result.retrying++
+ }
+ }
+ return result
+ }
+ }
+}
diff --git a/packages/cloud/src/server/email/types.ts b/packages/cloud/src/server/email/types.ts
new file mode 100644
index 000000000..3808b3e36
--- /dev/null
+++ b/packages/cloud/src/server/email/types.ts
@@ -0,0 +1,56 @@
+import type {
+ RenderedTransactionalEmail,
+ TransactionalEmailKind,
+ TransactionalEmailPayloadByKind
+} from '#cloud/email'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { Transaction } from 'kysely'
+
+export type TransactionalEmailEnvelope = RenderedTransactionalEmail & {
+ deliveryId: string
+ from: string
+ to: string
+ headers: Record<string, string>
+}
+
+export type TransactionalEmailSendResult = {
+ transportMessageId: string
+ acceptedAt: string
+}
+
+export type TransactionalEmailTransport = {
+ id: string
+ send(envelope: TransactionalEmailEnvelope): Promise<TransactionalEmailSendResult>
+}
+
+export type EnqueueTransactionalEmailInput<Kind extends TransactionalEmailKind> = {
+ idempotencyKey: string
+ kind: Kind
+ recipientEmail: string
+ payload: TransactionalEmailPayloadByKind[Kind]
+}
+
+export type TransactionalEmailDeliveryOptions = {
+ batchSize: number
+ leaseDurationMs: number
+ maximumAttempts?: number
+ now?: Date
+}
+
+export type TransactionalEmailDeliveryResult = {
+ claimed: number
+ accepted: number
+ retrying: number
+ failed: number
+ suppressed: number
+}
+
+export type TransactionalEmailService = {
+ enqueue<Kind extends TransactionalEmailKind>(
+ input: EnqueueTransactionalEmailInput<Kind>,
+ transaction?: Transaction<CloudDatabase>
+ ): Promise<string>
+ deliverPending(
+ options: TransactionalEmailDeliveryOptions
+ ): Promise<TransactionalEmailDeliveryResult>
+}
diff --git a/packages/cloud/src/server/email/worker.ts b/packages/cloud/src/server/email/worker.ts
new file mode 100644
index 000000000..0fc1dc90c
--- /dev/null
+++ b/packages/cloud/src/server/email/worker.ts
@@ -0,0 +1,33 @@
+import { startPeriodicWorker } from '../worker/periodic'
+import type { TransactionalEmailDeliveryResult, TransactionalEmailService } from './types'
+
+export type TransactionalEmailWorkerOptions = {
+ batchSize: number
+ intervalMs: number
+ leaseDurationMs: number
+ maximumAttempts: number
+ signal?: AbortSignal
+ onError?: (error: unknown) => void
+}
+
+export type TransactionalEmailWorker = {
+ runOnce(): Promise<TransactionalEmailDeliveryResult>
+ stop(): Promise<void>
+}
+
+export function startTransactionalEmailWorker(
+ email: TransactionalEmailService,
+ options: TransactionalEmailWorkerOptions
+): TransactionalEmailWorker {
+ return startPeriodicWorker({
+ intervalMs: options.intervalMs,
+ signal: options.signal,
+ onError: options.onError,
+ run: () =>
+ email.deliverPending({
+ batchSize: options.batchSize,
+ leaseDurationMs: options.leaseDurationMs,
+ maximumAttempts: options.maximumAttempts
+ })
+ })
+}
diff --git a/packages/cloud/src/server/index.ts b/packages/cloud/src/server/index.ts
new file mode 100644
index 000000000..871abe5a9
--- /dev/null
+++ b/packages/cloud/src/server/index.ts
@@ -0,0 +1,231 @@
+export {
+ adminErrorStatus,
+ AdminDomainError,
+ createAdminAuditService,
+ createAdminEmailService,
+ createAdminOperationsService,
+ createAdminUserService,
+ createCloudAdminRoutes,
+ createEnrollmentService,
+ normalizeEnrollmentEmail,
+ type AdminAuditService,
+ type AdminErrorCode,
+ type AdminEmailService,
+ type AdminOperationsService,
+ type AdminUserService,
+ type CloudAdminServices,
+ type EnrollmentMode,
+ type EnrollmentRecord,
+ type EnrollmentService,
+ type EnrollmentStatus
+} from '#cloud/admin'
+export {
+ createAuthenticationEmailService,
+ createAccountAuthenticationService,
+ createCloudAuthenticationRuntime,
+ createBetterAuthAdapter,
+ createCloudIdentityResolver,
+ createCloudSessionResolver,
+ type CloudActor,
+ type CloudAuthAdapter,
+ type CloudAuthRuntimeOptions,
+ type CloudIdentity,
+ type CloudIdentityResolver,
+ type CloudSessionResolver,
+ type AccountAuthenticationService,
+ type AuthenticationEmailService,
+ workspaceAccessControl,
+ workspaceRoles,
+ workspaceStatements
+} from './auth'
+export {
+ createCloudAPIRouter,
+ createPublicCloudAPIRouter,
+ type CloudAPI,
+ type CloudAPIEnvironment,
+ type CloudAPIServices,
+ type PublicCloudAPI
+} from './api'
+export {
+ createCloudApp,
+ shouldPreventIndexing,
+ withIndexingPolicy,
+ type CloudApp,
+ type CloudServices
+} from './app'
+export {
+ createDocumentCleanupService,
+ createUploadCleanupService,
+ startCleanupWorker,
+ type CleanupResult,
+ type CleanupServices,
+ type CleanupWorker,
+ type CleanupWorkerOptions,
+ type DocumentCleanupOptions,
+ type DocumentCleanupResult,
+ type DocumentCleanupService,
+ type UploadCleanupOptions,
+ type UploadCleanupResult,
+ type UploadCleanupService
+} from './cleanup'
+export {
+ createCollaborationRoutes,
+ createCollaborationTicketService,
+ createPublicCollaborationRoutes,
+ type CollaborationRouteEnvironment,
+ type CollaborationTicketService
+} from './collaboration'
+export {
+ CloudConfigError,
+ cloudDeploymentConfigSchema,
+ cloudDiscoveryFromConfig,
+ configuredSocialProviders,
+ parseCloudDeploymentConfig,
+ parseCloudDeploymentSource,
+ parseCloudDeploymentTOML,
+ parseCloudServerConfig,
+ CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES,
+ CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM,
+ CLOUD_PROTOCOL_MAX_UPLOAD_BYTES,
+ type CloudDeploymentConfig,
+ type CloudDeploymentInput,
+ type CloudEnvironment,
+ type CloudSecretReference,
+ type CloudServerConfig,
+ type CloudTechnicalLimits
+} from './config'
+export {
+ createCloudDatabase,
+ migrateCloudDatabase,
+ type CloudDatabase,
+ type CloudDatabaseOptions,
+ type Document,
+ type DocumentRevision,
+ type NewDocument,
+ type NewDocumentRevision,
+ type NewStorageObject,
+ type NewTransactionalEmail,
+ type NewUpload,
+ type NewWorkspace,
+ type StorageObject,
+ type TransactionalEmail,
+ type TransactionalEmailStatus,
+ type Upload,
+ type UploadStatus,
+ type Workspace,
+ type WorkspaceUpdate
+} from './db'
+export {
+ canEditDocument,
+ createDocumentRoutes,
+ createDocumentService,
+ DocumentConflictError,
+ DocumentForbiddenError,
+ DocumentNotFoundError,
+ resolveDocumentAccess,
+ UploadInvalidError,
+ type AccessDatabase,
+ type DocumentRouteEnvironment,
+ type DocumentService
+} from './documents'
+export {
+ createInvitationOutbox,
+ createTransactionalEmailService,
+ startTransactionalEmailWorker,
+ decryptTransactionalEmailPayload,
+ encryptTransactionalEmailPayload,
+ TransactionalEmailTransportError,
+ type EnqueueTransactionalEmailInput,
+ type TransactionalEmailDeliveryOptions,
+ type TransactionalEmailDeliveryResult,
+ type TransactionalEmailEnvelope,
+ type TransactionalEmailSendResult,
+ type TransactionalEmailService,
+ type TransactionalEmailTransport,
+ type TransactionalEmailWorker,
+ type TransactionalEmailWorkerOptions
+} from './email'
+export {
+ noOpInvitationDelivery,
+ type DocumentInvitationMessage,
+ type InvitationDelivery,
+ type InvitationOutbox
+} from './invitations'
+export type {
+ AbortObjectUploadInput,
+ CompletedObjectPart,
+ CompleteObjectUploadInput,
+ CreateObjectDownloadInput,
+ CreateObjectUploadInput,
+ ObjectDownload,
+ ObjectMultipartUpload,
+ ObjectSingleUpload,
+ ObjectStore,
+ ObjectStoreCapabilities,
+ ObjectStoreReadiness,
+ ObjectUpload,
+ ObjectUploadPart,
+ StoredObject
+} from './objects'
+export {
+ capabilityHashMatches,
+ createDocumentSharingRoutes,
+ createDocumentSharingService,
+ createPublicDocumentRoutes,
+ createPublicSharingRoutes,
+ decryptContinuationToken,
+ DocumentShareInvalidError,
+ encryptContinuationToken,
+ hashCapability,
+ type DocumentShareCapability,
+ type DocumentSharingService,
+ type ResolvedDocumentShare,
+ type ResolvedSharePrincipal,
+ type SharingRouteEnvironment
+} from './sharing'
+export {
+ CLOUD_FEATURE_KEYS,
+ CloudPolicy,
+ createWorkspaceEntitlementRepository,
+ DatabaseEntitlementSource,
+ EntitlementOpenFeatureProvider,
+ createDefaultCloudPolicy,
+ createEntitlementService,
+ StaticEntitlementSource,
+ parseStaticEntitlementsTOML,
+ staticEntitlementValues,
+ staticEntitlementsSchema,
+ type CloudPolicyContext,
+ type EntitlementSource,
+ type EntitlementService,
+ type EntitlementSubject,
+ type StaticEntitlements
+} from './policy'
+export {
+ createStorageQuotaService,
+ createStorageReconciliationService,
+ StorageQuotaExceededError,
+ type StorageQuotaService,
+ type StorageQuotaSnapshot,
+ type StorageReconciliation
+} from './quota'
+export {
+ CLOUD_RATE_LIMITS,
+ createActorRateLimiter,
+ createCloudRateLimiter,
+ createRateLimitCleanupService,
+ createTrustedIPRateLimiter,
+ PostgresRateLimitStore,
+ rateLimitKey,
+ trustedClientIP,
+ type ClientIdentityOptions,
+ type RateLimitCleanupService,
+ type RateLimitPolicy
+} from './rate-limit'
+export {
+ createWorkspaceRoutes,
+ createWorkspaceService,
+ WorkspaceSlugConflictError,
+ type WorkspaceRouteEnvironment,
+ type WorkspaceService
+} from './workspaces'
diff --git a/packages/cloud/src/server/invitations/index.ts b/packages/cloud/src/server/invitations/index.ts
new file mode 100644
index 000000000..60e218d8f
--- /dev/null
+++ b/packages/cloud/src/server/invitations/index.ts
@@ -0,0 +1,6 @@
+export {
+ noOpInvitationDelivery,
+ type DocumentInvitationMessage,
+ type InvitationDelivery,
+ type InvitationOutbox
+} from './types'
diff --git a/packages/cloud/src/server/invitations/types.ts b/packages/cloud/src/server/invitations/types.ts
new file mode 100644
index 000000000..d7887962a
--- /dev/null
+++ b/packages/cloud/src/server/invitations/types.ts
@@ -0,0 +1,30 @@
+import type { DocumentPermission } from '#cloud/contract'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { Transaction } from 'kysely'
+
+export type DocumentInvitationMessage = {
+ deliveryId: string
+ recipientEmail: string
+ inviterName: string
+ documentName: string
+ permission: DocumentPermission
+ expiresAt: string
+ acceptanceURL: string
+}
+
+export type InvitationDelivery = {
+ sendDocumentInvitation(message: DocumentInvitationMessage): Promise<void>
+}
+
+export type InvitationOutbox = {
+ enqueueDocumentInvitation(
+ message: DocumentInvitationMessage,
+ transaction?: Transaction<CloudDatabase>
+ ): Promise<string>
+}
+
+export const noOpInvitationDelivery: InvitationDelivery = {
+ async sendDocumentInvitation() {
+ return undefined
+ }
+}
diff --git a/packages/cloud/src/server/objects/index.ts b/packages/cloud/src/server/objects/index.ts
new file mode 100644
index 000000000..b3578b75a
--- /dev/null
+++ b/packages/cloud/src/server/objects/index.ts
@@ -0,0 +1,16 @@
+export type {
+ AbortObjectUploadInput,
+ CompletedObjectPart,
+ CompleteObjectUploadInput,
+ CreateObjectDownloadInput,
+ CreateObjectUploadInput,
+ ObjectDownload,
+ ObjectMultipartUpload,
+ ObjectSingleUpload,
+ ObjectStore,
+ ObjectStoreCapabilities,
+ ObjectStoreReadiness,
+ ObjectUpload,
+ ObjectUploadPart,
+ StoredObject
+} from './types'
diff --git a/packages/cloud/src/server/objects/types.ts b/packages/cloud/src/server/objects/types.ts
new file mode 100644
index 000000000..d21430101
--- /dev/null
+++ b/packages/cloud/src/server/objects/types.ts
@@ -0,0 +1,81 @@
+export type ObjectDownload = {
+ url: string
+ method: 'GET'
+ headers: Readonly<Record<string, string>>
+ expiresAt: string
+}
+
+export type ObjectStoreCapabilities = {
+ nativeSHA256: boolean
+ multipartUpload: boolean
+ conditionalWrites: boolean
+}
+
+export type ObjectStoreReadiness = {
+ ok: boolean
+ checksumVerification: 'native' | 'metadata'
+}
+
+export type ObjectUploadPart = {
+ partNumber: number
+ url: string
+ method: 'PUT'
+ headers: Readonly<Record<string, string>>
+}
+
+export type ObjectMultipartUpload = {
+ kind: 'multipart'
+ uploadId: string
+ partSize: number
+ parts: ObjectUploadPart[]
+ expiresAt: string
+}
+
+export type ObjectSingleUpload = {
+ kind: 'single'
+ url: string
+ method: 'PUT'
+ headers: Readonly<Record<string, string>>
+ expiresAt: string
+}
+
+export type ObjectUpload = ObjectSingleUpload | ObjectMultipartUpload
+
+export type CompletedObjectPart = { partNumber: number; etag: string }
+
+export type CreateObjectDownloadInput = {
+ key: string
+ expiresAt: Date
+}
+
+export type CreateObjectUploadInput = CreateObjectDownloadInput & {
+ byteSize: number
+ checksum: string
+ contentType: string
+}
+
+export type CompleteObjectUploadInput = {
+ key: string
+ uploadId: string
+ parts: CompletedObjectPart[]
+}
+
+export type AbortObjectUploadInput = Omit<CompleteObjectUploadInput, 'parts'>
+
+export type StoredObject = {
+ byteSize: number
+ checksum: string
+ checksumVerification: 'native' | 'metadata'
+ contentType: string
+}
+
+export interface ObjectStore {
+ readonly capabilities: ObjectStoreCapabilities
+ checkReadiness(): Promise<ObjectStoreReadiness>
+ createDownload(input: CreateObjectDownloadInput): Promise<ObjectDownload>
+ createUpload(input: CreateObjectUploadInput): Promise<ObjectUpload>
+ completeUpload(input: CompleteObjectUploadInput): Promise<void>
+ abortUpload(input: AbortObjectUploadInput): Promise<void>
+ head(key: string): Promise<StoredObject | null>
+ delete(key: string): Promise<void>
+}
diff --git a/packages/cloud/src/server/policy/database.ts b/packages/cloud/src/server/policy/database.ts
new file mode 100644
index 000000000..d3f50f202
--- /dev/null
+++ b/packages/cloud/src/server/policy/database.ts
@@ -0,0 +1,74 @@
+import type { CloudDatabase } from '#cloud/server/db'
+import type { Kysely } from 'kysely'
+import * as v from 'valibot'
+
+import type { EntitlementSource, EntitlementSubject } from './entitlements'
+import {
+ staticEntitlementValues,
+ staticEntitlementsSchema,
+ type StaticEntitlements
+} from './static'
+
+export class DatabaseEntitlementSource implements EntitlementSource {
+ constructor(private readonly database: Kysely<CloudDatabase>) {}
+
+ private async values(subject: EntitlementSubject): Promise<Record<string, boolean | number>> {
+ if (subject.type !== 'workspace') return {}
+ const row = await this.database
+ .selectFrom('workspaceEntitlement')
+ .select('values')
+ .where('workspaceId', '=', subject.id)
+ .executeTakeFirst()
+ return row ? staticEntitlementValues(v.parse(staticEntitlementsSchema, row.values)) : {}
+ }
+
+ async boolean(subject: EntitlementSubject, key: string): Promise<boolean | null> {
+ const value = (await this.values(subject))[key]
+ return typeof value === 'boolean' ? value : null
+ }
+
+ async number(subject: EntitlementSubject, key: string): Promise<number | null> {
+ const value = (await this.values(subject))[key]
+ return typeof value === 'number' ? value : null
+ }
+
+ async string(_subject: EntitlementSubject, _key: string): Promise<string | null> {
+ return null
+ }
+}
+
+export function createWorkspaceEntitlementRepository(database: Kysely<CloudDatabase>) {
+ return {
+ async get(workspaceId: string) {
+ return database
+ .selectFrom('workspaceEntitlement')
+ .selectAll()
+ .where('workspaceId', '=', workspaceId)
+ .executeTakeFirst()
+ },
+
+ async set(workspaceId: string, values: StaticEntitlements, source: string) {
+ const validated = v.parse(staticEntitlementsSchema, values)
+ return database
+ .insertInto('workspaceEntitlement')
+ .values({ workspaceId, values: validated, source })
+ .onConflict((conflict) =>
+ conflict.column('workspaceId').doUpdateSet({
+ values: validated,
+ source,
+ revision: (expression) => expression('workspaceEntitlement.revision', '+', 1),
+ updatedAt: new Date()
+ })
+ )
+ .returningAll()
+ .executeTakeFirstOrThrow()
+ },
+
+ async clear(workspaceId: string): Promise<void> {
+ await database
+ .deleteFrom('workspaceEntitlement')
+ .where('workspaceId', '=', workspaceId)
+ .execute()
+ }
+ }
+}
diff --git a/packages/cloud/src/server/policy/entitlements.ts b/packages/cloud/src/server/policy/entitlements.ts
new file mode 100644
index 000000000..f3e340399
--- /dev/null
+++ b/packages/cloud/src/server/policy/entitlements.ts
@@ -0,0 +1,29 @@
+export type EntitlementSubject = {
+ type: 'workspace' | 'user' | 'organization' | 'deployment'
+ id: string
+}
+
+export type EntitlementSource = {
+ boolean(subject: EntitlementSubject, key: string): Promise<boolean | null>
+ number(subject: EntitlementSubject, key: string): Promise<number | null>
+ string(subject: EntitlementSubject, key: string): Promise<string | null>
+}
+
+export class StaticEntitlementSource implements EntitlementSource {
+ constructor(private readonly values: Readonly<Record<string, boolean | number | string>>) {}
+
+ async boolean(_subject: EntitlementSubject, key: string): Promise<boolean | null> {
+ const value = this.values[key]
+ return typeof value === 'boolean' ? value : null
+ }
+
+ async number(_subject: EntitlementSubject, key: string): Promise<number | null> {
+ const value = this.values[key]
+ return typeof value === 'number' ? value : null
+ }
+
+ async string(_subject: EntitlementSubject, key: string): Promise<string | null> {
+ const value = this.values[key]
+ return typeof value === 'string' ? value : null
+ }
+}
diff --git a/packages/cloud/src/server/policy/index.ts b/packages/cloud/src/server/policy/index.ts
new file mode 100644
index 000000000..fc48ed47c
--- /dev/null
+++ b/packages/cloud/src/server/policy/index.ts
@@ -0,0 +1,16 @@
+export { createWorkspaceEntitlementRepository, DatabaseEntitlementSource } from './database'
+export {
+ StaticEntitlementSource,
+ type EntitlementSource,
+ type EntitlementSubject
+} from './entitlements'
+export { CLOUD_FEATURE_KEYS, type CloudPolicyContext } from './keys'
+export { EntitlementOpenFeatureProvider } from './provider'
+export {
+ parseStaticEntitlementsTOML,
+ staticEntitlementValues,
+ staticEntitlementsSchema,
+ type StaticEntitlements
+} from './static'
+export { CloudPolicy, createDefaultCloudPolicy } from './policy'
+export { createEntitlementService, type EntitlementService } from './service'
diff --git a/packages/cloud/src/server/policy/keys.ts b/packages/cloud/src/server/policy/keys.ts
new file mode 100644
index 000000000..bea971d04
--- /dev/null
+++ b/packages/cloud/src/server/policy/keys.ts
@@ -0,0 +1,21 @@
+export const CLOUD_FEATURE_KEYS = {
+ capabilityLinks: 'cloud.sharing.capability-links',
+ anonymousView: 'cloud.sharing.anonymous-view',
+ anonymousEdit: 'cloud.sharing.anonymous-edit',
+ guestPresence: 'cloud.sharing.guest-presence',
+ collaboration: 'cloud.collaboration.enabled',
+ serverEnforcedWrites: 'cloud.collaboration.server-enforced-writes',
+ revisionHistory: 'cloud.documents.revision-history',
+ maximumFileBytes: 'cloud.documents.maximum-file-bytes',
+ maximumStorageBytes: 'cloud.storage.maximum-bytes',
+ maximumParticipants: 'cloud.collaboration.maximum-participants'
+} as const
+
+export type CloudPolicyContext = {
+ targetingKey: string
+ actorId?: string
+ workspaceId?: string
+ organizationId?: string
+ documentId?: string
+ deploymentMode: 'official' | 'self-hosted'
+}
diff --git a/packages/cloud/src/server/policy/policy.ts b/packages/cloud/src/server/policy/policy.ts
new file mode 100644
index 000000000..24fb5f681
--- /dev/null
+++ b/packages/cloud/src/server/policy/policy.ts
@@ -0,0 +1,83 @@
+import { CLOUD_PROTOCOL_MAX_UPLOAD_BYTES } from '#cloud/server/config'
+import {
+ OpenFeature,
+ TypedInMemoryProvider,
+ type Client,
+ type EvaluationContext,
+ type Provider
+} from '@openfeature/server-sdk'
+
+import { CLOUD_FEATURE_KEYS, type CloudPolicyContext } from './keys'
+
+const DEFAULT_FLAGS = {
+ [CLOUD_FEATURE_KEYS.capabilityLinks]: {
+ variants: { enabled: true, disabled: false },
+ defaultVariant: 'enabled',
+ disabled: false
+ },
+ [CLOUD_FEATURE_KEYS.anonymousView]: {
+ variants: { enabled: true, disabled: false },
+ defaultVariant: 'enabled',
+ disabled: false
+ },
+ [CLOUD_FEATURE_KEYS.anonymousEdit]: {
+ variants: { enabled: true, disabled: false },
+ defaultVariant: 'enabled',
+ disabled: false
+ },
+ [CLOUD_FEATURE_KEYS.guestPresence]: {
+ variants: { enabled: true, disabled: false },
+ defaultVariant: 'enabled',
+ disabled: false
+ },
+ [CLOUD_FEATURE_KEYS.collaboration]: {
+ variants: { enabled: true, disabled: false },
+ defaultVariant: 'enabled',
+ disabled: false
+ },
+ [CLOUD_FEATURE_KEYS.serverEnforcedWrites]: {
+ variants: { enabled: false, disabled: false },
+ defaultVariant: 'disabled',
+ disabled: false
+ },
+ [CLOUD_FEATURE_KEYS.revisionHistory]: {
+ variants: { enabled: true, disabled: false },
+ defaultVariant: 'enabled',
+ disabled: false
+ },
+ [CLOUD_FEATURE_KEYS.maximumFileBytes]: {
+ variants: { default: CLOUD_PROTOCOL_MAX_UPLOAD_BYTES },
+ defaultVariant: 'default',
+ disabled: false
+ }
+} as const
+
+function evaluationContext(context: CloudPolicyContext): EvaluationContext {
+ const evaluation: EvaluationContext = {
+ targetingKey: context.targetingKey,
+ deploymentMode: context.deploymentMode
+ }
+ if (context.actorId) evaluation.actorId = context.actorId
+ if (context.workspaceId) evaluation.workspaceId = context.workspaceId
+ if (context.organizationId) evaluation.organizationId = context.organizationId
+ if (context.documentId) evaluation.documentId = context.documentId
+ return evaluation
+}
+
+export class CloudPolicy {
+ constructor(private readonly client: Client) {}
+
+ boolean(key: string, defaultValue: boolean, context: CloudPolicyContext): Promise<boolean> {
+ return this.client.getBooleanValue(key, defaultValue, evaluationContext(context))
+ }
+
+ number(key: string, defaultValue: number, context: CloudPolicyContext): Promise<number> {
+ return this.client.getNumberValue(key, defaultValue, evaluationContext(context))
+ }
+}
+
+export function createDefaultCloudPolicy(provider?: Provider): CloudPolicy {
+ const domain = `openpencil-cloud-${crypto.randomUUID()}`
+ OpenFeature.setProvider(domain, provider ?? new TypedInMemoryProvider(DEFAULT_FLAGS))
+ return new CloudPolicy(OpenFeature.getClient(domain))
+}
diff --git a/packages/cloud/src/server/policy/provider.ts b/packages/cloud/src/server/policy/provider.ts
new file mode 100644
index 000000000..55bb1ae0d
--- /dev/null
+++ b/packages/cloud/src/server/policy/provider.ts
@@ -0,0 +1,67 @@
+import {
+ type EvaluationContext,
+ type Logger,
+ type Provider,
+ type ProviderMetadata,
+ type ResolutionDetails
+} from '@openfeature/server-sdk'
+
+import type { EntitlementSource, EntitlementSubject } from './entitlements'
+
+function subject(context: EvaluationContext): EntitlementSubject {
+ const type = context.subjectType
+ return {
+ type: type === 'user' || type === 'organization' || type === 'deployment' ? type : 'workspace',
+ id: context.targetingKey ?? 'deployment'
+ }
+}
+
+export class EntitlementOpenFeatureProvider implements Provider {
+ readonly metadata: ProviderMetadata = { name: 'openpencil-entitlements' }
+ readonly runsOn = 'server' as const
+
+ constructor(private readonly source: EntitlementSource) {}
+
+ async resolveBooleanEvaluation(
+ flagKey: string,
+ defaultValue: boolean,
+ context: EvaluationContext,
+ _logger: Logger
+ ): Promise<ResolutionDetails<boolean>> {
+ const value = await this.source.boolean(subject(context), flagKey)
+ return value === null
+ ? { value: defaultValue, reason: 'DEFAULT' }
+ : { value, reason: 'TARGETING_MATCH' }
+ }
+
+ async resolveNumberEvaluation(
+ flagKey: string,
+ defaultValue: number,
+ context: EvaluationContext,
+ _logger: Logger
+ ): Promise<ResolutionDetails<number>> {
+ const value = await this.source.number(subject(context), flagKey)
+ return value === null
+ ? { value: defaultValue, reason: 'DEFAULT' }
+ : { value, reason: 'TARGETING_MATCH' }
+ }
+
+ async resolveStringEvaluation(
+ flagKey: string,
+ defaultValue: string,
+ context: EvaluationContext,
+ _logger: Logger
+ ): Promise<ResolutionDetails<string>> {
+ const value = await this.source.string(subject(context), flagKey)
+ return value === null
+ ? { value: defaultValue, reason: 'DEFAULT' }
+ : { value, reason: 'TARGETING_MATCH' }
+ }
+
+ async resolveObjectEvaluation<T>(
+ _flagKey: string,
+ defaultValue: T
+ ): Promise<ResolutionDetails<T>> {
+ return { value: defaultValue, reason: 'DEFAULT' }
+ }
+}
diff --git a/packages/cloud/src/server/policy/service.ts b/packages/cloud/src/server/policy/service.ts
new file mode 100644
index 000000000..e44f807d3
--- /dev/null
+++ b/packages/cloud/src/server/policy/service.ts
@@ -0,0 +1,79 @@
+import type { WorkspaceEntitlements } from '#cloud/contract'
+import type { CloudDatabase } from '#cloud/server/db'
+import { workspaceRole } from '#cloud/server/documents/repository'
+import { DocumentNotFoundError } from '#cloud/server/documents/service'
+import { createStorageQuotaService } from '#cloud/server/quota'
+import type { Kysely } from 'kysely'
+
+import { CLOUD_FEATURE_KEYS } from './keys'
+import type { CloudPolicy } from './policy'
+
+export function createEntitlementService(
+ database: Kysely<CloudDatabase>,
+ policy: CloudPolicy,
+ technicalMaximumFileBytes: number,
+ technicalMaximumParticipants = Number.MAX_SAFE_INTEGER
+) {
+ const quota = createStorageQuotaService(database)
+ return {
+ async workspace(userId: string, workspaceId: string): Promise<WorkspaceEntitlements> {
+ if (!(await workspaceRole(database, userId, workspaceId))) throw new DocumentNotFoundError()
+ const context = {
+ targetingKey: workspaceId,
+ actorId: userId,
+ workspaceId,
+ deploymentMode: 'self-hosted' as const
+ }
+ const [
+ capabilityLinks,
+ anonymousView,
+ anonymousEdit,
+ guestPresence,
+ collaboration,
+ revisionHistory,
+ maximumFileBytes,
+ maximumStorage,
+ maximumParticipants,
+ usage
+ ] = await Promise.all([
+ policy.boolean(CLOUD_FEATURE_KEYS.capabilityLinks, false, context),
+ policy.boolean(CLOUD_FEATURE_KEYS.anonymousView, false, context),
+ policy.boolean(CLOUD_FEATURE_KEYS.anonymousEdit, false, context),
+ policy.boolean(CLOUD_FEATURE_KEYS.guestPresence, false, context),
+ policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, context),
+ policy.boolean(CLOUD_FEATURE_KEYS.revisionHistory, false, context),
+ policy.number(CLOUD_FEATURE_KEYS.maximumFileBytes, technicalMaximumFileBytes, context),
+ policy.number(CLOUD_FEATURE_KEYS.maximumStorageBytes, Number.MAX_SAFE_INTEGER, context),
+ policy.number(
+ CLOUD_FEATURE_KEYS.maximumParticipants,
+ technicalMaximumParticipants,
+ context
+ ),
+ quota.snapshot(workspaceId)
+ ])
+ // Technical limits are ceilings: an entitlement can lower them but never raise them.
+ const participants = Math.min(technicalMaximumParticipants, maximumParticipants)
+ return {
+ features: {
+ capabilityLinks,
+ anonymousView,
+ anonymousEdit,
+ guestPresence,
+ collaboration,
+ revisionHistory
+ },
+ limits: {
+ maximumFileBytes: Math.min(technicalMaximumFileBytes, maximumFileBytes),
+ maximumStorageBytes: maximumStorage === Number.MAX_SAFE_INTEGER ? null : maximumStorage,
+ maximumParticipants: participants === Number.MAX_SAFE_INTEGER ? null : participants
+ },
+ usage: {
+ committedStorageBytes: usage.committedBytes,
+ reservedStorageBytes: usage.reservedBytes
+ }
+ }
+ }
+ }
+}
+
+export type EntitlementService = ReturnType<typeof createEntitlementService>
diff --git a/packages/cloud/src/server/policy/static.ts b/packages/cloud/src/server/policy/static.ts
new file mode 100644
index 000000000..458b5796a
--- /dev/null
+++ b/packages/cloud/src/server/policy/static.ts
@@ -0,0 +1,97 @@
+import { pickBy } from 'es-toolkit/object'
+import { isNotNil } from 'es-toolkit/predicate'
+import * as v from 'valibot'
+
+import { CLOUD_FEATURE_KEYS } from './keys'
+
+const positiveInteger = v.pipe(v.number(), v.integer(), v.minValue(1))
+
+export const staticEntitlementsSchema = v.object({
+ documents: v.optional(
+ v.object({
+ maximumFileBytes: v.optional(positiveInteger),
+ revisionHistory: v.optional(v.boolean())
+ }),
+ {}
+ ),
+ storage: v.optional(v.object({ maximumBytes: v.optional(positiveInteger) }), {}),
+ sharing: v.optional(
+ v.object({
+ capabilityLinks: v.optional(v.boolean()),
+ anonymousView: v.optional(v.boolean()),
+ anonymousEdit: v.optional(v.boolean()),
+ guestPresence: v.optional(v.boolean())
+ }),
+ {}
+ ),
+ collaboration: v.optional(
+ v.object({
+ enabled: v.optional(v.boolean()),
+ maximumParticipants: v.optional(positiveInteger)
+ }),
+ {}
+ )
+})
+
+export type StaticEntitlements = v.InferOutput<typeof staticEntitlementsSchema>
+
+export const staticEntitlementsTOMLSchema = v.object({
+ documents: v.optional(
+ v.object({
+ maximum_file_bytes: v.optional(positiveInteger),
+ revision_history: v.optional(v.boolean())
+ })
+ ),
+ storage: v.optional(v.object({ maximum_bytes: v.optional(positiveInteger) })),
+ sharing: v.optional(
+ v.object({
+ capability_links: v.optional(v.boolean()),
+ anonymous_view: v.optional(v.boolean()),
+ anonymous_edit: v.optional(v.boolean()),
+ guest_presence: v.optional(v.boolean())
+ })
+ ),
+ collaboration: v.optional(
+ v.object({
+ enabled: v.optional(v.boolean()),
+ maximum_participants: v.optional(positiveInteger)
+ })
+ )
+})
+
+export function parseStaticEntitlementsTOML(input: unknown): StaticEntitlements {
+ const value = v.parse(staticEntitlementsTOMLSchema, input)
+ return v.parse(staticEntitlementsSchema, {
+ documents: {
+ maximumFileBytes: value.documents?.maximum_file_bytes,
+ revisionHistory: value.documents?.revision_history
+ },
+ storage: { maximumBytes: value.storage?.maximum_bytes },
+ sharing: {
+ capabilityLinks: value.sharing?.capability_links,
+ anonymousView: value.sharing?.anonymous_view,
+ anonymousEdit: value.sharing?.anonymous_edit,
+ guestPresence: value.sharing?.guest_presence
+ },
+ collaboration: {
+ enabled: value.collaboration?.enabled,
+ maximumParticipants: value.collaboration?.maximum_participants
+ }
+ })
+}
+
+export function staticEntitlementValues(input: unknown): Record<string, boolean | number> {
+ const entitlements = v.parse(staticEntitlementsSchema, input)
+ const values: Record<string, boolean | number | undefined> = {
+ [CLOUD_FEATURE_KEYS.maximumFileBytes]: entitlements.documents.maximumFileBytes,
+ [CLOUD_FEATURE_KEYS.revisionHistory]: entitlements.documents.revisionHistory,
+ [CLOUD_FEATURE_KEYS.maximumStorageBytes]: entitlements.storage.maximumBytes,
+ [CLOUD_FEATURE_KEYS.capabilityLinks]: entitlements.sharing.capabilityLinks,
+ [CLOUD_FEATURE_KEYS.anonymousView]: entitlements.sharing.anonymousView,
+ [CLOUD_FEATURE_KEYS.anonymousEdit]: entitlements.sharing.anonymousEdit,
+ [CLOUD_FEATURE_KEYS.guestPresence]: entitlements.sharing.guestPresence,
+ [CLOUD_FEATURE_KEYS.collaboration]: entitlements.collaboration.enabled,
+ [CLOUD_FEATURE_KEYS.maximumParticipants]: entitlements.collaboration.maximumParticipants
+ }
+ return pickBy(values, isNotNil) as Record<string, boolean | number>
+}
diff --git a/packages/cloud/src/server/quota/index.ts b/packages/cloud/src/server/quota/index.ts
new file mode 100644
index 000000000..2841f103e
--- /dev/null
+++ b/packages/cloud/src/server/quota/index.ts
@@ -0,0 +1,7 @@
+export { createStorageReconciliationService, type StorageReconciliation } from './reconcile'
+export {
+ createStorageQuotaService,
+ StorageQuotaExceededError,
+ type StorageQuotaService,
+ type StorageQuotaSnapshot
+} from './storage'
diff --git a/packages/cloud/src/server/quota/reconcile.ts b/packages/cloud/src/server/quota/reconcile.ts
new file mode 100644
index 000000000..6d995ed46
--- /dev/null
+++ b/packages/cloud/src/server/quota/reconcile.ts
@@ -0,0 +1,53 @@
+import type { CloudDatabase } from '#cloud/server/db'
+import { sumBy } from 'es-toolkit'
+import type { Kysely } from 'kysely'
+
+export type StorageReconciliation = {
+ workspaceId: string
+ recordedBytes: number
+ calculatedBytes: number
+ corrected: boolean
+}
+
+export function createStorageReconciliationService(database: Kysely<CloudDatabase>) {
+ return {
+ async reconcile(options: { dryRun: boolean }): Promise<StorageReconciliation[]> {
+ const workspaces = await database.selectFrom('workspace').select('id').execute()
+ const results: StorageReconciliation[] = []
+ for (const workspace of workspaces) {
+ const [recorded, objects] = await Promise.all([
+ database
+ .selectFrom('workspaceStorageUsage')
+ .select('committedBytes')
+ .where('workspaceId', '=', workspace.id)
+ .executeTakeFirst(),
+ database
+ .selectFrom('storageObject')
+ .innerJoin('documentRevision', 'documentRevision.storageObjectId', 'storageObject.id')
+ .innerJoin('document', 'document.id', 'documentRevision.documentId')
+ .select(['storageObject.id', 'storageObject.byteSize'])
+ .distinct()
+ .where('document.workspaceId', '=', workspace.id)
+ .execute()
+ ])
+ const recordedBytes = Number(recorded?.committedBytes ?? 0)
+ const calculatedBytes = sumBy(objects, (object) => Number(object.byteSize))
+ const corrected = recordedBytes !== calculatedBytes
+ if (corrected && !options.dryRun) {
+ await database
+ .insertInto('workspaceStorageUsage')
+ .values({ workspaceId: workspace.id, committedBytes: calculatedBytes })
+ .onConflict((conflict) =>
+ conflict.column('workspaceId').doUpdateSet({
+ committedBytes: calculatedBytes,
+ updatedAt: new Date()
+ })
+ )
+ .execute()
+ }
+ results.push({ workspaceId: workspace.id, recordedBytes, calculatedBytes, corrected })
+ }
+ return results
+ }
+ }
+}
diff --git a/packages/cloud/src/server/quota/storage.ts b/packages/cloud/src/server/quota/storage.ts
new file mode 100644
index 000000000..8fb858d70
--- /dev/null
+++ b/packages/cloud/src/server/quota/storage.ts
@@ -0,0 +1,157 @@
+import type { CloudDatabase } from '#cloud/server/db'
+import type { Kysely, Transaction } from 'kysely'
+
+export class StorageQuotaExceededError extends Error {
+ override readonly name = 'StorageQuotaExceededError'
+}
+
+export type StorageQuotaSnapshot = {
+ committedBytes: number
+ reservedBytes: number
+}
+
+type StorageDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>
+
+export function createStorageQuotaService(database: Kysely<CloudDatabase>) {
+ async function snapshot(
+ executor: StorageDatabase,
+ workspaceId: string,
+ now = new Date()
+ ): Promise<StorageQuotaSnapshot> {
+ const [usage, reservation] = await Promise.all([
+ executor
+ .selectFrom('workspaceStorageUsage')
+ .select('committedBytes')
+ .where('workspaceId', '=', workspaceId)
+ .executeTakeFirst(),
+ executor
+ .selectFrom('uploadStorageReservation')
+ .select((expression) =>
+ expression.fn.coalesce(expression.fn.sum('bytes'), expression.val(0)).as('reservedBytes')
+ )
+ .where('workspaceId', '=', workspaceId)
+ .where('committedAt', 'is', null)
+ .where('releasedAt', 'is', null)
+ .where('expiresAt', '>', now)
+ .executeTakeFirstOrThrow()
+ ])
+ return {
+ committedBytes: Number(usage?.committedBytes ?? 0),
+ reservedBytes: Number(reservation.reservedBytes)
+ }
+ }
+
+ async function reserve(
+ executor: StorageDatabase,
+ input: {
+ workspaceId: string
+ uploadId: string
+ bytes: number
+ expiresAt: Date
+ maximumBytes: number | null
+ }
+ ): Promise<void> {
+ await executor
+ .insertInto('workspaceStorageUsage')
+ .values({ workspaceId: input.workspaceId, committedBytes: 0 })
+ .onConflict((conflict) => conflict.column('workspaceId').doNothing())
+ .execute()
+ await executor
+ .selectFrom('workspaceStorageUsage')
+ .select('workspaceId')
+ .where('workspaceId', '=', input.workspaceId)
+ .forUpdate()
+ .executeTakeFirstOrThrow()
+ const usage = await snapshot(executor, input.workspaceId)
+ if (
+ input.maximumBytes !== null &&
+ usage.committedBytes + usage.reservedBytes + input.bytes > input.maximumBytes
+ ) {
+ throw new StorageQuotaExceededError('Workspace storage quota exceeded')
+ }
+ await executor
+ .insertInto('uploadStorageReservation')
+ .values({
+ id: crypto.randomUUID(),
+ workspaceId: input.workspaceId,
+ uploadId: input.uploadId,
+ bytes: input.bytes,
+ expiresAt: input.expiresAt,
+ committedAt: null,
+ releasedAt: null
+ })
+ .onConflict((conflict) => conflict.column('uploadId').doNothing())
+ .execute()
+ }
+
+ async function commit(executor: StorageDatabase, uploadId: string): Promise<void> {
+ const reservation = await executor
+ .selectFrom('uploadStorageReservation')
+ .select(['id', 'workspaceId', 'bytes', 'committedAt', 'releasedAt'])
+ .where('uploadId', '=', uploadId)
+ .forUpdate()
+ .executeTakeFirst()
+ if (!reservation || reservation.committedAt || reservation.releasedAt) return
+ await executor
+ .updateTable('workspaceStorageUsage')
+ .set({
+ committedBytes: (expression) =>
+ expression('committedBytes', '+', Number(reservation.bytes)),
+ updatedAt: new Date()
+ })
+ .where('workspaceId', '=', reservation.workspaceId)
+ .execute()
+ await executor
+ .updateTable('uploadStorageReservation')
+ .set({ committedAt: new Date() })
+ .where('id', '=', reservation.id)
+ .execute()
+ }
+
+ return {
+ snapshot: (workspaceId: string) => snapshot(database, workspaceId),
+
+ async reserve(input: {
+ workspaceId: string
+ uploadId: string
+ bytes: number
+ expiresAt: Date
+ maximumBytes: number | null
+ }): Promise<void> {
+ await database.transaction().execute((transaction) => reserve(transaction, input))
+ },
+
+ reserveInTransaction(
+ transaction: Transaction<CloudDatabase>,
+ input: {
+ workspaceId: string
+ uploadId: string
+ bytes: number
+ expiresAt: Date
+ maximumBytes: number | null
+ }
+ ): Promise<void> {
+ return reserve(transaction, input)
+ },
+
+ async commit(uploadId: string): Promise<void> {
+ await database.transaction().execute((transaction) => commit(transaction, uploadId))
+ },
+
+ commitInTransaction(transaction: Transaction<CloudDatabase>, uploadId: string): Promise<void> {
+ return commit(transaction, uploadId)
+ },
+
+ async release(uploadId: string): Promise<void> {
+ await database
+ .updateTable('uploadStorageReservation')
+ .set({ releasedAt: new Date() })
+ .where('uploadId', '=', uploadId)
+ .where('committedAt', 'is', null)
+ .where('releasedAt', 'is', null)
+ .execute()
+ }
+ }
+}
+
+export type StorageQuotaService = ReturnType<typeof createStorageQuotaService>
diff --git a/packages/cloud/src/server/rate-limit/cleanup.ts b/packages/cloud/src/server/rate-limit/cleanup.ts
new file mode 100644
index 000000000..66f33c1c6
--- /dev/null
+++ b/packages/cloud/src/server/rate-limit/cleanup.ts
@@ -0,0 +1,16 @@
+import type { CloudDatabase } from '#cloud/server/db'
+import type { Kysely } from 'kysely'
+
+export function createRateLimitCleanupService(database: Kysely<CloudDatabase>) {
+ return {
+ async cleanupExpired(before: Date): Promise<number> {
+ const result = await database
+ .deleteFrom('cloudRateLimit')
+ .where('windowStartedAt', '<', before)
+ .executeTakeFirst()
+ return Number(result.numDeletedRows)
+ }
+ }
+}
+
+export type RateLimitCleanupService = ReturnType<typeof createRateLimitCleanupService>
diff --git a/packages/cloud/src/server/rate-limit/index.ts b/packages/cloud/src/server/rate-limit/index.ts
new file mode 100644
index 000000000..c016eccf2
--- /dev/null
+++ b/packages/cloud/src/server/rate-limit/index.ts
@@ -0,0 +1,10 @@
+export { createRateLimitCleanupService, type RateLimitCleanupService } from './cleanup'
+export { rateLimitKey, trustedClientIP, type ClientIdentityOptions } from './keys'
+export {
+ CLOUD_RATE_LIMITS,
+ createActorRateLimiter,
+ createCloudRateLimiter,
+ createTrustedIPRateLimiter,
+ type RateLimitPolicy
+} from './middleware'
+export { PostgresRateLimitStore } from './postgres'
diff --git a/packages/cloud/src/server/rate-limit/keys.ts b/packages/cloud/src/server/rate-limit/keys.ts
new file mode 100644
index 000000000..2369cfb9c
--- /dev/null
+++ b/packages/cloud/src/server/rate-limit/keys.ts
@@ -0,0 +1,38 @@
+import type { CloudActor } from '#cloud/server/auth'
+import type { Context } from 'hono'
+
+export type ClientIdentityOptions = {
+ trustedHeaders: string[]
+}
+
+/**
+ * The client address a trusted proxy reported. List-valued headers such as `X-Forwarded-For` carry
+ * whatever the client sent followed by what each proxy appended, so only the right-most entry,
+ * the one the trusted proxy wrote, identifies the client.
+ */
+export function trustedClientIP(context: Context, options: ClientIdentityOptions): string | null {
+ for (const header of options.trustedHeaders) {
+ const value = context.req
+ .header(header)
+ ?.split(',')
+ .map((entry) => entry.trim())
+ .findLast((entry) => entry.length > 0)
+ if (value) return value
+ }
+ return null
+}
+
+export const rateLimitKey = {
+ email(email: string): string {
+ return `email:${email.trim().toLowerCase()}`
+ },
+ ip(ip: string): string {
+ return `ip:${ip}`
+ },
+ actor(actor: CloudActor): string {
+ return `actor:${actor.userId}`
+ },
+ resource(resourceId: string, identity: string): string {
+ return `resource:${resourceId}:${identity}`
+ }
+}
diff --git a/packages/cloud/src/server/rate-limit/middleware.ts b/packages/cloud/src/server/rate-limit/middleware.ts
new file mode 100644
index 000000000..63f9663cf
--- /dev/null
+++ b/packages/cloud/src/server/rate-limit/middleware.ts
@@ -0,0 +1,98 @@
+import type { CloudAPIEnvironment } from '#cloud/server/api/types'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { Context, Env, Input } from 'hono'
+import { rateLimiter, type RateLimitExceededEventHandler } from 'hono-rate-limiter'
+import type { Kysely } from 'kysely'
+
+import { trustedClientIP, type ClientIdentityOptions } from './keys'
+import { PostgresRateLimitStore } from './postgres'
+
+export type RateLimitPolicy = {
+ namespace: string
+ windowMs: number
+ limit: number
+}
+
+export const CLOUD_RATE_LIMITS = {
+ publicCapability: { namespace: 'public-capability', windowMs: 60_000, limit: 30 },
+ collaborationTicket: { namespace: 'collaboration-ticket', windowMs: 60_000, limit: 60 },
+ invitationMutation: { namespace: 'invitation-mutation', windowMs: 60_000, limit: 30 },
+ workspaceCreation: { namespace: 'workspace-creation', windowMs: 60_000, limit: 30 },
+ documentCreation: { namespace: 'document-creation', windowMs: 60_000, limit: 60 },
+ uploadCreation: { namespace: 'upload-creation', windowMs: 60_000, limit: 120 },
+ authenticatedMutation: { namespace: 'authenticated-mutation', windowMs: 60_000, limit: 120 },
+ adminRead: { namespace: 'admin-read', windowMs: 60_000, limit: 300 },
+ adminMutation: { namespace: 'admin-mutation', windowMs: 60_000, limit: 30 }
+} as const satisfies Record<string, RateLimitPolicy>
+
+type RateLimitOptions<E extends Env, P extends string, I extends Input> = {
+ database: Kysely<CloudDatabase>
+ secret: string
+ policy: RateLimitPolicy
+ keyGenerator(context: Context<E, P, I>): string
+ handler?: RateLimitExceededEventHandler<E, P, I>
+ skip?: (context: Context<E, P, I>) => boolean
+ standardHeaders?: boolean | 'draft-6' | 'draft-7'
+}
+
+export function createCloudRateLimiter<
+ E extends Env = Env,
+ P extends string = string,
+ I extends Input = Input
+>(options: RateLimitOptions<E, P, I>) {
+ return rateLimiter<E, P, I>({
+ windowMs: options.policy.windowMs,
+ limit: options.policy.limit,
+ standardHeaders: options.standardHeaders ?? 'draft-7',
+ store: new PostgresRateLimitStore(options.database, options.secret, options.policy.namespace),
+ keyGenerator: (context) => options.keyGenerator(context),
+ handler: options.handler
+ ? (context, next, used) => options.handler?.(context, next, used)
+ : undefined,
+ skip: options.skip
+ })
+}
+
+export function createTrustedIPRateLimiter(
+ database: Kysely<CloudDatabase>,
+ secret: string,
+ policy: RateLimitPolicy,
+ client: ClientIdentityOptions,
+ handler?: RateLimitExceededEventHandler,
+ options?: {
+ resource?: (context: Context) => string
+ skip?: (context: Context) => boolean
+ }
+) {
+ return createCloudRateLimiter({
+ database,
+ secret,
+ policy,
+ keyGenerator: (context) => {
+ const ip = trustedClientIP(context, client) ?? 'unavailable'
+ return options?.resource ? `resource:${options.resource(context)}:ip:${ip}` : `ip:${ip}`
+ },
+ skip: (context) =>
+ trustedClientIP(context, client) === null || Boolean(options?.skip?.(context)),
+ handler
+ })
+}
+
+export function createActorRateLimiter(
+ database: Kysely<CloudDatabase>,
+ secret: string,
+ policy: RateLimitPolicy,
+ skip?: (context: Context<CloudAPIEnvironment, '*'>) => boolean,
+ resource?: (context: Context<CloudAPIEnvironment, '*'>) => string
+) {
+ return createCloudRateLimiter<CloudAPIEnvironment, '*'>({
+ database,
+ secret,
+ policy,
+ keyGenerator: (context) =>
+ resource
+ ? `resource:${resource(context)}:actor:${context.get('actor').userId}`
+ : `actor:${context.get('actor').userId}`,
+ skip
+ })
+}
diff --git a/packages/cloud/src/server/rate-limit/postgres.ts b/packages/cloud/src/server/rate-limit/postgres.ts
new file mode 100644
index 000000000..9ca6060b3
--- /dev/null
+++ b/packages/cloud/src/server/rate-limit/postgres.ts
@@ -0,0 +1,79 @@
+import type { CloudDatabase } from '#cloud/server/db'
+import { sha256 } from '@noble/hashes/sha2.js'
+import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'
+import type { ClientRateLimitInfo, Store } from 'hono-rate-limiter'
+import type { Kysely } from 'kysely'
+
+export class PostgresRateLimitStore implements Store {
+ readonly localKeys = false
+ readonly prefix: string
+ private windowMs = 60_000
+
+ constructor(
+ private readonly database: Kysely<CloudDatabase>,
+ private readonly secret: string,
+ namespace: string,
+ options: { windowMs?: number } = {}
+ ) {
+ this.prefix = `${namespace}:`
+ this.windowMs = options.windowMs ?? this.windowMs
+ }
+
+ init(options: { windowMs: number }): void {
+ this.windowMs = options.windowMs
+ }
+
+ private hash(key: string): string {
+ return bytesToHex(sha256(utf8ToBytes(`${this.secret}:${this.prefix}:${key}`)))
+ }
+
+ async increment(key: string): Promise<ClientRateLimitInfo> {
+ const now = new Date()
+ const resetTime = new Date(
+ Math.floor(now.getTime() / this.windowMs) * this.windowMs + this.windowMs
+ )
+ const row = await this.database
+ .insertInto('cloudRateLimit')
+ .values({
+ keyHash: this.hash(key),
+ windowStartedAt: new Date(resetTime.getTime() - this.windowMs),
+ requestCount: 1,
+ updatedAt: now
+ })
+ .onConflict((conflict) =>
+ conflict.column('keyHash').doUpdateSet((expression) => ({
+ requestCount: expression
+ .case()
+ .whenRef('cloudRateLimit.windowStartedAt', '=', 'excluded.windowStartedAt')
+ .then(expression('cloudRateLimit.requestCount', '+', 1))
+ .else(1)
+ .end(),
+ windowStartedAt: expression.ref('excluded.windowStartedAt'),
+ updatedAt: expression.ref('excluded.updatedAt')
+ }))
+ )
+ .returning(['requestCount', 'windowStartedAt'])
+ .executeTakeFirstOrThrow()
+ return {
+ totalHits: Number(row.requestCount),
+ resetTime: new Date(new Date(row.windowStartedAt).getTime() + this.windowMs)
+ }
+ }
+
+ async decrement(key: string): Promise<void> {
+ await this.database
+ .updateTable('cloudRateLimit')
+ .set((expression) => ({
+ requestCount: expression.fn('greatest', [
+ expression('requestCount', '-', 1),
+ expression.val(0)
+ ])
+ }))
+ .where('keyHash', '=', this.hash(key))
+ .execute()
+ }
+
+ async resetKey(key: string): Promise<void> {
+ await this.database.deleteFrom('cloudRateLimit').where('keyHash', '=', this.hash(key)).execute()
+ }
+}
diff --git a/packages/cloud/src/server/sharing/access.ts b/packages/cloud/src/server/sharing/access.ts
new file mode 100644
index 000000000..eeae715dd
--- /dev/null
+++ b/packages/cloud/src/server/sharing/access.ts
@@ -0,0 +1,29 @@
+import type { CloudDatabase } from '#cloud/server/db'
+import { resolveDocumentAccess } from '#cloud/server/documents/access'
+import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/service'
+import type { Kysely } from 'kysely'
+
+export async function requireSharingAccess(
+ database: Kysely<CloudDatabase>,
+ userId: string,
+ documentId: string
+): Promise<void> {
+ const access = await resolveDocumentAccess(database, userId, documentId)
+ if (!access) throw new DocumentNotFoundError()
+ if (!access.canManageSharing) throw new DocumentForbiddenError()
+}
+
+/**
+ * Ends every collaboration ticket and room key issued for the document so far: removing someone's
+ * access must also remove them from its live room.
+ */
+export async function advanceCollaborationEpoch(
+ database: Kysely<CloudDatabase>,
+ documentId: string
+): Promise<void> {
+ await database
+ .updateTable('document')
+ .set({ collaborationEpoch: (expression) => expression('collaborationEpoch', '+', 1) })
+ .where('id', '=', documentId)
+ .executeTakeFirst()
+}
diff --git a/packages/cloud/src/server/sharing/capabilities/service.ts b/packages/cloud/src/server/sharing/capabilities/service.ts
new file mode 100644
index 000000000..9c7efbf4d
--- /dev/null
+++ b/packages/cloud/src/server/sharing/capabilities/service.ts
@@ -0,0 +1,268 @@
+import type {
+ CreateDocumentShareInput,
+ DocumentPermission,
+ DocumentShare,
+ ResolveDocumentShareInput,
+ UpdateDocumentShareInput
+} from '#cloud/contract'
+import type { CloudActor } from '#cloud/server/auth'
+import type { CloudDatabase } from '#cloud/server/db'
+import { DocumentNotFoundError } from '#cloud/server/documents/service'
+import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'
+import type { CloudPolicy } from '#cloud/server/policy/policy'
+import type { Kysely, UpdateObject } from 'kysely'
+
+import { randomHex } from '@open-pencil/scene-graph/random'
+
+import { advanceCollaborationEpoch, requireSharingAccess } from '../access'
+import { shareContract } from '../contracts'
+import { capabilityHashMatches, hashCapability } from '../crypto'
+import { DocumentShareInvalidError } from '../errors'
+import { createSharingPolicy } from '../policy'
+
+const SHARE_SECRET_BYTES = 24
+
+export type DocumentShareCapability = {
+ share: DocumentShare
+ secret: string
+ path: string
+}
+
+export type ResolvedSharePrincipal =
+ | { kind: 'user'; userId: string; name: string; email: string }
+ | { kind: 'guest'; guestId: string; name: string }
+
+export type ResolvedDocumentShare = {
+ documentId: string
+ permission: DocumentPermission
+ principal: ResolvedSharePrincipal
+ roomEpoch: number
+}
+
+export type CapabilityServiceOptions = {
+ policy?: CloudPolicy
+ deploymentMode?: 'official' | 'self-hosted'
+}
+
+export function createCapabilityService(
+ database: Kysely<CloudDatabase>,
+ options: CapabilityServiceOptions
+) {
+ const sharingPolicy = createSharingPolicy(database, options)
+
+ async function updateActiveShare(
+ userId: string,
+ documentId: string,
+ shareId: string,
+ changes: UpdateObject<CloudDatabase, 'documentShare'>
+ ) {
+ await requireSharingAccess(database, userId, documentId)
+ const row = await database
+ .updateTable('documentShare')
+ .set(changes)
+ .where('id', '=', shareId)
+ .where('documentId', '=', documentId)
+ .where('revokedAt', 'is', null)
+ .returningAll()
+ .executeTakeFirst()
+ if (!row) throw new DocumentNotFoundError()
+ return row
+ }
+
+ return {
+ async listShares(userId: string, documentId: string): Promise<DocumentShare[]> {
+ await requireSharingAccess(database, userId, documentId)
+ const rows = await database
+ .selectFrom('documentShare')
+ .selectAll()
+ .where('documentId', '=', documentId)
+ .where('revokedAt', 'is', null)
+ .orderBy('createdAt', 'desc')
+ .execute()
+ return rows.map(shareContract)
+ },
+
+ async createShare(
+ userId: string,
+ documentId: string,
+ input: CreateDocumentShareInput
+ ): Promise<DocumentShareCapability> {
+ await requireSharingAccess(database, userId, documentId)
+ await sharingPolicy.requireCapabilityLink({
+ actorId: userId,
+ documentId,
+ permission: input.permission
+ })
+ const id = crypto.randomUUID()
+ const secret = randomHex(SHARE_SECRET_BYTES)
+ const row = await database.transaction().execute(async (transaction) => {
+ const document = await transaction
+ .selectFrom('document')
+ .select('collaborationEpoch')
+ .where('id', '=', documentId)
+ .forUpdate()
+ .executeTakeFirstOrThrow()
+ return transaction
+ .insertInto('documentShare')
+ .values({
+ id,
+ documentId,
+ permission: input.permission,
+ secretHash: hashCapability(secret),
+ roomEpoch: document.collaborationEpoch,
+ createdBy: userId,
+ expiresAt: input.expiresAt ? new Date(input.expiresAt) : null,
+ revokedAt: null,
+ lastUsedAt: null
+ })
+ .returningAll()
+ .executeTakeFirstOrThrow()
+ })
+ return { share: shareContract(row), secret, path: `/share/${id}#${secret}` }
+ },
+
+ async updateShare(
+ userId: string,
+ documentId: string,
+ shareId: string,
+ input: UpdateDocumentShareInput
+ ): Promise<DocumentShare> {
+ // Authorization comes first, so a caller without access learns nothing about the share
+ // or the document's link policy.
+ await requireSharingAccess(database, userId, documentId)
+ const current = await database
+ .selectFrom('documentShare')
+ .select('permission')
+ .where('id', '=', shareId)
+ .where('documentId', '=', documentId)
+ .where('revokedAt', 'is', null)
+ .executeTakeFirst()
+ if (!current) throw new DocumentNotFoundError()
+ const permission = input.permission ?? current.permission
+ await sharingPolicy.requireCapabilityLink({ actorId: userId, documentId, permission })
+ const changes: UpdateObject<CloudDatabase, 'documentShare'> = { updatedAt: new Date() }
+ if (input.permission) changes.permission = input.permission
+ if (input.expiresAt !== undefined) {
+ changes.expiresAt = input.expiresAt ? new Date(input.expiresAt) : null
+ }
+ const row = await updateActiveShare(userId, documentId, shareId, changes)
+ return shareContract(row)
+ },
+
+ async rotateShare(
+ userId: string,
+ documentId: string,
+ shareId: string
+ ): Promise<DocumentShareCapability> {
+ const secret = randomHex(SHARE_SECRET_BYTES)
+ const row = await database.transaction().execute(async (transaction) => {
+ await requireSharingAccess(transaction, userId, documentId)
+ const document = await transaction
+ .selectFrom('document')
+ .select('collaborationEpoch')
+ .where('id', '=', documentId)
+ .forUpdate()
+ .executeTakeFirstOrThrow()
+ const updated = await transaction
+ .updateTable('documentShare')
+ .set({
+ secretHash: hashCapability(secret),
+ roomEpoch: document.collaborationEpoch,
+ updatedAt: new Date()
+ })
+ .where('id', '=', shareId)
+ .where('documentId', '=', documentId)
+ .where('revokedAt', 'is', null)
+ .returningAll()
+ .executeTakeFirst()
+ if (!updated) throw new DocumentNotFoundError()
+ return updated
+ })
+ return { share: shareContract(row), secret, path: `/share/${shareId}#${secret}` }
+ },
+
+ async revokeShare(userId: string, documentId: string, shareId: string): Promise<void> {
+ await database.transaction().execute(async (transaction) => {
+ await requireSharingAccess(transaction, userId, documentId)
+ const result = await transaction
+ .updateTable('documentShare')
+ .set({ revokedAt: new Date(), updatedAt: new Date() })
+ .where('id', '=', shareId)
+ .where('documentId', '=', documentId)
+ .where('revokedAt', 'is', null)
+ .executeTakeFirst()
+ if (Number(result.numUpdatedRows) === 0) throw new DocumentNotFoundError()
+ await advanceCollaborationEpoch(transaction, documentId)
+ })
+ },
+
+ async resolveShare(
+ shareId: string,
+ input: ResolveDocumentShareInput,
+ actor?: CloudActor
+ ): Promise<ResolvedDocumentShare> {
+ const row = await database
+ .selectFrom('documentShare')
+ .innerJoin('document', 'document.id', 'documentShare.documentId')
+ .select([
+ 'documentShare.id',
+ 'documentShare.documentId',
+ 'documentShare.permission',
+ 'documentShare.secretHash',
+ 'documentShare.roomEpoch',
+ 'documentShare.expiresAt'
+ ])
+ .where('documentShare.id', '=', shareId)
+ .where('documentShare.revokedAt', 'is', null)
+ .where('document.deletedAt', 'is', null)
+ .executeTakeFirst()
+ if (
+ !row ||
+ !capabilityHashMatches(row.secretHash, input.secret) ||
+ (row.expiresAt && new Date(row.expiresAt).getTime() <= Date.now())
+ ) {
+ throw new DocumentShareInvalidError()
+ }
+ if (!actor && options.policy) {
+ const document = await database
+ .selectFrom('document')
+ .select('workspaceId')
+ .where('id', '=', row.documentId)
+ .executeTakeFirstOrThrow()
+ const featureKey =
+ row.permission === 'edit'
+ ? CLOUD_FEATURE_KEYS.anonymousEdit
+ : CLOUD_FEATURE_KEYS.anonymousView
+ if (
+ !(await options.policy.boolean(featureKey, false, {
+ targetingKey: document.workspaceId,
+ workspaceId: document.workspaceId,
+ documentId: row.documentId,
+ deploymentMode: options.deploymentMode ?? 'self-hosted'
+ }))
+ ) {
+ throw new DocumentShareInvalidError()
+ }
+ }
+ await database
+ .updateTable('documentShare')
+ .set({ lastUsedAt: new Date() })
+ .where('id', '=', shareId)
+ .execute()
+ return {
+ documentId: row.documentId,
+ permission: row.permission,
+ principal: actor
+ ? { kind: 'user', userId: actor.userId, name: actor.name, email: actor.email }
+ : {
+ kind: 'guest',
+ guestId: input.guestId ?? crypto.randomUUID(),
+ name: input.guestName ?? 'Guest'
+ },
+ roomEpoch: row.roomEpoch
+ }
+ }
+ }
+}
+
+export type CapabilityService = ReturnType<typeof createCapabilityService>
diff --git a/packages/cloud/src/server/sharing/continuation.ts b/packages/cloud/src/server/sharing/continuation.ts
new file mode 100644
index 000000000..0e255b923
--- /dev/null
+++ b/packages/cloud/src/server/sharing/continuation.ts
@@ -0,0 +1,85 @@
+import type { InvitationPreview } from '#cloud/contract'
+import type { CloudActor } from '#cloud/server/auth'
+import type { CloudDatabase } from '#cloud/server/db'
+import { DocumentShareInvalidError } from '#cloud/server/sharing/errors'
+import type { Kysely } from 'kysely'
+
+import { capabilityHashMatches, decryptContinuationToken, encryptContinuationToken } from './crypto'
+
+const CONTINUATION_LIFETIME_MS = 10 * 60_000
+
+export type InvitationContinuationService = ReturnType<typeof createInvitationContinuationService>
+
+export function createInvitationContinuationService(
+ database: Kysely<CloudDatabase>,
+ secret: string,
+ validateInvitation: (invitationId: string, token: string) => Promise<InvitationPreview>
+) {
+ return {
+ async create(input: { invitationId: string; token: string }): Promise<{ id: string }> {
+ await validateInvitation(input.invitationId, input.token)
+ const id = crypto.randomUUID()
+ await database
+ .insertInto('invitationContinuation')
+ .values({
+ id,
+ invitationId: input.invitationId,
+ tokenEncrypted: await encryptContinuationToken(secret, input.token),
+ expiresAt: new Date(Date.now() + CONTINUATION_LIFETIME_MS),
+ consumedAt: null
+ })
+ .execute()
+ return { id }
+ },
+
+ async consume(id: string): Promise<{ invitationId: string; token: string }> {
+ return database.transaction().execute(async (transaction) => {
+ const row = await transaction
+ .selectFrom('invitationContinuation')
+ .select(['invitationId', 'tokenEncrypted', 'expiresAt', 'consumedAt'])
+ .where('id', '=', id)
+ .forUpdate()
+ .executeTakeFirst()
+ if (!row || row.consumedAt || new Date(row.expiresAt).getTime() <= Date.now()) {
+ throw new DocumentShareInvalidError()
+ }
+ await transaction
+ .updateTable('invitationContinuation')
+ .set({ consumedAt: new Date() })
+ .where('id', '=', id)
+ .execute()
+ return {
+ invitationId: row.invitationId,
+ token: await decryptContinuationToken(secret, row.tokenEncrypted)
+ }
+ })
+ }
+ }
+}
+
+export function invitationTokenIsActive(
+ invitation: {
+ tokenHash: string
+ expiresAt: Date | string
+ acceptedAt: Date | string | null
+ revokedAt: Date | string | null
+ },
+ token: string
+): boolean {
+ return (
+ capabilityHashMatches(invitation.tokenHash, token) &&
+ !invitation.acceptedAt &&
+ !invitation.revokedAt &&
+ new Date(invitation.expiresAt).getTime() > Date.now()
+ )
+}
+
+export function recipientHint(email: string): string {
+ const [local = '', domain = ''] = email.split('@')
+ const visible = local.slice(0, 2)
+ return `${visible}${'*'.repeat(Math.max(3, local.length - visible.length))}@${domain}`
+}
+
+export function invitationMatchesActor(actor: CloudActor, email: string): boolean {
+ return email === actor.email.trim().toLowerCase()
+}
diff --git a/packages/cloud/src/server/sharing/contracts.ts b/packages/cloud/src/server/sharing/contracts.ts
new file mode 100644
index 000000000..bc3016a4c
--- /dev/null
+++ b/packages/cloud/src/server/sharing/contracts.ts
@@ -0,0 +1,71 @@
+import type {
+ DocumentGrant,
+ DocumentInvitation,
+ DocumentPermission,
+ DocumentShare
+} from '#cloud/contract'
+
+export function dateString(value: Date | string | null): string | null {
+ if (value === null) return null
+ return value instanceof Date ? value.toISOString() : value
+}
+
+export function shareContract(row: {
+ id: string
+ documentId: string
+ permission: DocumentPermission
+ roomEpoch: number
+ createdBy: string
+ createdAt: Date | string
+ updatedAt: Date | string
+ expiresAt: Date | string | null
+ revokedAt: Date | string | null
+ lastUsedAt: Date | string | null
+}): DocumentShare {
+ return {
+ ...row,
+ createdAt: dateString(row.createdAt) ?? '',
+ updatedAt: dateString(row.updatedAt) ?? '',
+ expiresAt: dateString(row.expiresAt),
+ revokedAt: dateString(row.revokedAt),
+ lastUsedAt: dateString(row.lastUsedAt)
+ }
+}
+
+export function grantContract(row: {
+ id: string
+ documentId: string
+ userId: string
+ permission: DocumentPermission
+ createdBy: string
+ createdAt: Date | string
+ updatedAt: Date | string
+}): DocumentGrant {
+ return {
+ ...row,
+ createdAt: dateString(row.createdAt) ?? '',
+ updatedAt: dateString(row.updatedAt) ?? ''
+ }
+}
+
+export function invitationContract(row: {
+ id: string
+ documentId: string
+ emailNormalized: string
+ permission: DocumentPermission
+ invitedBy: string
+ invitedAt: Date | string
+ expiresAt: Date | string
+ acceptedAt: Date | string | null
+}): DocumentInvitation {
+ return {
+ id: row.id,
+ documentId: row.documentId,
+ email: row.emailNormalized,
+ permission: row.permission,
+ invitedBy: row.invitedBy,
+ invitedAt: dateString(row.invitedAt) ?? '',
+ expiresAt: dateString(row.expiresAt) ?? '',
+ acceptedAt: dateString(row.acceptedAt)
+ }
+}
diff --git a/packages/cloud/src/server/sharing/crypto.ts b/packages/cloud/src/server/sharing/crypto.ts
new file mode 100644
index 000000000..b45a982db
--- /dev/null
+++ b/packages/cloud/src/server/sharing/crypto.ts
@@ -0,0 +1,48 @@
+import { hkdf } from '@noble/hashes/hkdf.js'
+import { sha256 } from '@noble/hashes/sha2.js'
+import { bytesToHex, hexToBytes, utf8ToBytes } from '@noble/hashes/utils.js'
+import { compactDecrypt, CompactEncrypt } from 'jose'
+
+const CONTINUATION_SALT = utf8ToBytes('openpencil-cloud-invitation-continuation')
+const CONTINUATION_HEADER = { alg: 'dir', enc: 'A256GCM' } as const
+
+export function hashCapability(value: string): string {
+ return bytesToHex(sha256(utf8ToBytes(value)))
+}
+
+export function capabilityHashMatches(stored: string, value: string): boolean {
+ let expected: Uint8Array
+ try {
+ expected = hexToBytes(stored)
+ } catch {
+ return false
+ }
+ const actual = sha256(utf8ToBytes(value))
+ if (expected.length !== actual.length) return false
+ let difference = 0
+ for (const [index, expectedByte] of expected.entries()) {
+ difference |= expectedByte ^ (actual[index] ?? 0)
+ }
+ return difference === 0
+}
+
+function continuationKey(secret: string): Uint8Array {
+ return hkdf(sha256, utf8ToBytes(secret), CONTINUATION_SALT, new Uint8Array(), 32)
+}
+
+export async function encryptContinuationToken(secret: string, token: string): Promise<string> {
+ return new CompactEncrypt(utf8ToBytes(token))
+ .setProtectedHeader(CONTINUATION_HEADER)
+ .encrypt(continuationKey(secret))
+}
+
+export async function decryptContinuationToken(secret: string, value: string): Promise<string> {
+ const { plaintext, protectedHeader } = await compactDecrypt(value, continuationKey(secret))
+ if (
+ protectedHeader.alg !== CONTINUATION_HEADER.alg ||
+ protectedHeader.enc !== CONTINUATION_HEADER.enc
+ ) {
+ throw new Error('Unsupported invitation continuation encryption')
+ }
+ return new TextDecoder().decode(plaintext)
+}
diff --git a/packages/cloud/src/server/sharing/document-routes.ts b/packages/cloud/src/server/sharing/document-routes.ts
new file mode 100644
index 000000000..440e60330
--- /dev/null
+++ b/packages/cloud/src/server/sharing/document-routes.ts
@@ -0,0 +1,27 @@
+import { parseResolveDocumentShare } from '#cloud/contract'
+import type { DocumentService } from '#cloud/server/documents'
+import type { DocumentSharingService } from '#cloud/server/sharing'
+import { sharingRoute } from '#cloud/server/sharing/http'
+import { validatedJSON } from '#cloud/server/validation'
+import { Hono } from 'hono'
+
+export function createPublicDocumentRoutes(
+ sharing: DocumentSharingService,
+ documents: DocumentService
+) {
+ return new Hono().post(
+ '/shares/:shareId/document',
+ validatedJSON(parseResolveDocumentShare),
+ (context) =>
+ sharingRoute(context, async () => {
+ const resolution = await sharing.resolveShare(
+ context.req.param('shareId'),
+ context.req.valid('json')
+ )
+ return context.json({
+ resolution,
+ document: await documents.downloadShared(resolution.documentId)
+ })
+ })
+ )
+}
diff --git a/packages/cloud/src/server/sharing/errors.ts b/packages/cloud/src/server/sharing/errors.ts
new file mode 100644
index 000000000..ea85b8cc6
--- /dev/null
+++ b/packages/cloud/src/server/sharing/errors.ts
@@ -0,0 +1,7 @@
+export class InvitationDeliveryError extends Error {
+ override readonly name = 'InvitationDeliveryError'
+}
+
+export class DocumentShareInvalidError extends Error {
+ override readonly name = 'DocumentShareInvalidError'
+}
diff --git a/packages/cloud/src/server/sharing/grants/service.ts b/packages/cloud/src/server/sharing/grants/service.ts
new file mode 100644
index 000000000..75e5c2f3d
--- /dev/null
+++ b/packages/cloud/src/server/sharing/grants/service.ts
@@ -0,0 +1,79 @@
+import type { DocumentGrant, PutDocumentGrantInput } from '#cloud/contract'
+import type { CloudDatabase } from '#cloud/server/db'
+import { DocumentNotFoundError } from '#cloud/server/documents/service'
+import type { Kysely } from 'kysely'
+
+import { advanceCollaborationEpoch, requireSharingAccess } from '../access'
+import { grantContract } from '../contracts'
+
+export function createGrantService(database: Kysely<CloudDatabase>) {
+ return {
+ async listGrants(userId: string, documentId: string): Promise<DocumentGrant[]> {
+ await requireSharingAccess(database, userId, documentId)
+ const rows = await database
+ .selectFrom('documentGrant')
+ .select(['id', 'documentId', 'userId', 'permission', 'createdBy', 'createdAt', 'updatedAt'])
+ .where('documentId', '=', documentId)
+ .where('revokedAt', 'is', null)
+ .orderBy('createdAt')
+ .execute()
+ return rows.map(grantContract)
+ },
+
+ async putGrant(
+ userId: string,
+ documentId: string,
+ targetUserId: string,
+ input: PutDocumentGrantInput
+ ): Promise<DocumentGrant> {
+ await requireSharingAccess(database, userId, documentId)
+ const row = await database
+ .insertInto('documentGrant')
+ .values({
+ id: crypto.randomUUID(),
+ documentId,
+ userId: targetUserId,
+ permission: input.permission,
+ createdBy: userId,
+ revokedAt: null
+ })
+ .onConflict((conflict) =>
+ conflict.columns(['documentId', 'userId']).doUpdateSet({
+ permission: input.permission,
+ createdBy: userId,
+ revokedAt: null,
+ updatedAt: new Date()
+ })
+ )
+ .returning([
+ 'id',
+ 'documentId',
+ 'userId',
+ 'permission',
+ 'createdBy',
+ 'createdAt',
+ 'updatedAt'
+ ])
+ .executeTakeFirstOrThrow()
+ return grantContract(row)
+ },
+
+ /** Revoking access advances the collaboration epoch, so tickets and room keys issued before stop working. */
+ async revokeGrant(userId: string, documentId: string, targetUserId: string): Promise<void> {
+ await database.transaction().execute(async (transaction) => {
+ await requireSharingAccess(transaction, userId, documentId)
+ const result = await transaction
+ .updateTable('documentGrant')
+ .set({ revokedAt: new Date(), updatedAt: new Date() })
+ .where('documentId', '=', documentId)
+ .where('userId', '=', targetUserId)
+ .where('revokedAt', 'is', null)
+ .executeTakeFirst()
+ if (Number(result.numUpdatedRows) === 0) throw new DocumentNotFoundError()
+ await advanceCollaborationEpoch(transaction, documentId)
+ })
+ }
+ }
+}
+
+export type GrantService = ReturnType<typeof createGrantService>
diff --git a/packages/cloud/src/server/sharing/http.ts b/packages/cloud/src/server/sharing/http.ts
new file mode 100644
index 000000000..cfe8d6f12
--- /dev/null
+++ b/packages/cloud/src/server/sharing/http.ts
@@ -0,0 +1,34 @@
+import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents'
+import { DocumentShareInvalidError, InvitationDeliveryError } from '#cloud/server/sharing/errors'
+import { WorkspaceInvitationInvalidError } from '#cloud/server/workspaces/members'
+import type { Context } from 'hono'
+
+export function sharingDomainError(context: Context, error: unknown): Response | null {
+ if (
+ error instanceof DocumentNotFoundError ||
+ error instanceof DocumentShareInvalidError ||
+ error instanceof WorkspaceInvitationInvalidError
+ ) {
+ return context.json({ error: { code: 'not_found' as const } }, 404)
+ }
+ if (error instanceof InvitationDeliveryError) {
+ return context.json({ error: { code: 'invitation_delivery_failed' as const } }, 502)
+ }
+ if (error instanceof DocumentForbiddenError) {
+ return context.json({ error: { code: 'forbidden' as const } }, 403)
+ }
+ return null
+}
+
+export async function sharingRoute<T>(
+ context: Context,
+ action: () => Promise<T>
+): Promise<T | Response> {
+ try {
+ return await action()
+ } catch (error) {
+ const response = sharingDomainError(context, error)
+ if (response) return response
+ throw error
+ }
+}
diff --git a/packages/cloud/src/server/sharing/index.ts b/packages/cloud/src/server/sharing/index.ts
new file mode 100644
index 000000000..b8f916da0
--- /dev/null
+++ b/packages/cloud/src/server/sharing/index.ts
@@ -0,0 +1,35 @@
+export {
+ createCapabilityService,
+ type CapabilityService,
+ type CapabilityServiceOptions
+} from './capabilities/service'
+
+export {
+ capabilityHashMatches,
+ decryptContinuationToken,
+ encryptContinuationToken,
+ hashCapability
+} from './crypto'
+export { DocumentShareInvalidError, InvitationDeliveryError } from './errors'
+export { createGrantService, type GrantService } from './grants/service'
+
+export { createPublicDocumentRoutes } from './document-routes'
+export {
+ createInvitationService,
+ type InvitationService,
+ type InvitationServiceOptions
+} from './invitations/service'
+
+export {
+ createDocumentSharingRoutes,
+ createPublicSharingRoutes,
+ type SharingRouteEnvironment
+} from './routes'
+export {
+ createDocumentSharingService,
+ type DocumentShareCapability,
+ type DocumentSharingServiceOptions,
+ type DocumentSharingService,
+ type ResolvedDocumentShare,
+ type ResolvedSharePrincipal
+} from './service'
diff --git a/packages/cloud/src/server/sharing/invitations/service.ts b/packages/cloud/src/server/sharing/invitations/service.ts
new file mode 100644
index 000000000..86ccaac87
--- /dev/null
+++ b/packages/cloud/src/server/sharing/invitations/service.ts
@@ -0,0 +1,318 @@
+import type {
+ AcceptDocumentInvitationInput,
+ AcceptedInvitation,
+ CreateDocumentInvitationInput,
+ CreateInvitationContinuationInput,
+ DocumentInvitation,
+ InvitationPreview,
+ WorkspaceRole
+} from '#cloud/contract'
+import type { CloudActor } from '#cloud/server/auth'
+import type { CloudDatabase } from '#cloud/server/db'
+import { DocumentNotFoundError } from '#cloud/server/documents/service'
+import type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'
+import type { Kysely } from 'kysely'
+
+import { randomHex } from '@open-pencil/scene-graph/random'
+
+import { requireSharingAccess } from '../access'
+import {
+ createInvitationContinuationService,
+ invitationMatchesActor,
+ invitationTokenIsActive,
+ recipientHint
+} from '../continuation'
+import { dateString, grantContract, invitationContract } from '../contracts'
+import { hashCapability } from '../crypto'
+import { DocumentShareInvalidError, InvitationDeliveryError } from '../errors'
+
+const INVITATION_SECRET_BYTES = 24
+const INVITATION_LIFETIME_MS = 7 * 24 * 60 * 60_000
+
+/** Workspace invitations share the invitation link; their ids are not document invitations. */
+export type WorkspaceInvitationResolver = {
+ preview(invitationId: string, token: string): Promise<InvitationPreview | null>
+ accept(
+ actor: CloudActor,
+ invitationId: string,
+ token: string
+ ): Promise<{ workspaceId: string; role: WorkspaceRole } | null>
+}
+
+export type InvitationServiceOptions = {
+ workspaceInvitations?: WorkspaceInvitationResolver
+ continuationSecret?: string
+ delivery?: InvitationDelivery
+ outbox?: InvitationOutbox
+ publicURL?: string
+ appURL?: string
+}
+
+export function createInvitationService(
+ database: Kysely<CloudDatabase>,
+ options: InvitationServiceOptions
+) {
+ async function previewDocumentInvitation(
+ invitationId: string,
+ input: AcceptDocumentInvitationInput
+ ): Promise<InvitationPreview> {
+ const invitation = await database
+ .selectFrom('documentInvitation')
+ .innerJoin('document', 'document.id', 'documentInvitation.documentId')
+ .select([
+ 'documentInvitation.emailNormalized',
+ 'documentInvitation.permission',
+ 'documentInvitation.tokenHash',
+ 'documentInvitation.expiresAt',
+ 'documentInvitation.acceptedAt',
+ 'documentInvitation.revokedAt',
+ 'documentInvitation.invitedBy',
+ 'document.name as documentName'
+ ])
+ .where('documentInvitation.id', '=', invitationId)
+ .executeTakeFirst()
+ if (!invitation || !invitationTokenIsActive(invitation, input.token)) {
+ throw new DocumentShareInvalidError()
+ }
+ const inviter = await database
+ .selectFrom('user')
+ .select('name')
+ .where('id', '=', invitation.invitedBy)
+ .executeTakeFirst()
+ return {
+ kind: 'document',
+ documentName: invitation.documentName,
+ inviterName: inviter?.name ?? 'An OpenPencil user',
+ permission: invitation.permission,
+ expiresAt: dateString(invitation.expiresAt) ?? '',
+ recipientHint: recipientHint(invitation.emailNormalized)
+ }
+ }
+
+ const continuation = options.continuationSecret
+ ? createInvitationContinuationService(
+ database,
+ options.continuationSecret,
+ // Continuations are kept for document invitations only.
+ async (invitationId, token) => previewDocumentInvitation(invitationId, { token })
+ )
+ : null
+
+ return {
+ async listInvitations(userId: string, documentId: string): Promise<DocumentInvitation[]> {
+ await requireSharingAccess(database, userId, documentId)
+ const rows = await database
+ .selectFrom('documentInvitation')
+ .select([
+ 'id',
+ 'documentId',
+ 'emailNormalized',
+ 'permission',
+ 'invitedBy',
+ 'invitedAt',
+ 'expiresAt',
+ 'acceptedAt'
+ ])
+ .where('documentId', '=', documentId)
+ .where('revokedAt', 'is', null)
+ .orderBy('invitedAt')
+ .execute()
+ return rows.map(invitationContract)
+ },
+
+ async createInvitation(
+ userId: string,
+ documentId: string,
+ input: CreateDocumentInvitationInput
+ ): Promise<{ invitation: DocumentInvitation; token: string }> {
+ await requireSharingAccess(database, userId, documentId)
+ const id = crypto.randomUUID()
+ const token = randomHex(INVITATION_SECRET_BYTES)
+ const expiresAt = new Date(Date.now() + INVITATION_LIFETIME_MS)
+ const deliveryContext =
+ (options.delivery || options.outbox) && options.publicURL && options.appURL
+ ? await Promise.all([
+ database
+ .selectFrom('user')
+ .select('name')
+ .where('id', '=', userId)
+ .executeTakeFirst(),
+ database
+ .selectFrom('document')
+ .select('name')
+ .where('id', '=', documentId)
+ .executeTakeFirstOrThrow()
+ ])
+ : null
+ const acceptanceURL =
+ deliveryContext && options.publicURL && options.appURL
+ ? new URL(
+ `/cloud/invitations/${id}?server=${encodeURIComponent(options.publicURL)}#${token}`,
+ options.appURL
+ ).href
+ : null
+ const message =
+ deliveryContext && acceptanceURL
+ ? {
+ deliveryId: id,
+ recipientEmail: input.email,
+ inviterName: deliveryContext[0]?.name ?? 'An OpenPencil user',
+ documentName: deliveryContext[1].name,
+ permission: input.permission,
+ expiresAt: expiresAt.toISOString(),
+ acceptanceURL
+ }
+ : null
+ const row = await database.transaction().execute(async (transaction) => {
+ const inserted = await transaction
+ .insertInto('documentInvitation')
+ .values({
+ id,
+ documentId,
+ emailNormalized: input.email,
+ permission: input.permission,
+ tokenHash: hashCapability(token),
+ invitedBy: userId,
+ expiresAt,
+ acceptedAt: null,
+ revokedAt: null
+ })
+ .returning([
+ 'id',
+ 'documentId',
+ 'emailNormalized',
+ 'permission',
+ 'invitedBy',
+ 'invitedAt',
+ 'expiresAt',
+ 'acceptedAt'
+ ])
+ .executeTakeFirstOrThrow()
+ if (options.outbox && message) {
+ await options.outbox.enqueueDocumentInvitation(message, transaction)
+ }
+ return inserted
+ })
+ const invitation = invitationContract(row)
+ if (options.delivery && message && !options.outbox) {
+ try {
+ await options.delivery.sendDocumentInvitation(message)
+ } catch (error) {
+ await database
+ .updateTable('documentInvitation')
+ .set({ revokedAt: new Date() })
+ .where('id', '=', id)
+ .execute()
+ throw new InvitationDeliveryError('Invitation delivery failed', { cause: error })
+ }
+ }
+ return { invitation, token }
+ },
+
+ async createInvitationContinuation(input: CreateInvitationContinuationInput) {
+ if (!continuation) throw new DocumentShareInvalidError()
+ return continuation.create(input)
+ },
+
+ async consumeInvitationContinuation(id: string) {
+ if (!continuation) throw new DocumentShareInvalidError()
+ return continuation.consume(id)
+ },
+
+ /** What an invitation link offers: a document, or a workspace when the id is one of those. */
+ async previewInvitation(
+ invitationId: string,
+ input: AcceptDocumentInvitationInput
+ ): Promise<InvitationPreview> {
+ const workspace = await options.workspaceInvitations?.preview(invitationId, input.token)
+ return workspace ?? previewDocumentInvitation(invitationId, input)
+ },
+
+ async acceptInvitation(
+ actor: CloudActor,
+ invitationId: string,
+ input: AcceptDocumentInvitationInput
+ ): Promise<AcceptedInvitation> {
+ const workspace = await options.workspaceInvitations?.accept(actor, invitationId, input.token)
+ if (workspace) return { kind: 'workspace', ...workspace }
+ const invitation = await database
+ .selectFrom('documentInvitation')
+ .select([
+ 'id',
+ 'documentId',
+ 'emailNormalized',
+ 'permission',
+ 'invitedBy',
+ 'tokenHash',
+ 'expiresAt',
+ 'acceptedAt',
+ 'revokedAt'
+ ])
+ .where('id', '=', invitationId)
+ .executeTakeFirst()
+ if (
+ !invitation ||
+ !invitationMatchesActor(actor, invitation.emailNormalized) ||
+ !invitationTokenIsActive(invitation, input.token)
+ ) {
+ throw new DocumentShareInvalidError()
+ }
+ return database.transaction().execute(async (transaction) => {
+ const row = await transaction
+ .insertInto('documentGrant')
+ .values({
+ id: crypto.randomUUID(),
+ documentId: invitation.documentId,
+ userId: actor.userId,
+ permission: invitation.permission,
+ // The grant is the inviter's, so "shared by" names them, not the recipient.
+ createdBy: invitation.invitedBy,
+ revokedAt: null
+ })
+ .onConflict((conflict) =>
+ conflict.columns(['documentId', 'userId']).doUpdateSet({
+ permission: invitation.permission,
+ createdBy: invitation.invitedBy,
+ revokedAt: null,
+ updatedAt: new Date()
+ })
+ )
+ .returning([
+ 'id',
+ 'documentId',
+ 'userId',
+ 'permission',
+ 'createdBy',
+ 'createdAt',
+ 'updatedAt'
+ ])
+ .executeTakeFirstOrThrow()
+ await transaction
+ .updateTable('documentInvitation')
+ .set({ acceptedAt: new Date() })
+ .where('id', '=', invitationId)
+ .where('acceptedAt', 'is', null)
+ .execute()
+ return { kind: 'document' as const, grant: grantContract(row) }
+ })
+ },
+
+ async revokeInvitation(
+ userId: string,
+ documentId: string,
+ invitationId: string
+ ): Promise<void> {
+ await requireSharingAccess(database, userId, documentId)
+ const result = await database
+ .updateTable('documentInvitation')
+ .set({ revokedAt: new Date() })
+ .where('id', '=', invitationId)
+ .where('documentId', '=', documentId)
+ .where('revokedAt', 'is', null)
+ .executeTakeFirst()
+ if (Number(result.numUpdatedRows) === 0) throw new DocumentNotFoundError()
+ }
+ }
+}
+
+export type InvitationService = ReturnType<typeof createInvitationService>
diff --git a/packages/cloud/src/server/sharing/policy.ts b/packages/cloud/src/server/sharing/policy.ts
new file mode 100644
index 000000000..4a7656eda
--- /dev/null
+++ b/packages/cloud/src/server/sharing/policy.ts
@@ -0,0 +1,50 @@
+import type { DocumentPermission } from '#cloud/contract'
+import type { CloudDatabase } from '#cloud/server/db'
+import { DocumentForbiddenError } from '#cloud/server/documents/service'
+import { CLOUD_FEATURE_KEYS, type CloudPolicy, type CloudPolicyContext } from '#cloud/server/policy'
+import type { Kysely } from 'kysely'
+
+export type SharingPolicyOptions = {
+ policy?: CloudPolicy
+ deploymentMode?: 'official' | 'self-hosted'
+}
+
+export type CapabilityLinkPolicyInput = {
+ actorId: string
+ documentId: string
+ permission: DocumentPermission
+}
+
+export function createSharingPolicy(
+ database: Kysely<CloudDatabase>,
+ options: SharingPolicyOptions
+) {
+ async function requireCapabilityLink(input: CapabilityLinkPolicyInput): Promise<void> {
+ if (!options.policy) return
+ const document = await database
+ .selectFrom('document')
+ .select('workspaceId')
+ .where('id', '=', input.documentId)
+ .executeTakeFirstOrThrow()
+ const context: CloudPolicyContext = {
+ targetingKey: document.workspaceId,
+ actorId: input.actorId,
+ workspaceId: document.workspaceId,
+ documentId: input.documentId,
+ deploymentMode: options.deploymentMode ?? 'self-hosted'
+ }
+ if (!(await options.policy.boolean(CLOUD_FEATURE_KEYS.capabilityLinks, false, context))) {
+ throw new DocumentForbiddenError()
+ }
+ if (
+ input.permission === 'edit' &&
+ !(await options.policy.boolean(CLOUD_FEATURE_KEYS.anonymousEdit, false, context))
+ ) {
+ throw new DocumentForbiddenError()
+ }
+ }
+
+ return { requireCapabilityLink }
+}
+
+export type SharingPolicy = ReturnType<typeof createSharingPolicy>
diff --git a/packages/cloud/src/server/sharing/routes.ts b/packages/cloud/src/server/sharing/routes.ts
new file mode 100644
index 000000000..d35db861d
--- /dev/null
+++ b/packages/cloud/src/server/sharing/routes.ts
@@ -0,0 +1,245 @@
+import {
+ parseAcceptDocumentInvitation,
+ parseCreateInvitationContinuation,
+ parseCreateDocumentInvitation,
+ parseLookupCloudUser,
+ parseCreateDocumentShare,
+ parsePutDocumentGrant,
+ parseResolveDocumentShare,
+ parseUpdateDocumentShare
+} from '#cloud/contract'
+import type { CloudActor } from '#cloud/server/auth'
+import type { CloudDatabase } from '#cloud/server/db'
+import { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'
+import { sharingRoute } from '#cloud/server/sharing/http'
+import type { DocumentSharingService } from '#cloud/server/sharing/service'
+import { validatedJSON } from '#cloud/server/validation'
+import { Hono } from 'hono'
+import type { Kysely } from 'kysely'
+
+export type SharingRouteEnvironment = {
+ Variables: { actor: CloudActor }
+}
+
+export function createDocumentSharingRoutes(
+ service: DocumentSharingService,
+ rateLimit?: { database: Kysely<CloudDatabase>; secret: string }
+) {
+ const router = new Hono<SharingRouteEnvironment>()
+ if (rateLimit) {
+ router.use(
+ '/documents/:documentId/invitations',
+ createActorRateLimiter(
+ rateLimit.database,
+ rateLimit.secret,
+ CLOUD_RATE_LIMITS.invitationMutation,
+ (context) => context.req.method !== 'POST',
+ (context) => context.req.param('documentId') ?? 'unknown'
+ )
+ )
+ }
+ return router
+ .post('/documents/:documentId/users/lookup', validatedJSON(parseLookupCloudUser), (context) =>
+ sharingRoute(context, async () =>
+ context.json({
+ user: await service.lookupUser(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.valid('json')
+ )
+ })
+ )
+ )
+ .get('/documents/:documentId/users/:userId', (context) =>
+ sharingRoute(context, async () =>
+ context.json({
+ user: await service.userProfile(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.param('userId')
+ )
+ })
+ )
+ )
+ .get('/documents/:documentId/shares', (context) =>
+ sharingRoute(context, async () =>
+ context.json({
+ shares: await service.listShares(
+ context.get('actor').userId,
+ context.req.param('documentId')
+ )
+ })
+ )
+ )
+ .post('/documents/:documentId/shares', validatedJSON(parseCreateDocumentShare), (context) =>
+ sharingRoute(context, async () =>
+ context.json(
+ await service.createShare(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.valid('json')
+ ),
+ 201
+ )
+ )
+ )
+ .patch(
+ '/documents/:documentId/shares/:shareId',
+ validatedJSON(parseUpdateDocumentShare),
+ (context) =>
+ sharingRoute(context, async () =>
+ context.json({
+ share: await service.updateShare(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.param('shareId'),
+ context.req.valid('json')
+ )
+ })
+ )
+ )
+ .post('/documents/:documentId/shares/:shareId/rotate', (context) =>
+ sharingRoute(context, async () =>
+ context.json(
+ await service.rotateShare(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.param('shareId')
+ )
+ )
+ )
+ )
+ .delete('/documents/:documentId/shares/:shareId', (context) =>
+ sharingRoute(context, async () => {
+ await service.revokeShare(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.param('shareId')
+ )
+ return context.body(null, 204)
+ })
+ )
+ .get('/documents/:documentId/grants', (context) =>
+ sharingRoute(context, async () =>
+ context.json({
+ grants: await service.listGrants(
+ context.get('actor').userId,
+ context.req.param('documentId')
+ )
+ })
+ )
+ )
+ .put('/documents/:documentId/grants/:userId', validatedJSON(parsePutDocumentGrant), (context) =>
+ sharingRoute(context, async () =>
+ context.json({
+ grant: await service.putGrant(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.param('userId'),
+ context.req.valid('json')
+ )
+ })
+ )
+ )
+ .delete('/documents/:documentId/grants/:userId', (context) =>
+ sharingRoute(context, async () => {
+ await service.revokeGrant(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.param('userId')
+ )
+ return context.body(null, 204)
+ })
+ )
+ .get('/documents/:documentId/invitations', (context) =>
+ sharingRoute(context, async () =>
+ context.json({
+ invitations: await service.listInvitations(
+ context.get('actor').userId,
+ context.req.param('documentId')
+ )
+ })
+ )
+ )
+ .post(
+ '/documents/:documentId/invitations',
+ validatedJSON(parseCreateDocumentInvitation),
+ (context) =>
+ sharingRoute(context, async () =>
+ context.json(
+ await service.createInvitation(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.valid('json')
+ ),
+ 201
+ )
+ )
+ )
+ .post(
+ '/invitations/:invitationId/accept',
+ validatedJSON(parseAcceptDocumentInvitation),
+ (context) =>
+ sharingRoute(context, async () =>
+ context.json({
+ accepted: await service.acceptInvitation(
+ context.get('actor'),
+ context.req.param('invitationId'),
+ context.req.valid('json')
+ )
+ })
+ )
+ )
+ .delete('/documents/:documentId/invitations/:invitationId', (context) =>
+ sharingRoute(context, async () => {
+ await service.revokeInvitation(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.param('invitationId')
+ )
+ return context.body(null, 204)
+ })
+ )
+}
+
+export function createPublicSharingRoutes(service: DocumentSharingService) {
+ return new Hono()
+ .post(
+ '/invitations/continuations',
+ validatedJSON(parseCreateInvitationContinuation),
+ (context) =>
+ sharingRoute(context, async () =>
+ context.json(await service.createInvitationContinuation(context.req.valid('json')), 201)
+ )
+ )
+ .post('/invitations/continuations/:continuationId/consume', (context) =>
+ sharingRoute(context, async () =>
+ context.json(
+ await service.consumeInvitationContinuation(context.req.param('continuationId'))
+ )
+ )
+ )
+ .post(
+ '/invitations/:invitationId/preview',
+ validatedJSON(parseAcceptDocumentInvitation),
+ (context) =>
+ sharingRoute(context, async () =>
+ context.json({
+ invitation: await service.previewInvitation(
+ context.req.param('invitationId'),
+ context.req.valid('json')
+ )
+ })
+ )
+ )
+ .post('/shares/:shareId/resolve', validatedJSON(parseResolveDocumentShare), (context) =>
+ sharingRoute(context, async () =>
+ context.json({
+ resolution: await service.resolveShare(
+ context.req.param('shareId'),
+ context.req.valid('json')
+ )
+ })
+ )
+ )
+}
diff --git a/packages/cloud/src/server/sharing/service.ts b/packages/cloud/src/server/sharing/service.ts
new file mode 100644
index 000000000..ec561ac31
--- /dev/null
+++ b/packages/cloud/src/server/sharing/service.ts
@@ -0,0 +1,118 @@
+import type { CloudUserProfile, LookupCloudUserInput } from '#cloud/contract'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'
+import type { CloudPolicy } from '#cloud/server/policy/policy'
+import type { Kysely } from 'kysely'
+
+import { requireSharingAccess } from './access'
+import {
+ createCapabilityService,
+ type DocumentShareCapability,
+ type ResolvedDocumentShare,
+ type ResolvedSharePrincipal
+} from './capabilities/service'
+import { createGrantService } from './grants/service'
+import { createInvitationService, type WorkspaceInvitationResolver } from './invitations/service'
+
+export type { DocumentShareCapability, ResolvedDocumentShare, ResolvedSharePrincipal }
+
+export type DocumentSharingServiceOptions = {
+ continuationSecret?: string
+ delivery?: InvitationDelivery
+ outbox?: InvitationOutbox
+ publicURL?: string
+ appURL?: string
+ policy?: CloudPolicy
+ deploymentMode?: 'official' | 'self-hosted'
+ workspaceInvitations?: WorkspaceInvitationResolver
+}
+
+export function createDocumentSharingService(
+ database: Kysely<CloudDatabase>,
+ options: DocumentSharingServiceOptions = {}
+) {
+ const capabilities = createCapabilityService(database, options)
+ const grants = createGrantService(database)
+ const invitations = createInvitationService(database, options)
+
+ return {
+ async lookupUser(
+ userId: string,
+ documentId: string,
+ input: LookupCloudUserInput
+ ): Promise<CloudUserProfile | null> {
+ await requireSharingAccess(database, userId, documentId)
+ const user = await database
+ .selectFrom('user')
+ .select(['id', 'name', 'email', 'image'])
+ .where((expression) =>
+ expression(expression.fn('lower', [expression.ref('email')]), '=', input.email)
+ )
+ .executeTakeFirst()
+ return user ?? null
+ },
+
+ async userProfile(
+ userId: string,
+ documentId: string,
+ profileUserId: string
+ ): Promise<CloudUserProfile | null> {
+ await requireSharingAccess(database, userId, documentId)
+ // Only people connected to this document: its owner, its workspace's members, the holders
+ // and givers of its grants, and the people who invited others to it. User IDs are text in
+ // these tables, so they are compared with the requested ID rather than `user.id`.
+ const related = await database
+ .selectFrom('document')
+ .select('document.id')
+ .where('document.id', '=', documentId)
+ .where((expression) =>
+ expression.or([
+ expression('document.createdBy', '=', profileUserId),
+ expression.exists(
+ expression
+ .selectFrom('workspaceMember')
+ .select('workspaceMember.userId')
+ .whereRef('workspaceMember.workspaceId', '=', 'document.workspaceId')
+ .where('workspaceMember.userId', '=', profileUserId)
+ ),
+ expression.exists(
+ expression
+ .selectFrom('documentGrant')
+ .select('documentGrant.id')
+ .whereRef('documentGrant.documentId', '=', 'document.id')
+ .where((grant) =>
+ grant.or([
+ grant.and([
+ grant('documentGrant.userId', '=', profileUserId),
+ grant('documentGrant.revokedAt', 'is', null)
+ ]),
+ grant('documentGrant.createdBy', '=', profileUserId)
+ ])
+ )
+ ),
+ expression.exists(
+ expression
+ .selectFrom('documentInvitation')
+ .select('documentInvitation.id')
+ .whereRef('documentInvitation.documentId', '=', 'document.id')
+ .where('documentInvitation.invitedBy', '=', profileUserId)
+ )
+ ])
+ )
+ .executeTakeFirst()
+ if (!related) return null
+ const user = await database
+ .selectFrom('user')
+ .select(['id', 'name', 'email', 'image'])
+ .where('id', '=', profileUserId)
+ .executeTakeFirst()
+ return user ?? null
+ },
+
+ ...capabilities,
+ ...grants,
+ ...invitations
+ }
+}
+
+export type DocumentSharingService = ReturnType<typeof createDocumentSharingService>
diff --git a/packages/cloud/src/server/validation.ts b/packages/cloud/src/server/validation.ts
new file mode 100644
index 000000000..8486508d1
--- /dev/null
+++ b/packages/cloud/src/server/validation.ts
@@ -0,0 +1,16 @@
+import type { Context } from 'hono'
+import { validator } from 'hono/validator'
+import { ValiError } from 'valibot'
+
+export function validatedJSON<T>(parse: (input: unknown) => T) {
+ return validator('json', (value, context: Context) => {
+ try {
+ return parse(value)
+ } catch (error) {
+ if (error instanceof ValiError) {
+ return context.json({ error: { code: 'invalid_request' as const } }, 400)
+ }
+ throw error
+ }
+ })
+}
diff --git a/packages/cloud/src/server/worker/interval.ts b/packages/cloud/src/server/worker/interval.ts
new file mode 100644
index 000000000..084478cdc
--- /dev/null
+++ b/packages/cloud/src/server/worker/interval.ts
@@ -0,0 +1,23 @@
+/**
+ * Waits `milliseconds`, or less if `signal` aborts first. One timer and one listener that is
+ * removed again, so a long-lived signal doesn't collect a composite signal per wait.
+ */
+export async function waitForWorkerInterval(
+ milliseconds: number,
+ signal: AbortSignal
+): Promise<void> {
+ if (signal.aborted) return
+ const stopped = new AbortController()
+ await new Promise<void>((resolve) => {
+ stopped.signal.addEventListener('abort', () => resolve(), { once: true })
+ const timer = setTimeout(() => stopped.abort(), milliseconds)
+ signal.addEventListener(
+ 'abort',
+ () => {
+ clearTimeout(timer)
+ stopped.abort()
+ },
+ { once: true, signal: stopped.signal }
+ )
+ })
+}
diff --git a/packages/cloud/src/server/worker/periodic.ts b/packages/cloud/src/server/worker/periodic.ts
new file mode 100644
index 000000000..f51be4eb4
--- /dev/null
+++ b/packages/cloud/src/server/worker/periodic.ts
@@ -0,0 +1,42 @@
+import { waitForWorkerInterval } from './interval'
+
+export type PeriodicWorkerOptions<Result> = {
+ intervalMs: number
+ run(): Promise<Result>
+ signal?: AbortSignal
+ onError?: (error: unknown) => void
+}
+
+export type PeriodicWorker<Result> = {
+ runOnce(): Promise<Result>
+ stop(): Promise<void>
+}
+
+export function startPeriodicWorker<Result>(
+ options: PeriodicWorkerOptions<Result>
+): PeriodicWorker<Result> {
+ const controller = new AbortController()
+ const abort = () => controller.abort()
+ options.signal?.addEventListener('abort', abort, { once: true })
+
+ async function loop(): Promise<void> {
+ while (!controller.signal.aborted) {
+ try {
+ await options.run()
+ } catch (error) {
+ options.onError?.(error)
+ }
+ await waitForWorkerInterval(options.intervalMs, controller.signal)
+ }
+ }
+
+ const running = loop()
+ return {
+ runOnce: () => options.run(),
+ async stop() {
+ controller.abort()
+ options.signal?.removeEventListener('abort', abort)
+ await running
+ }
+ }
+}
diff --git a/packages/cloud/src/server/workspaces/index.ts b/packages/cloud/src/server/workspaces/index.ts
new file mode 100644
index 000000000..ab5b60be8
--- /dev/null
+++ b/packages/cloud/src/server/workspaces/index.ts
@@ -0,0 +1,16 @@
+export {
+ createWorkspaceMemberService,
+ WorkspaceAlreadyMemberError,
+ WorkspaceForbiddenError,
+ WorkspaceInvitationInvalidError,
+ WorkspaceLastAdminError,
+ WorkspaceNotEmptyError,
+ WorkspaceNotFoundError,
+ type WorkspaceMemberService
+} from './members'
+export { createWorkspaceRoutes, type WorkspaceRouteEnvironment } from './routes'
+export {
+ createWorkspaceService,
+ WorkspaceSlugConflictError,
+ type WorkspaceService
+} from './service'
diff --git a/packages/cloud/src/server/workspaces/members.ts b/packages/cloud/src/server/workspaces/members.ts
new file mode 100644
index 000000000..8cbe62879
--- /dev/null
+++ b/packages/cloud/src/server/workspaces/members.ts
@@ -0,0 +1,456 @@
+import type {
+ CreateWorkspaceInvitationInput,
+ CreatedWorkspaceInvitation,
+ InvitationPreview,
+ WorkspaceInvitation,
+ WorkspaceMembers,
+ WorkspaceRole,
+ WorkspaceSummary
+} from '#cloud/contract'
+import type { CloudActor } from '#cloud/server/auth'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { TransactionalEmailService } from '#cloud/server/email/types'
+import {
+ invitationMatchesActor,
+ invitationTokenIsActive,
+ recipientHint
+} from '#cloud/server/sharing/continuation'
+import { dateString } from '#cloud/server/sharing/contracts'
+import { hashCapability } from '#cloud/server/sharing/crypto'
+import { findWorkspace, type WorkspaceDatabase } from '#cloud/server/workspaces/repository'
+import type { Kysely } from 'kysely'
+
+import { randomHex } from '@open-pencil/scene-graph/random'
+
+const INVITATION_SECRET_BYTES = 24
+const INVITATION_LIFETIME_MS = 7 * 24 * 60 * 60_000
+
+/** The workspace does not exist, or the person is not a member of it. */
+export class WorkspaceNotFoundError extends Error {
+ constructor() {
+ super('Workspace not found')
+ this.name = 'WorkspaceNotFoundError'
+ }
+}
+
+/** Only a workspace's administrators may do this. */
+export class WorkspaceForbiddenError extends Error {
+ constructor() {
+ super('Workspace administrators only')
+ this.name = 'WorkspaceForbiddenError'
+ }
+}
+
+/** The change would leave a workspace with members but no administrator. */
+export class WorkspaceLastAdminError extends Error {
+ constructor() {
+ super('A workspace needs an administrator')
+ this.name = 'WorkspaceLastAdminError'
+ }
+}
+
+/**
+ * A workspace still holds documents: live ones, or deleted ones kept until cleanup removes their
+ * files, which deleting the workspace now would leave behind in object storage.
+ */
+export class WorkspaceNotEmptyError extends Error {
+ constructor(readonly reason: 'documents' | 'pending-cleanup') {
+ super('Workspace still holds documents')
+ this.name = 'WorkspaceNotEmptyError'
+ }
+}
+
+/** The person invited already belongs to the workspace. */
+export class WorkspaceAlreadyMemberError extends Error {
+ constructor() {
+ super('Already a member of this workspace')
+ this.name = 'WorkspaceAlreadyMemberError'
+ }
+}
+
+/** The invitation is unknown, used, withdrawn, expired, or meant for someone else. */
+export class WorkspaceInvitationInvalidError extends Error {
+ constructor() {
+ super('Workspace invitation is not valid')
+ this.name = 'WorkspaceInvitationInvalidError'
+ }
+}
+
+export type WorkspaceMemberServiceOptions = {
+ email?: TransactionalEmailService
+ publicURL: string
+ appURL: string
+}
+
+function invitationContract(row: {
+ id: string
+ emailNormalized: string
+ role: WorkspaceRole
+ invitedAt: Date | string
+ expiresAt: Date | string
+}): WorkspaceInvitation {
+ return {
+ id: row.id,
+ email: row.emailNormalized,
+ role: row.role,
+ invitedAt: dateString(row.invitedAt) ?? '',
+ expiresAt: dateString(row.expiresAt) ?? ''
+ }
+}
+
+async function adminCount(database: WorkspaceDatabase, workspaceId: string): Promise<number> {
+ const rows = await database
+ .selectFrom('workspaceMember')
+ .select('userId')
+ .where('workspaceId', '=', workspaceId)
+ .where('role', '=', 'admin')
+ .forUpdate()
+ .execute()
+ return rows.length
+}
+
+/** A member's row, locked until the transaction ends so roles change one at a time. */
+async function lockedMember(
+ database: WorkspaceDatabase,
+ workspaceId: string,
+ memberId: string
+): Promise<{ role: WorkspaceRole }> {
+ const member = await database
+ .selectFrom('workspaceMember')
+ .select('role')
+ .where('workspaceId', '=', workspaceId)
+ .where('userId', '=', memberId)
+ .forUpdate()
+ .executeTakeFirst()
+ if (!member) throw new WorkspaceNotFoundError()
+ return member
+}
+
+/**
+ * Who belongs to a workspace and who is invited to it. Administrators invite, change roles, and
+ * remove people; anyone may leave. A workspace with members always keeps an administrator.
+ */
+export function createWorkspaceMemberService(
+ database: Kysely<CloudDatabase>,
+ options: WorkspaceMemberServiceOptions
+) {
+ async function membership(userId: string, workspaceId: string): Promise<WorkspaceSummary> {
+ const workspace = await findWorkspace(database, userId, workspaceId)
+ if (!workspace) throw new WorkspaceNotFoundError()
+ return workspace
+ }
+
+ async function requireAdmin(userId: string, workspaceId: string): Promise<WorkspaceSummary> {
+ const workspace = await membership(userId, workspaceId)
+ if (workspace.role !== 'admin') throw new WorkspaceForbiddenError()
+ return workspace
+ }
+
+ /** A workspace's members with their accounts; user ids are text in membership rows. */
+ function memberUsers(workspaceId: string) {
+ return database
+ .selectFrom('workspaceMember')
+ .innerJoin('user', (join) =>
+ join.on((expression) =>
+ expression(
+ expression.cast(expression.ref('user.id'), 'text'),
+ '=',
+ expression.ref('workspaceMember.userId')
+ )
+ )
+ )
+ .where('workspaceMember.workspaceId', '=', workspaceId)
+ }
+
+ function acceptanceURL(invitationId: string, token: string): string {
+ return new URL(
+ `/cloud/invitations/${invitationId}?server=${encodeURIComponent(options.publicURL)}#${token}`,
+ options.appURL
+ ).href
+ }
+
+ return {
+ async rename(userId: string, workspaceId: string, name: string): Promise<WorkspaceSummary> {
+ await requireAdmin(userId, workspaceId)
+ await database
+ .updateTable('workspace')
+ .set({ name, updatedAt: new Date() })
+ .where('id', '=', workspaceId)
+ .execute()
+ return membership(userId, workspaceId)
+ },
+
+ async list(userId: string, workspaceId: string): Promise<WorkspaceMembers> {
+ const workspace = await membership(userId, workspaceId)
+ const members = await memberUsers(workspaceId)
+ .select([
+ 'workspaceMember.userId',
+ 'workspaceMember.role',
+ 'workspaceMember.createdAt',
+ 'user.name',
+ 'user.email'
+ ])
+ .orderBy('workspaceMember.createdAt')
+ .execute()
+ const invitations =
+ workspace.role === 'admin'
+ ? await database
+ .selectFrom('workspaceInvitation')
+ .select(['id', 'emailNormalized', 'role', 'invitedAt', 'expiresAt'])
+ .where('workspaceId', '=', workspaceId)
+ .where('acceptedAt', 'is', null)
+ .where('revokedAt', 'is', null)
+ .where('expiresAt', '>', new Date())
+ .orderBy('invitedAt')
+ .execute()
+ : []
+ return {
+ members: members.map((member) => ({
+ userId: member.userId,
+ name: member.name,
+ email: member.email,
+ role: member.role,
+ joinedAt: dateString(member.createdAt) ?? ''
+ })),
+ invitations: invitations.map(invitationContract)
+ }
+ },
+
+ /** Invites someone by email; a newer invitation to the same address replaces the older. */
+ async invite(
+ userId: string,
+ workspaceId: string,
+ input: CreateWorkspaceInvitationInput
+ ): Promise<CreatedWorkspaceInvitation> {
+ const workspace = await requireAdmin(userId, workspaceId)
+ const existing = await memberUsers(workspaceId)
+ .select('workspaceMember.userId')
+ .where((expression) =>
+ expression(expression.fn('lower', [expression.ref('user.email')]), '=', input.email)
+ )
+ .executeTakeFirst()
+ if (existing) throw new WorkspaceAlreadyMemberError()
+ const inviter = await database
+ .selectFrom('user')
+ .select('name')
+ .where('id', '=', userId)
+ .executeTakeFirst()
+ const id = crypto.randomUUID()
+ const token = randomHex(INVITATION_SECRET_BYTES)
+ const expiresAt = new Date(Date.now() + INVITATION_LIFETIME_MS)
+ const url = acceptanceURL(id, token)
+ const row = await database.transaction().execute(async (transaction) => {
+ await transaction
+ .updateTable('workspaceInvitation')
+ .set({ revokedAt: new Date() })
+ .where('workspaceId', '=', workspaceId)
+ .where('emailNormalized', '=', input.email)
+ .where('acceptedAt', 'is', null)
+ .where('revokedAt', 'is', null)
+ .execute()
+ const inserted = await transaction
+ .insertInto('workspaceInvitation')
+ .values({
+ id,
+ workspaceId,
+ emailNormalized: input.email,
+ role: input.role,
+ tokenHash: hashCapability(token),
+ invitedBy: userId,
+ expiresAt,
+ acceptedAt: null,
+ revokedAt: null
+ })
+ .returning(['id', 'emailNormalized', 'role', 'invitedAt', 'expiresAt'])
+ .executeTakeFirstOrThrow()
+ await options.email?.enqueue(
+ {
+ idempotencyKey: `workspace-invitation/${id}`,
+ kind: 'workspace-invitation',
+ recipientEmail: input.email,
+ payload: {
+ inviterName: inviter?.name ?? 'An OpenPencil user',
+ workspaceName: workspace.name,
+ role: input.role,
+ expiresAt: expiresAt.toISOString(),
+ acceptanceURL: url
+ }
+ },
+ transaction
+ )
+ return inserted
+ })
+ return { invitation: invitationContract(row), acceptanceURL: url }
+ },
+
+ async revokeInvitation(
+ userId: string,
+ workspaceId: string,
+ invitationId: string
+ ): Promise<void> {
+ await requireAdmin(userId, workspaceId)
+ const result = await database
+ .updateTable('workspaceInvitation')
+ .set({ revokedAt: new Date() })
+ .where('id', '=', invitationId)
+ .where('workspaceId', '=', workspaceId)
+ .where('acceptedAt', 'is', null)
+ .where('revokedAt', 'is', null)
+ .executeTakeFirst()
+ if (Number(result.numUpdatedRows) === 0) throw new WorkspaceNotFoundError()
+ },
+
+ async updateRole(
+ userId: string,
+ workspaceId: string,
+ memberId: string,
+ role: WorkspaceRole
+ ): Promise<void> {
+ await requireAdmin(userId, workspaceId)
+ await database.transaction().execute(async (transaction) => {
+ const member = await lockedMember(transaction, workspaceId, memberId)
+ if (member.role === 'admin' && role !== 'admin') {
+ if ((await adminCount(transaction, workspaceId)) <= 1) throw new WorkspaceLastAdminError()
+ }
+ await transaction
+ .updateTable('workspaceMember')
+ .set({ role })
+ .where('workspaceId', '=', workspaceId)
+ .where('userId', '=', memberId)
+ .execute()
+ })
+ },
+
+ /** Deletes an empty workspace, with its members and invitations. */
+ async delete(userId: string, workspaceId: string): Promise<void> {
+ await requireAdmin(userId, workspaceId)
+ await database.transaction().execute(async (transaction) => {
+ // Locked first, so a document created meanwhile waits and then finds no workspace.
+ await transaction
+ .selectFrom('workspace')
+ .select('id')
+ .where('id', '=', workspaceId)
+ .forUpdate()
+ .executeTakeFirstOrThrow()
+ const documents = await transaction
+ .selectFrom('document')
+ .select(['deletedAt'])
+ .where('workspaceId', '=', workspaceId)
+ .execute()
+ if (documents.some((document) => document.deletedAt === null)) {
+ throw new WorkspaceNotEmptyError('documents')
+ }
+ if (documents.length > 0) throw new WorkspaceNotEmptyError('pending-cleanup')
+ await transaction.deleteFrom('workspace').where('id', '=', workspaceId).execute()
+ })
+ },
+
+ /** Removes a member, or lets someone leave; the last administrator cannot go. */
+ async remove(userId: string, workspaceId: string, memberId: string): Promise<void> {
+ if (memberId === userId) await membership(userId, workspaceId)
+ else await requireAdmin(userId, workspaceId)
+ await database.transaction().execute(async (transaction) => {
+ const member = await lockedMember(transaction, workspaceId, memberId)
+ if (member.role === 'admin' && (await adminCount(transaction, workspaceId)) <= 1) {
+ throw new WorkspaceLastAdminError()
+ }
+ await transaction
+ .deleteFrom('workspaceMember')
+ .where('workspaceId', '=', workspaceId)
+ .where('userId', '=', memberId)
+ .execute()
+ })
+ },
+
+ /** What a workspace invitation link offers, or null when the id is not one. */
+ async preview(invitationId: string, token: string): Promise<InvitationPreview | null> {
+ const invitation = await database
+ .selectFrom('workspaceInvitation')
+ .innerJoin('workspace', 'workspace.id', 'workspaceInvitation.workspaceId')
+ .select([
+ 'workspaceInvitation.emailNormalized',
+ 'workspaceInvitation.role',
+ 'workspaceInvitation.tokenHash',
+ 'workspaceInvitation.expiresAt',
+ 'workspaceInvitation.acceptedAt',
+ 'workspaceInvitation.revokedAt',
+ 'workspaceInvitation.invitedBy',
+ 'workspace.name as workspaceName'
+ ])
+ .where('workspaceInvitation.id', '=', invitationId)
+ .executeTakeFirst()
+ if (!invitation) return null
+ if (!invitationTokenIsActive(invitation, token)) throw new WorkspaceInvitationInvalidError()
+ const inviter = await database
+ .selectFrom('user')
+ .select('name')
+ .where('id', '=', invitation.invitedBy)
+ .executeTakeFirst()
+ return {
+ kind: 'workspace',
+ workspaceName: invitation.workspaceName,
+ role: invitation.role,
+ inviterName: inviter?.name ?? 'An OpenPencil user',
+ expiresAt: dateString(invitation.expiresAt) ?? '',
+ recipientHint: recipientHint(invitation.emailNormalized)
+ }
+ },
+
+ /**
+ * Joins the workspace an invitation names, or returns null when the id is not a workspace
+ * invitation. Someone already in it keeps the role they have.
+ */
+ async accept(
+ actor: CloudActor,
+ invitationId: string,
+ token: string
+ ): Promise<{ workspaceId: string; role: WorkspaceRole } | null> {
+ const invitation = await database
+ .selectFrom('workspaceInvitation')
+ .select([
+ 'workspaceId',
+ 'emailNormalized',
+ 'role',
+ 'tokenHash',
+ 'expiresAt',
+ 'acceptedAt',
+ 'revokedAt'
+ ])
+ .where('id', '=', invitationId)
+ .executeTakeFirst()
+ if (!invitation) return null
+ if (
+ !invitationMatchesActor(actor, invitation.emailNormalized) ||
+ !invitationTokenIsActive(invitation, token)
+ ) {
+ throw new WorkspaceInvitationInvalidError()
+ }
+ return database.transaction().execute(async (transaction) => {
+ await transaction
+ .insertInto('workspaceMember')
+ .values({
+ workspaceId: invitation.workspaceId,
+ userId: actor.userId,
+ role: invitation.role
+ })
+ .onConflict((conflict) => conflict.columns(['workspaceId', 'userId']).doNothing())
+ .execute()
+ await transaction
+ .updateTable('workspaceInvitation')
+ .set({ acceptedAt: new Date() })
+ .where('id', '=', invitationId)
+ .where('acceptedAt', 'is', null)
+ .execute()
+ const member = await transaction
+ .selectFrom('workspaceMember')
+ .select('role')
+ .where('workspaceId', '=', invitation.workspaceId)
+ .where('userId', '=', actor.userId)
+ .executeTakeFirstOrThrow()
+ return { workspaceId: invitation.workspaceId, role: member.role }
+ })
+ }
+ }
+}
+
+export type WorkspaceMemberService = ReturnType<typeof createWorkspaceMemberService>
diff --git a/packages/cloud/src/server/workspaces/repository.ts b/packages/cloud/src/server/workspaces/repository.ts
new file mode 100644
index 000000000..ff46f69dc
--- /dev/null
+++ b/packages/cloud/src/server/workspaces/repository.ts
@@ -0,0 +1,91 @@
+import type { CreateWorkspaceInput, WorkspaceRole, WorkspaceSummary } from '#cloud/contract'
+import type { CloudDatabase } from '#cloud/server/db'
+import type { Kysely, Transaction } from 'kysely'
+
+export type WorkspaceDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>
+
+function toISOString(value: Date | string): string {
+ return value instanceof Date ? value.toISOString() : value
+}
+
+export async function listWorkspaces(
+ database: WorkspaceDatabase,
+ userId: string
+): Promise<WorkspaceSummary[]> {
+ const rows = await database
+ .selectFrom('workspace')
+ .innerJoin('workspaceMember', 'workspaceMember.workspaceId', 'workspace.id')
+ .select([
+ 'workspace.id',
+ 'workspace.name',
+ 'workspace.slug',
+ 'workspace.createdAt',
+ 'workspace.updatedAt',
+ 'workspaceMember.role'
+ ])
+ .where('workspaceMember.userId', '=', userId)
+ .orderBy('workspace.updatedAt', 'desc')
+ .execute()
+
+ return rows.map((row) => ({
+ ...row,
+ createdAt: toISOString(row.createdAt),
+ updatedAt: toISOString(row.updatedAt)
+ }))
+}
+
+export async function findWorkspace(
+ database: WorkspaceDatabase,
+ userId: string,
+ workspaceId: string
+): Promise<WorkspaceSummary | undefined> {
+ const row = await database
+ .selectFrom('workspace')
+ .innerJoin('workspaceMember', 'workspaceMember.workspaceId', 'workspace.id')
+ .select([
+ 'workspace.id',
+ 'workspace.name',
+ 'workspace.slug',
+ 'workspace.createdAt',
+ 'workspace.updatedAt',
+ 'workspaceMember.role'
+ ])
+ .where('workspace.id', '=', workspaceId)
+ .where('workspaceMember.userId', '=', userId)
+ .executeTakeFirst()
+ return row
+ ? {
+ ...row,
+ createdAt: toISOString(row.createdAt),
+ updatedAt: toISOString(row.updatedAt)
+ }
+ : undefined
+}
+
+export async function insertWorkspace(
+ database: WorkspaceDatabase,
+ actorId: string,
+ input: CreateWorkspaceInput & { id: string; slug: string }
+): Promise<boolean> {
+ const inserted = await database
+ .insertInto('workspace')
+ .values({
+ id: input.id,
+ name: input.name,
+ slug: input.slug,
+ createdBy: actorId
+ })
+ .onConflict((conflict) => conflict.column('slug').doNothing())
+ .returning('id')
+ .executeTakeFirst()
+ return inserted !== undefined
+}
+
+export async function insertWorkspaceMember(
+ database: WorkspaceDatabase,
+ workspaceId: string,
+ userId: string,
+ role: WorkspaceRole
+): Promise<void> {
+ await database.insertInto('workspaceMember').values({ workspaceId, userId, role }).execute()
+}
diff --git a/packages/cloud/src/server/workspaces/routes.ts b/packages/cloud/src/server/workspaces/routes.ts
new file mode 100644
index 000000000..bbec95f34
--- /dev/null
+++ b/packages/cloud/src/server/workspaces/routes.ts
@@ -0,0 +1,176 @@
+import {
+ parseCreateWorkspace,
+ parseCreateWorkspaceInvitation,
+ parseUpdateWorkspace,
+ parseUpdateWorkspaceMember
+} from '#cloud/contract'
+import type { CloudActor } from '#cloud/server/auth'
+import type { CloudDatabase } from '#cloud/server/db'
+import { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'
+import { validatedJSON } from '#cloud/server/validation'
+import {
+ WorkspaceAlreadyMemberError,
+ WorkspaceForbiddenError,
+ WorkspaceLastAdminError,
+ WorkspaceNotEmptyError,
+ WorkspaceNotFoundError,
+ type WorkspaceMemberService
+} from '#cloud/server/workspaces/members'
+import type { WorkspaceService } from '#cloud/server/workspaces/service'
+import { WorkspaceSlugConflictError } from '#cloud/server/workspaces/service'
+import { Hono, type Context } from 'hono'
+import type { Kysely } from 'kysely'
+
+export type WorkspaceRouteEnvironment = {
+ Variables: {
+ actor: CloudActor
+ }
+}
+
+/** Runs a membership action, answering its domain errors with their HTTP codes. */
+async function memberRoute<T>(context: Context, action: () => Promise<T>): Promise<T | Response> {
+ try {
+ return await action()
+ } catch (error) {
+ if (error instanceof WorkspaceNotFoundError) {
+ return context.json({ error: { code: 'not_found' as const } }, 404)
+ }
+ if (error instanceof WorkspaceForbiddenError) {
+ return context.json({ error: { code: 'forbidden' as const } }, 403)
+ }
+ if (error instanceof WorkspaceLastAdminError) {
+ return context.json({ error: { code: 'last_admin' as const } }, 409)
+ }
+ if (error instanceof WorkspaceNotEmptyError) {
+ const code = error.reason === 'documents' ? 'not_empty' : 'cleanup_pending'
+ return context.json({ error: { code } }, 409)
+ }
+ if (error instanceof WorkspaceAlreadyMemberError) {
+ return context.json({ error: { code: 'already_member' as const } }, 409)
+ }
+ throw error
+ }
+}
+
+export function createWorkspaceRoutes(
+ service: WorkspaceService,
+ members: WorkspaceMemberService,
+ rateLimit?: { database: Kysely<CloudDatabase>; secret: string }
+) {
+ const router = new Hono<WorkspaceRouteEnvironment>()
+ if (rateLimit) {
+ router.use(
+ '/',
+ createActorRateLimiter(
+ rateLimit.database,
+ rateLimit.secret,
+ CLOUD_RATE_LIMITS.workspaceCreation,
+ (context) => context.req.method !== 'POST'
+ )
+ )
+ router.use(
+ '/:workspaceId/invitations',
+ createActorRateLimiter(
+ rateLimit.database,
+ rateLimit.secret,
+ CLOUD_RATE_LIMITS.invitationMutation,
+ (context) => context.req.method !== 'POST',
+ (context) => context.req.param('workspaceId') ?? 'unknown'
+ )
+ )
+ }
+ return router
+ .get('/', async (context) => {
+ const workspaces = await service.list(context.get('actor').userId)
+ return context.json({ workspaces })
+ })
+ .post('/', validatedJSON(parseCreateWorkspace), async (context) => {
+ try {
+ const workspace = await service.create(
+ context.get('actor').userId,
+ context.req.valid('json')
+ )
+ return context.json({ workspace }, 201)
+ } catch (error) {
+ if (error instanceof WorkspaceSlugConflictError) {
+ return context.json({ error: { code: 'slug_conflict' as const } }, 409)
+ }
+ throw error
+ }
+ })
+ .get('/:workspaceId', async (context) => {
+ const workspace = await service.get(
+ context.get('actor').userId,
+ context.req.param('workspaceId')
+ )
+ if (!workspace) return context.json({ error: { code: 'not_found' as const } }, 404)
+ return context.json({ workspace })
+ })
+ .patch('/:workspaceId', validatedJSON(parseUpdateWorkspace), (context) =>
+ memberRoute(context, async () =>
+ context.json({
+ workspace: await members.rename(
+ context.get('actor').userId,
+ context.req.param('workspaceId'),
+ context.req.valid('json').name
+ )
+ })
+ )
+ )
+ .delete('/:workspaceId', (context) =>
+ memberRoute(context, async () => {
+ await members.delete(context.get('actor').userId, context.req.param('workspaceId'))
+ return context.body(null, 204)
+ })
+ )
+ .get('/:workspaceId/members', (context) =>
+ memberRoute(context, async () =>
+ context.json(
+ await members.list(context.get('actor').userId, context.req.param('workspaceId'))
+ )
+ )
+ )
+ .post('/:workspaceId/invitations', validatedJSON(parseCreateWorkspaceInvitation), (context) =>
+ memberRoute(context, async () =>
+ context.json(
+ await members.invite(
+ context.get('actor').userId,
+ context.req.param('workspaceId'),
+ context.req.valid('json')
+ ),
+ 201
+ )
+ )
+ )
+ .delete('/:workspaceId/invitations/:invitationId', (context) =>
+ memberRoute(context, async () => {
+ await members.revokeInvitation(
+ context.get('actor').userId,
+ context.req.param('workspaceId'),
+ context.req.param('invitationId')
+ )
+ return context.body(null, 204)
+ })
+ )
+ .patch('/:workspaceId/members/:userId', validatedJSON(parseUpdateWorkspaceMember), (context) =>
+ memberRoute(context, async () => {
+ await members.updateRole(
+ context.get('actor').userId,
+ context.req.param('workspaceId'),
+ context.req.param('userId'),
+ context.req.valid('json').role
+ )
+ return context.body(null, 204)
+ })
+ )
+ .delete('/:workspaceId/members/:userId', (context) =>
+ memberRoute(context, async () => {
+ await members.remove(
+ context.get('actor').userId,
+ context.req.param('workspaceId'),
+ context.req.param('userId')
+ )
+ return context.body(null, 204)
+ })
+ )
+}
diff --git a/packages/cloud/src/server/workspaces/service.ts b/packages/cloud/src/server/workspaces/service.ts
new file mode 100644
index 000000000..f05bdd11c
--- /dev/null
+++ b/packages/cloud/src/server/workspaces/service.ts
@@ -0,0 +1,84 @@
+import type { CreateWorkspaceInput, WorkspaceSummary } from '#cloud/contract'
+import type { CloudDatabase } from '#cloud/server/db'
+import {
+ findWorkspace,
+ insertWorkspace,
+ insertWorkspaceMember,
+ listWorkspaces
+} from '#cloud/server/workspaces/repository'
+import type { Kysely } from 'kysely'
+
+export class WorkspaceSlugConflictError extends Error {
+ constructor(readonly slug: string) {
+ super(`Workspace slug is already in use: ${slug}`)
+ this.name = 'WorkspaceSlugConflictError'
+ }
+}
+
+function fallbackSlug(name: string): string {
+ const normalized = name
+ .toLowerCase()
+ .normalize('NFKD')
+ .replace(/[\u0300-\u036f]/g, '')
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-|-$/g, '')
+ .slice(0, 48)
+ return normalized.length >= 3 ? normalized : 'workspace'
+}
+
+function generatedSlug(name: string): string {
+ return `${fallbackSlug(name)}-${crypto.randomUUID().slice(0, 8)}`
+}
+
+function personalWorkspaceName(name: string): string {
+ const first = name.trim().split(/\s+/)[0]
+ return first ? `${first}’s workspace` : 'Personal workspace'
+}
+
+export function createWorkspaceService(database: Kysely<CloudDatabase>) {
+ return {
+ list(userId: string): Promise<WorkspaceSummary[]> {
+ return listWorkspaces(database, userId)
+ },
+
+ get(userId: string, workspaceId: string): Promise<WorkspaceSummary | undefined> {
+ return findWorkspace(database, userId, workspaceId)
+ },
+
+ async create(userId: string, input: CreateWorkspaceInput): Promise<WorkspaceSummary> {
+ const workspaceId = crypto.randomUUID()
+ const slug = input.slug ?? generatedSlug(input.name)
+ await database.transaction().execute(async (transaction) => {
+ const inserted = await insertWorkspace(transaction, userId, {
+ ...input,
+ id: workspaceId,
+ slug
+ })
+ if (!inserted) throw new WorkspaceSlugConflictError(slug)
+ await insertWorkspaceMember(transaction, workspaceId, userId, 'admin')
+ })
+ const workspace = await findWorkspace(database, userId, workspaceId)
+ if (!workspace) throw new Error('Created workspace could not be read')
+ return workspace
+ },
+
+ /**
+ * Gives an active account with no workspace one of its own, so it has somewhere to save. The
+ * slug is fixed per person, so concurrent calls make one workspace and later calls none.
+ */
+ async ensurePersonal(user: { userId: string; name: string }): Promise<void> {
+ if ((await listWorkspaces(database, user.userId)).length > 0) return
+ const workspaceId = crypto.randomUUID()
+ await database.transaction().execute(async (transaction) => {
+ const inserted = await insertWorkspace(transaction, user.userId, {
+ id: workspaceId,
+ name: personalWorkspaceName(user.name),
+ slug: `personal-${user.userId}`
+ })
+ if (inserted) await insertWorkspaceMember(transaction, workspaceId, user.userId, 'admin')
+ })
+ }
+ }
+}
+
+export type WorkspaceService = ReturnType<typeof createWorkspaceService>
diff --git a/packages/cloud/tests/client/api.test.ts b/packages/cloud/tests/client/api.test.ts
new file mode 100644
index 000000000..ba117942e
--- /dev/null
+++ b/packages/cloud/tests/client/api.test.ts
@@ -0,0 +1,203 @@
+import { describe, expect, test } from 'bun:test'
+
+import { CloudAPIError, createCloudAPIClient } from '#cloud/client'
+
+const workspaceId = '11111111-1111-4111-8111-111111111111'
+const documentId = '22222222-2222-4222-8222-222222222222'
+const revisionId = '33333333-3333-4333-8333-333333333333'
+const collaborationTicket = {
+ token: 'signed-token',
+ documentId,
+ roomId: `cloud:${documentId}:2`,
+ roomKey: 'r'.repeat(43),
+ principal: { kind: 'guest' as const, guestId: 'stable-guest-id-123', name: 'Guest' },
+ permission: 'view' as const,
+ roomEpoch: 2,
+ expiresAt: '2026-01-01T00:05:00.000Z',
+ serverEnforcedWrites: false as const
+}
+
+const document = {
+ id: documentId,
+ workspaceId,
+ name: 'Homepage',
+ currentRevisionId: revisionId,
+ version: 1,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+}
+
+describe('createCloudAPIClient', () => {
+ test('validates document metadata and sends authenticated requests', async () => {
+ const requests: Request[] = []
+ const client = createCloudAPIClient('https://cloud.example.com/api', {
+ fetch: async (input, init) => {
+ requests.push(new Request(input, init))
+ return Response.json({ documents: [document] })
+ }
+ })
+
+ expect(await client.listDocuments(workspaceId)).toEqual([document])
+ expect(requests[0]?.url).toBe(
+ `https://cloud.example.com/api/workspaces/${workspaceId}/documents`
+ )
+ expect(requests[0]?.credentials).toBe('include')
+ })
+
+ test('lists documents shared with the person and rejects malformed entries', async () => {
+ const shared = {
+ ...document,
+ workspaceName: 'Client work',
+ permission: 'view' as const,
+ sharedBy: { name: 'Alice' },
+ sharedAt: '2026-01-02T00:00:00.000Z'
+ }
+ let body: unknown = { documents: [shared] }
+ const requests: string[] = []
+ const client = createCloudAPIClient('https://cloud.example.com/api', {
+ fetch: async (input, init) => {
+ requests.push(new Request(input, init).url)
+ return Response.json(body)
+ }
+ })
+
+ expect(await client.listSharedDocuments()).toEqual([shared])
+ expect(requests).toEqual(['https://cloud.example.com/api/shared-documents'])
+ body = { documents: [{ ...shared, permission: 'owner' }] }
+ await expect(client.listSharedDocuments()).rejects.toThrow()
+ })
+
+ test('creates upload sessions and commits revisions', async () => {
+ const requests: Request[] = []
+ const client = createCloudAPIClient('https://cloud.example.com/api/', {
+ fetch: async (input, init) => {
+ const request = new Request(input, init)
+ requests.push(request)
+ if (request.url.endsWith('/uploads')) {
+ return Response.json({
+ id: '44444444-4444-4444-8444-444444444444',
+ upload: {
+ kind: 'single',
+ url: 'https://objects.example.com/upload',
+ method: 'PUT',
+ headers: { 'x-amz-checksum-sha256': 'checksum' },
+ expiresAt: '2026-01-01T00:15:00.000Z'
+ }
+ })
+ }
+ return Response.json({ document })
+ }
+ })
+
+ const upload = await client.createUpload(documentId, {
+ baseRevisionId: revisionId,
+ byteSize: 5,
+ checksum: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',
+ contentType: 'application/octet-stream'
+ })
+ expect(upload.upload.kind).toBe('single')
+ if (upload.upload.kind !== 'single') throw new Error('Expected a single upload')
+ expect(upload.upload.method).toBe('PUT')
+ expect(
+ await client.commitUpload(upload.id, {
+ checksum: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='
+ })
+ ).toEqual(document)
+ expect(requests.every((request) => request.method === 'POST')).toBe(true)
+ })
+
+ test('looks up authorized user profiles and accepts invitations', async () => {
+ const invitationId = '44444444-4444-4444-8444-444444444444'
+ const grant = {
+ id: '55555555-5555-4555-8555-555555555555',
+ documentId,
+ userId: 'recipient-user',
+ permission: 'view' as const,
+ createdBy: 'owner-user',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ }
+ const requests: Request[] = []
+ const client = createCloudAPIClient('https://cloud.example.com/api', {
+ fetch: async (input, init) => {
+ const request = new Request(input, init)
+ requests.push(request)
+ if (request.url.endsWith('/users/lookup')) {
+ return Response.json({
+ user: {
+ id: 'recipient-user',
+ name: 'Recipient',
+ email: '[email protected]',
+ image: null
+ }
+ })
+ }
+ if (request.url.endsWith('/preview')) {
+ return Response.json({
+ invitation: {
+ kind: 'document',
+ documentName: 'Homepage',
+ inviterName: 'Alice',
+ permission: 'view',
+ expiresAt: '2026-01-08T00:00:00.000Z',
+ recipientHint: 're*******@example.com'
+ }
+ })
+ }
+ return Response.json({ accepted: { kind: 'document', grant } })
+ }
+ })
+
+ expect(await client.lookupUser(documentId, { email: '[email protected]' })).toEqual({
+ id: 'recipient-user',
+ name: 'Recipient',
+ email: '[email protected]',
+ image: null
+ })
+ expect(await client.previewInvitation(invitationId, { token: 't'.repeat(32) })).toMatchObject({
+ documentName: 'Homepage',
+ recipientHint: 're*******@example.com'
+ })
+ expect(await client.acceptInvitation(invitationId, { token: 't'.repeat(32) })).toEqual({
+ kind: 'document',
+ grant
+ })
+ expect(requests.map((request) => request.url)).toEqual([
+ `https://cloud.example.com/api/documents/${documentId}/users/lookup`,
+ `https://cloud.example.com/api/invitations/${invitationId}/preview`,
+ `https://cloud.example.com/api/invitations/${invitationId}/accept`
+ ])
+ })
+
+ test('requests and validates public collaboration tickets without dropping the API prefix', async () => {
+ const requests: Request[] = []
+ const client = createCloudAPIClient('https://cloud.example.com/api', {
+ fetch: async (input, init) => {
+ requests.push(new Request(input, init))
+ return Response.json({ ticket: collaborationTicket })
+ }
+ })
+
+ expect(
+ await client.getSharedCollaborationTicket('share-id', {
+ secret: 'x'.repeat(32),
+ guestName: 'Guest',
+ guestId: 'stable-guest-id-123'
+ })
+ ).toEqual(collaborationTicket)
+ expect(requests[0]?.url).toBe(
+ 'https://cloud.example.com/api/shares/share-id/collaboration-ticket'
+ )
+ expect(requests[0]?.credentials).toBe('include')
+ })
+
+ test('preserves stable API error codes', async () => {
+ const client = createCloudAPIClient('https://cloud.example.com/api', {
+ fetch: async () => Response.json({ error: { code: 'revision_conflict' } }, { status: 409 })
+ })
+
+ const error = await client.listDocuments(workspaceId).catch((caught: unknown) => caught)
+ expect(error).toBeInstanceOf(CloudAPIError)
+ expect(error).toMatchObject({ status: 409, code: 'revision_conflict' })
+ })
+})
diff --git a/packages/cloud/tests/client/auth-failure.test.ts b/packages/cloud/tests/client/auth-failure.test.ts
new file mode 100644
index 000000000..2dfcd2d14
--- /dev/null
+++ b/packages/cloud/tests/client/auth-failure.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, test } from 'bun:test'
+
+import { cloudAuthFailure } from '#cloud/client'
+
+describe('sign-in failures', () => {
+ test('tell passkey refusals from server failures', () => {
+ expect(cloudAuthFailure({ code: 'ERROR_CEREMONY_ABORTED', status: 400 }).failure).toBe(
+ 'passkey-cancelled'
+ )
+ expect(
+ cloudAuthFailure({ code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED', status: 400 }).failure
+ ).toBe('passkey-exists')
+ // A browser that won't make passkeys for the address, such as Safari on some local hosts.
+ expect(cloudAuthFailure({ code: 'ERROR_INVALID_DOMAIN', status: 400 }).failure).toBe(
+ 'passkey-unavailable'
+ )
+ expect(cloudAuthFailure({ code: 'SOMETHING_ELSE', status: 500 }).failure).toBe('unavailable')
+ expect(cloudAuthFailure({ code: 'SESSION_NOT_FRESH', status: 403 }).failure).toBe(
+ 'session-not-fresh'
+ )
+ expect(cloudAuthFailure({ status: 429 }).failure).toBe('rate-limited')
+ })
+})
diff --git a/packages/cloud/tests/client/auth-navigation.test.ts b/packages/cloud/tests/client/auth-navigation.test.ts
new file mode 100644
index 000000000..fa9705119
--- /dev/null
+++ b/packages/cloud/tests/client/auth-navigation.test.ts
@@ -0,0 +1,43 @@
+import { expect, test } from 'bun:test'
+
+import { cloudEditorReturnURL, cloudSignInURL } from '#cloud/client'
+import type { CloudDiscovery } from '#cloud/contract'
+
+const discovery: CloudDiscovery = {
+ protocolVersion: '1',
+ deployment: 'self-hosted',
+ apiURL: 'https://cloud.example/api',
+ authURL: 'https://cloud.example/api/auth',
+ appURL: 'https://editor.example',
+ authentication: { socialProviders: [], enterpriseSSO: false, enrollmentMode: 'open' },
+ capabilities: { documents: true, workspaces: true, collaboration: true }
+}
+
+test('email-only instance owns sign-in and preserves an opaque invitation continuation', () => {
+ const target =
+ 'https://editor.example/cloud/invitations/id?continuation=opaque&server=https%3A%2F%2Fcloud.example'
+ const login = new URL(cloudSignInURL(discovery, target))
+ expect(login.origin).toBe('https://cloud.example')
+ expect(login.pathname).toBe('/auth/sign-in')
+ const callback = new URL(login.searchParams.get('redirect') ?? '', login.origin)
+ expect(callback.pathname).toBe('/auth/return')
+ expect(cloudEditorReturnURL(discovery, callback.searchParams.get('editor') ?? '')).toBe(target)
+})
+
+test('return navigation rejects foreign origins and userinfo and strips fragment secrets', () => {
+ for (const value of [
+ 'https://evil.example',
+ 'https://editor.example.evil.example',
+ 'https://user:[email protected]',
+ // eslint-disable-next-line no-script-url -- Reject script URLs at the untrusted navigation boundary.
+ 'javascript:alert(1)'
+ ]) {
+ expect(() => cloudEditorReturnURL(discovery, value)).toThrow()
+ }
+ expect(cloudEditorReturnURL(discovery, 'https://editor.example/storage#secret')).toBe(
+ 'https://editor.example/storage'
+ )
+ expect(() =>
+ cloudSignInURL({ ...discovery, appURL: undefined }, 'https://editor.example')
+ ).toThrow()
+})
diff --git a/packages/cloud/tests/client/auth.test.ts b/packages/cloud/tests/client/auth.test.ts
new file mode 100644
index 000000000..21b735a05
--- /dev/null
+++ b/packages/cloud/tests/client/auth.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, mock, test } from 'bun:test'
+
+import {
+ createCloudAuthClient,
+ signInToCloud,
+ signOutFromCloud,
+ type CloudFetch
+} from '#cloud/client'
+import { parseCloudDiscovery } from '#cloud/contract'
+
+const discovery = parseCloudDiscovery({
+ protocolVersion: '1',
+ deployment: 'self-hosted' as const,
+ apiURL: 'https://cloud.example.com/api',
+ authURL: 'https://cloud.example.com/api/auth',
+ appURL: 'https://app.example.com',
+ authentication: { socialProviders: ['google' as const], enterpriseSSO: false },
+ capabilities: { documents: true, workspaces: true, collaboration: true }
+})
+
+describe('Cloud Better Auth client', () => {
+ test('sends the CAPTCHA response through Better Auth', async () => {
+ let request: Request | undefined
+ const fetch: CloudFetch = mock(async (input, init) => {
+ request = new Request(input, init)
+ return Response.json({ status: true })
+ })
+ const client = createCloudAuthClient(discovery, {
+ captchaResponse: 'turnstile-token',
+ fetch
+ })
+
+ await client.requestPasswordReset({
+ email: '[email protected]',
+ redirectTo: 'https://cloud.example.com/auth/reset-password'
+ })
+
+ expect(request?.headers.get('x-captcha-response')).toBe('turnstile-token')
+ })
+
+ test('starts social sign-in and signs out through Better Auth client actions', async () => {
+ const requests: Request[] = []
+ const fetch: CloudFetch = mock(async (input, init) => {
+ const request = new Request(input, init)
+ requests.push(request)
+ return request.url.endsWith('/sign-in/social')
+ ? Response.json({ url: 'https://accounts.example.com/authorize' })
+ : Response.json({ success: true })
+ })
+ const navigate = mock(() => undefined)
+
+ await signInToCloud(discovery, 'google', {
+ callbackURL: 'https://app.example.com/settings',
+ fetch,
+ navigate
+ })
+ await signOutFromCloud(discovery, { fetch })
+
+ expect(requests.map((request) => request.url)).toEqual([
+ 'https://cloud.example.com/api/auth/sign-in/social',
+ 'https://cloud.example.com/api/auth/sign-out'
+ ])
+ expect(navigate).toHaveBeenCalledWith('https://accounts.example.com/authorize')
+ })
+})
diff --git a/packages/cloud/tests/client/device-authorization.test.ts b/packages/cloud/tests/client/device-authorization.test.ts
new file mode 100644
index 000000000..0ff5ed771
--- /dev/null
+++ b/packages/cloud/tests/client/device-authorization.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, test } from 'bun:test'
+
+import { pollCloudDeviceToken, requestCloudDeviceAuthorization } from '#cloud/client'
+import type { CloudDeviceAuthorization, CloudFetch } from '#cloud/client'
+import type { CloudDiscovery } from '#cloud/contract'
+
+const discovery: CloudDiscovery = {
+ protocolVersion: '1',
+ deployment: 'self-hosted',
+ apiURL: 'https://cloud.example.com/api',
+ authURL: 'https://cloud.example.com/api/auth',
+ appURL: 'https://app.example.com',
+ authentication: { socialProviders: [], enterpriseSSO: false, enrollmentMode: 'open' },
+ capabilities: { documents: true, workspaces: true, collaboration: true }
+}
+
+function authorization(expiresIn = 600): CloudDeviceAuthorization {
+ return {
+ device_code: 'device-code',
+ user_code: 'ABCD-EFGH',
+ verification_uri: 'https://cloud.example.com/cloud/device',
+ verification_uri_complete: 'https://cloud.example.com/cloud/device?user_code=ABCDEFGH',
+ expires_in: expiresIn,
+ interval: 1
+ }
+}
+
+const immediateSleep = async (): Promise<void> => undefined
+
+describe('Cloud device authorization client', () => {
+ test('requests a connection-scoped device code', async () => {
+ let requestBody: unknown
+ const request: CloudFetch = async (_input, init) => {
+ requestBody = JSON.parse(String(init?.body))
+ return Response.json(authorization())
+ }
+ const result = await requestCloudDeviceAuthorization(discovery, 'connection-id', {
+ fetch: request
+ })
+ expect(result.device_code).toBe('device-code')
+ expect(requestBody).toMatchObject({ client_id: 'openpencil-desktop:connection-id' })
+ })
+
+ test('polls pending authorization until a bearer token is available', async () => {
+ let calls = 0
+ const token = await pollCloudDeviceToken(discovery, 'connection-id', authorization(), {
+ sleep: immediateSleep,
+ async fetch() {
+ calls++
+ return calls === 1
+ ? Response.json(
+ { error: 'authorization_pending', error_description: 'Pending' },
+ { status: 400 }
+ )
+ : Response.json({
+ access_token: 'session-token',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ scope: 'openid profile'
+ })
+ }
+ })
+ expect(token.access_token).toBe('session-token')
+ expect(calls).toBe(2)
+ })
+
+ test('maps denial without retrying', async () => {
+ const error = pollCloudDeviceToken(discovery, 'connection-id', authorization(), {
+ sleep: immediateSleep,
+ fetch: async () =>
+ Response.json(
+ { error: 'access_denied', error_description: 'Authorization denied' },
+ { status: 400 }
+ )
+ })
+ await expect(error).rejects.toMatchObject({
+ name: 'CloudDeviceAuthorizationError',
+ code: 'denied'
+ })
+ })
+
+ test('backs off after a rate limit and keeps polling', async () => {
+ const waits: number[] = []
+ let calls = 0
+ const token = await pollCloudDeviceToken(discovery, 'connection-id', authorization(), {
+ async sleep(milliseconds) {
+ waits.push(milliseconds)
+ },
+ async fetch() {
+ calls++
+ return calls === 1
+ ? Response.json({ message: 'Too many requests' }, { status: 429 })
+ : Response.json({
+ access_token: 'session-token',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ scope: 'openid profile'
+ })
+ }
+ })
+ expect(token.access_token).toBe('session-token')
+ expect(waits).toEqual([1000, 6000])
+ })
+
+ test('reports an unreadable error response as unavailable', async () => {
+ const error = pollCloudDeviceToken(discovery, 'connection-id', authorization(), {
+ sleep: immediateSleep,
+ fetch: async () => new Response('<html>Bad gateway</html>', { status: 502 })
+ })
+ await expect(error).rejects.toMatchObject({
+ name: 'CloudDeviceAuthorizationError',
+ code: 'unavailable'
+ })
+ })
+
+ test('expires before another token request', async () => {
+ let now = 0
+ let requests = 0
+ const error = pollCloudDeviceToken(discovery, 'connection-id', authorization(1), {
+ now: () => now,
+ sleep: async (milliseconds) => {
+ now += milliseconds
+ },
+ fetch: async () => {
+ requests++
+ return Response.json({})
+ }
+ })
+ await expect(error).rejects.toThrow('Cloud device authorization expired')
+ expect(requests).toBe(0)
+ })
+
+ test('cancellation prevents token requests', async () => {
+ const controller = new AbortController()
+ let requests = 0
+ const polling = pollCloudDeviceToken(discovery, 'connection-id', authorization(), {
+ signal: controller.signal,
+ sleep: async (_milliseconds, signal) => {
+ controller.abort(new DOMException('Authorization cancelled', 'AbortError'))
+ signal?.throwIfAborted()
+ },
+ fetch: async () => {
+ requests++
+ return Response.json({})
+ }
+ })
+ await expect(polling).rejects.toHaveProperty('name', 'AbortError')
+ expect(requests).toBe(0)
+ })
+})
diff --git a/packages/cloud/tests/client/discovery.test.ts b/packages/cloud/tests/client/discovery.test.ts
new file mode 100644
index 000000000..3966d1951
--- /dev/null
+++ b/packages/cloud/tests/client/discovery.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, test } from 'bun:test'
+
+import { CloudClientError, discoverCloud } from '#cloud/client'
+import { CLOUD_PROTOCOL_VERSION } from '#cloud/contract'
+
+const discovery = {
+ protocolVersion: CLOUD_PROTOCOL_VERSION,
+ deployment: 'official' as const,
+ apiURL: 'https://cloud.openpencil.dev/api',
+ authURL: 'https://cloud.openpencil.dev/api/auth',
+ appURL: 'https://app.openpencil.dev',
+ authentication: {
+ socialProviders: ['apple' as const, 'google' as const],
+ enterpriseSSO: false,
+ enrollmentMode: 'open' as const,
+ emailPassword: {
+ signIn: true,
+ signUp: true,
+ minimumPasswordLength: 15,
+ captcha: {
+ provider: 'cloudflare-turnstile' as const,
+ siteKey: 'public-site-key'
+ }
+ }
+ },
+ capabilities: {
+ documents: true,
+ workspaces: true,
+ collaboration: false
+ }
+}
+
+describe('discoverCloud', () => {
+ test('loads and validates discovery from the well-known path', async () => {
+ let requestedURL = ''
+ const result = await discoverCloud('https://cloud.openpencil.dev/custom?ignored=yes', {
+ fetch: async (input) => {
+ requestedURL = String(input)
+ return Response.json(discovery)
+ }
+ })
+
+ expect(requestedURL).toBe('https://cloud.openpencil.dev/.well-known/openpencil')
+ expect(result).toEqual(discovery)
+ })
+
+ test('reports non-successful discovery responses', async () => {
+ const request = discoverCloud('https://cloud.openpencil.dev', {
+ fetch: async () => new Response(null, { status: 404 })
+ })
+
+ await expect(request).rejects.toThrow('HTTP 404')
+ })
+
+ test('rejects non-HTTP server URLs before fetching', async () => {
+ const request = discoverCloud('file:///tmp/openpencil', {
+ fetch: async () => Response.json(discovery)
+ })
+
+ await expect(request).rejects.toBeInstanceOf(CloudClientError)
+ })
+})
diff --git a/packages/cloud/tests/client/email-auth.test.ts b/packages/cloud/tests/client/email-auth.test.ts
new file mode 100644
index 000000000..aed5cb481
--- /dev/null
+++ b/packages/cloud/tests/client/email-auth.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ resendCloudVerification,
+ signInToCloudWithEmail,
+ signUpToCloudWithEmail,
+ type CloudFetch
+} from '#cloud/client'
+import { parseCloudDiscovery } from '#cloud/contract'
+
+const discovery = parseCloudDiscovery({
+ protocolVersion: '1',
+ deployment: 'self-hosted' as const,
+ apiURL: 'https://cloud.example.com/api',
+ authURL: 'https://cloud.example.com/api/auth',
+ appURL: 'https://app.example.com',
+ authentication: {
+ socialProviders: [],
+ emailPassword: { signIn: true, signUp: true, minimumPasswordLength: 8 },
+ enterpriseSSO: false
+ },
+ capabilities: { documents: true, workspaces: true, collaboration: true }
+})
+
+const CREDENTIALS = { email: '[email protected]', password: 'correct horse' }
+
+function answering(body: unknown, status = 200): { fetch: CloudFetch; requests: Request[] } {
+ const requests: Request[] = []
+ const fetch: CloudFetch = async (input, init) => {
+ requests.push(new Request(input, init))
+ return Response.json(body, { status })
+ }
+ return { fetch, requests }
+}
+
+describe('signing in to Cloud with an email and password', () => {
+ test('keeps the session token the server answers with', async () => {
+ const { fetch, requests } = answering({ redirect: false, token: 'session-token', user: {} })
+
+ const result = await signInToCloudWithEmail(discovery, CREDENTIALS, { fetch })
+
+ expect(result).toEqual({ ok: true, value: { status: 'signed-in', token: 'session-token' } })
+ expect(requests[0]?.url).toBe('https://cloud.example.com/api/auth/sign-in/email')
+ })
+
+ test('reports a second step instead of a token', async () => {
+ const { fetch } = answering({ twoFactorRedirect: true })
+
+ const result = await signInToCloudWithEmail(discovery, CREDENTIALS, { fetch })
+
+ expect(result).toEqual({ ok: true, value: { status: 'two-step' } })
+ })
+
+ test('tells an unconfirmed email from a wrong password', async () => {
+ const unverified = answering({ code: 'EMAIL_NOT_VERIFIED', message: 'Email not verified' }, 403)
+ const wrong = answering({ code: 'INVALID_EMAIL_OR_PASSWORD', message: 'Invalid' }, 401)
+
+ expect(await signInToCloudWithEmail(discovery, CREDENTIALS, unverified)).toEqual({
+ ok: false,
+ failure: 'email-not-verified'
+ })
+ expect(await signInToCloudWithEmail(discovery, CREDENTIALS, wrong)).toEqual({
+ ok: false,
+ failure: 'invalid-credentials'
+ })
+ })
+
+ test('says the server is unavailable when it cannot be reached', async () => {
+ const fetch: CloudFetch = () => Promise.reject(new TypeError('Failed to fetch'))
+
+ expect(await signInToCloudWithEmail(discovery, CREDENTIALS, { fetch })).toEqual({
+ ok: false,
+ failure: 'unavailable'
+ })
+ })
+})
+
+describe('joining Cloud with an email and password', () => {
+ test('sends the verification link to the page it names', async () => {
+ const { fetch, requests } = answering({ token: null, user: {} })
+
+ const result = await signUpToCloudWithEmail(
+ discovery,
+ { ...CREDENTIALS, name: 'Ada', verifiedURL: 'https://cloud.example.com/auth/verified' },
+ { fetch }
+ )
+
+ expect(result).toEqual({ ok: true, value: undefined })
+ expect(await requests[0]?.json()).toMatchObject({
+ name: 'Ada',
+ email: '[email protected]',
+ callbackURL: 'https://cloud.example.com/auth/verified'
+ })
+ })
+
+ test('asks for another verification link', async () => {
+ const { fetch, requests } = answering({ status: true })
+
+ const result = await resendCloudVerification(
+ discovery,
+ { email: '[email protected]', verifiedURL: 'https://cloud.example.com/auth/verified' },
+ { fetch }
+ )
+
+ expect(result).toEqual({ ok: true, value: undefined })
+ expect(requests[0]?.url).toBe('https://cloud.example.com/api/auth/send-verification-email')
+ })
+})
diff --git a/packages/cloud/tests/client/links.test.ts b/packages/cloud/tests/client/links.test.ts
new file mode 100644
index 000000000..b8564bfa8
--- /dev/null
+++ b/packages/cloud/tests/client/links.test.ts
@@ -0,0 +1,46 @@
+import { expect, test } from 'bun:test'
+
+import { cloudRedirectPath, cloudShareURL } from '#cloud/client'
+import type { CloudDiscovery } from '#cloud/contract'
+
+const discovery: CloudDiscovery = {
+ protocolVersion: '1',
+ deployment: 'self-hosted',
+ apiURL: 'https://company.example/api',
+ authURL: 'https://company.example/api/auth',
+ appURL: 'https://editor.company.example',
+ authentication: { socialProviders: [], enterpriseSSO: false, enrollmentMode: 'open' },
+ capabilities: { documents: true, workspaces: true, collaboration: true }
+}
+
+test('sharing uses the owning public editor without requiring browser globals', () => {
+ const url = new URL(cloudShareURL(discovery, 'https://company.example', 'share-id', 'secret'))
+ expect(url.origin).toBe('https://editor.company.example')
+ expect(url.pathname).toBe('/cloud/share/share-id')
+ expect(url.searchParams.get('server')).toBe('https://company.example')
+ expect(url.hash).toBe('#secret')
+ expect(url.search).not.toContain('secret')
+})
+
+test('sharing rejects absent or non-web editor URLs', () => {
+ expect(() =>
+ cloudShareURL({ ...discovery, appURL: undefined }, discovery.apiURL, 'id', 'secret')
+ ).toThrow()
+ expect(() =>
+ cloudShareURL({ ...discovery, appURL: 'tauri://localhost' }, discovery.apiURL, 'id', 'secret')
+ ).toThrow()
+})
+
+test('authentication continuation stays on the issuing origin', () => {
+ expect(cloudRedirectPath('/cloud/device?user_code=ABCD')).toBe('/cloud/device?user_code=ABCD')
+ for (const input of [
+ '//evil.example',
+ '/\\evil.example',
+ 'https://evil.example',
+ // eslint-disable-next-line no-script-url -- Reject script URLs at the untrusted navigation boundary.
+ 'javascript:alert(1)',
+ undefined
+ ]) {
+ expect(cloudRedirectPath(input)).toBe('/app')
+ }
+})
diff --git a/packages/cloud/tests/contract/account.test.ts b/packages/cloud/tests/contract/account.test.ts
new file mode 100644
index 000000000..12d03b08b
--- /dev/null
+++ b/packages/cloud/tests/contract/account.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, test } from 'bun:test'
+
+import { cloudPasskeysResponseSchema } from '#cloud/contract'
+import * as v from 'valibot'
+
+describe('account contract', () => {
+ test('reads a passkey the browser created without a name', () => {
+ const passkey = { id: 'passkey-1', name: null, createdAt: '2026-10-15T12:54:14.633Z' }
+ expect(v.parse(cloudPasskeysResponseSchema, { passkeys: [passkey] })).toEqual({
+ passkeys: [passkey]
+ })
+ })
+})
diff --git a/packages/cloud/tests/contract/discovery.test.ts b/packages/cloud/tests/contract/discovery.test.ts
new file mode 100644
index 000000000..e7d3feb82
--- /dev/null
+++ b/packages/cloud/tests/contract/discovery.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, test } from 'bun:test'
+
+import { CLOUD_DISCOVERY_PATH, CLOUD_PROTOCOL_VERSION, parseCloudDiscovery } from '#cloud/contract'
+
+const discovery = {
+ protocolVersion: CLOUD_PROTOCOL_VERSION,
+ deployment: 'self-hosted' as const,
+ apiURL: 'https://pencil.example.com/api',
+ authURL: 'https://pencil.example.com/api/auth',
+ appURL: 'https://app.example.com',
+ authentication: {
+ socialProviders: ['google' as const],
+ enterpriseSSO: true,
+ enrollmentMode: 'open' as const,
+ emailPassword: {
+ signIn: true,
+ signUp: false,
+ minimumPasswordLength: 15,
+ captcha: {
+ provider: 'cloudflare-turnstile' as const,
+ siteKey: 'public-site-key'
+ }
+ },
+ mfa: {
+ deploymentAdminRequired: true,
+ totp: true,
+ passkeys: true,
+ recoveryCodes: true
+ }
+ },
+ capabilities: {
+ documents: true,
+ workspaces: true,
+ collaboration: false
+ }
+}
+
+describe('Cloud discovery contract', () => {
+ test('publishes the stable discovery path and protocol version', () => {
+ expect(CLOUD_DISCOVERY_PATH).toBe('/.well-known/openpencil')
+ expect(CLOUD_PROTOCOL_VERSION).toBe('1')
+ })
+
+ test('parses a valid discovery document', () => {
+ expect(parseCloudDiscovery(discovery)).toEqual(discovery)
+ })
+
+ test('rejects an unsupported protocol version', () => {
+ expect(() => parseCloudDiscovery({ ...discovery, protocolVersion: '2' })).toThrow()
+ })
+
+ test('rejects relative service URLs', () => {
+ expect(() => parseCloudDiscovery({ ...discovery, apiURL: '/api' })).toThrow()
+ })
+})
diff --git a/packages/cloud/tests/contract/sharing.test.ts b/packages/cloud/tests/contract/sharing.test.ts
new file mode 100644
index 000000000..7fc281949
--- /dev/null
+++ b/packages/cloud/tests/contract/sharing.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createDocumentShareSchema, updateDocumentShareSchema } from '#cloud/contract'
+import * as v from 'valibot'
+
+describe('document share contract', () => {
+ test('accepts an ISO expiry or none', () => {
+ for (const expiresAt of ['2026-10-18T12:00:00.000Z', null, undefined]) {
+ expect(
+ v.safeParse(createDocumentShareSchema, { permission: 'view', expiresAt }).success
+ ).toBe(true)
+ expect(v.safeParse(updateDocumentShareSchema, { expiresAt }).success).toBe(true)
+ }
+ })
+
+ test('rejects an expiry that is not a timestamp', () => {
+ for (const expiresAt of ['tomorrow', '', '2026-13-40']) {
+ expect(
+ v.safeParse(createDocumentShareSchema, { permission: 'view', expiresAt }).success
+ ).toBe(false)
+ expect(v.safeParse(updateDocumentShareSchema, { expiresAt }).success).toBe(false)
+ }
+ })
+})
diff --git a/packages/cloud/tests/e2e/cloud.ts b/packages/cloud/tests/e2e/cloud.ts
new file mode 100644
index 000000000..3fe36681c
--- /dev/null
+++ b/packages/cloud/tests/e2e/cloud.ts
@@ -0,0 +1,237 @@
+import { createHash } from 'node:crypto'
+
+import { responseJSON } from '#cloud-tests/helpers/response'
+import {
+ CloudAPIError,
+ createCloudAPIClient,
+ type CloudFetch,
+ type CloudUpload
+} from '#cloud/client'
+import { createNodeCloudDatabase, createS3ObjectStore } from '#cloud/runtime/node'
+import {
+ createCloudApp,
+ createBetterAuthAdapter,
+ createDocumentCleanupService,
+ createUploadCleanupService,
+ migrateCloudDatabase,
+ parseCloudServerConfig,
+ type CloudActor,
+ type CloudApp
+} from '#cloud/server'
+import * as v from 'valibot'
+
+const actor: CloudActor = {
+ userId: `e2e-${crypto.randomUUID()}`,
+ email: '[email protected]',
+ name: 'Cloud E2E'
+}
+const config = parseCloudServerConfig({
+ deployment: 'self-hosted',
+ publicURL: 'http://localhost:8787',
+ databaseURL:
+ process.env.DATABASE_URL ??
+ 'postgresql://openpencil:openpencil-development-password@localhost:54329/openpencil',
+ authSecret: 'full-stack-e2e-secret-at-least-32-characters',
+ s3Endpoint: process.env.S3_ENDPOINT ?? 'http://localhost:8333',
+ s3Region: process.env.S3_REGION ?? 'us-east-1',
+ s3Bucket: process.env.S3_BUCKET ?? 'openpencil',
+ s3AccessKeyId: process.env.S3_ACCESS_KEY_ID ?? 'openpencil',
+ s3SecretAccessKey: process.env.S3_SECRET_ACCESS_KEY ?? 'openpencil-development-secret',
+ s3ForcePathStyle: true,
+ s3ChecksumVerification: 'metadata'
+})
+
+function checksum(bytes: Uint8Array): string {
+ return createHash('sha256').update(bytes).digest('base64')
+}
+
+async function uploadBytes(upload: CloudUpload['upload'], bytes: Uint8Array) {
+ if (upload.kind === 'single') {
+ const response = await fetch(upload.url, {
+ method: upload.method,
+ headers: upload.headers,
+ body: bytes.slice()
+ })
+ if (!response.ok) throw new Error(`Single upload failed with HTTP ${response.status}`)
+ return undefined
+ }
+ const parts = []
+ for (const part of upload.parts) {
+ const start = (part.partNumber - 1) * upload.partSize
+ const response = await fetch(part.url, {
+ method: part.method,
+ headers: part.headers,
+ body: bytes.slice(start, Math.min(bytes.byteLength, start + upload.partSize))
+ })
+ if (!response.ok) throw new Error(`Part ${part.partNumber} failed with HTTP ${response.status}`)
+ const etag = response.headers.get('etag')
+ if (!etag) throw new Error(`Part ${part.partNumber} did not return an ETag`)
+ parts.push({ partNumber: part.partNumber, etag })
+ }
+ return { uploadId: upload.uploadId, parts }
+}
+
+function appFetch(app: CloudApp): CloudFetch {
+ return async (input, init) =>
+ app.fetch(input instanceof Request ? input : new Request(input, init))
+}
+
+const database = createNodeCloudDatabase({ connectionString: config.databaseURL })
+const objects = createS3ObjectStore(config)
+try {
+ const auth = createBetterAuthAdapter(config, database)
+ await migrateCloudDatabase(database, { run: auth.migrate, schemaVersion: auth.schemaVersion })
+ const app = createCloudApp({ config, database, auth, objects, resolveSession: async () => actor })
+ const ready = await app.request('/ready')
+ if (!ready.ok) throw new Error(`Cloud readiness failed with HTTP ${ready.status}`)
+
+ const workspaceResponse = await app.request('/api/workspaces', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'Cloud E2E', slug: `cloud-e2e-${crypto.randomUUID()}` })
+ })
+ if (workspaceResponse.status !== 201) {
+ throw new Error(`Workspace creation failed with HTTP ${workspaceResponse.status}`)
+ }
+ const workspaceBody = await responseJSON(
+ workspaceResponse,
+ v.object({ workspace: v.object({ id: v.string() }) })
+ )
+ const client = createCloudAPIClient('http://localhost:8787/api', { fetch: appFetch(app) })
+ const document = await client.createDocument(workspaceBody.workspace.id, {
+ id: crypto.randomUUID(),
+ name: 'E2E.fig'
+ })
+
+ const firstBytes = new TextEncoder().encode('OpenPencil Cloud full-stack E2E revision one')
+ const firstChecksum = checksum(firstBytes)
+ const firstUpload = await client.createUpload(document.id, {
+ baseRevisionId: null,
+ byteSize: firstBytes.byteLength,
+ checksum: firstChecksum,
+ contentType: 'application/octet-stream'
+ })
+ const firstMultipart = await uploadBytes(firstUpload.upload, firstBytes)
+ if (firstMultipart) throw new Error('Expected the first revision to use a single PUT')
+ const firstRevision = await client.commitUpload(firstUpload.id, { checksum: firstChecksum })
+ if (!firstRevision.currentRevisionId || firstRevision.version !== 1) {
+ throw new Error('First revision was not committed')
+ }
+ const repeated = await client.commitUpload(firstUpload.id, { checksum: firstChecksum })
+ if (repeated.currentRevisionId !== firstRevision.currentRevisionId || repeated.version !== 1) {
+ throw new Error('Repeated commit was not idempotent')
+ }
+
+ try {
+ await client.createUpload(document.id, {
+ baseRevisionId: null,
+ byteSize: firstBytes.byteLength,
+ checksum: firstChecksum,
+ contentType: 'application/octet-stream'
+ })
+ throw new Error('Expected a stale revision conflict')
+ } catch (error) {
+ if (!(error instanceof CloudAPIError) || error.code !== 'revision_conflict') throw error
+ }
+
+ const secondBytes = new Uint8Array(33 * 1024 * 1024)
+ for (let index = 0; index < secondBytes.byteLength; index++) secondBytes[index] = index % 251
+ const secondChecksum = checksum(secondBytes)
+ const secondUpload = await client.createUpload(document.id, {
+ baseRevisionId: firstRevision.currentRevisionId,
+ byteSize: secondBytes.byteLength,
+ checksum: secondChecksum,
+ contentType: 'application/octet-stream'
+ })
+ const secondMultipart = await uploadBytes(secondUpload.upload, secondBytes)
+ if (!secondMultipart) throw new Error('Expected the second revision to use multipart upload')
+ const secondRevision = await client.commitUpload(secondUpload.id, {
+ checksum: secondChecksum,
+ multipart: secondMultipart
+ })
+ if (secondRevision.version !== 2) throw new Error('Second revision was not committed')
+
+ const remote = await client.getDocument(document.id)
+ const downloaded = await fetch(remote.download.url)
+ const downloadedChecksum = checksum(new Uint8Array(await downloaded.arrayBuffer()))
+ if (!downloaded.ok || downloadedChecksum !== secondChecksum) {
+ throw new Error('Committed revision download did not match its SHA-256')
+ }
+
+ const abandonedUploads = await Promise.all(
+ Array.from({ length: 3 }, () =>
+ client.createUpload(document.id, {
+ baseRevisionId: secondRevision.currentRevisionId,
+ byteSize: secondBytes.byteLength,
+ checksum: secondChecksum,
+ contentType: 'application/octet-stream'
+ })
+ )
+ )
+ if (abandonedUploads.some((upload) => upload.upload.kind !== 'multipart')) {
+ throw new Error('Expected cleanup fixtures to use multipart uploads')
+ }
+ const cleanupOptions = {
+ batchSize: 2,
+ leaseDurationMs: 5 * 60 * 1000,
+ now: new Date(Date.now() + 16 * 60 * 1000)
+ }
+ const cleanupWorkers = [
+ createUploadCleanupService(database, objects),
+ createUploadCleanupService(database, objects)
+ ]
+ const cleanupResults = await Promise.all(
+ cleanupWorkers.map((cleanup) => cleanup.cleanupExpiredUploads(cleanupOptions))
+ )
+ if (
+ cleanupResults.reduce((total, result) => total + result.claimed, 0) !== 3 ||
+ cleanupResults.reduce((total, result) => total + result.cleaned, 0) !== 3 ||
+ cleanupResults.some((result) => result.failed !== 0)
+ ) {
+ throw new Error(
+ `Concurrent cleanup returned unexpected results: ${JSON.stringify(cleanupResults)}`
+ )
+ }
+
+ const usage = await client.getUsage(workspaceBody.workspace.id)
+ if (
+ usage.documentCount !== 1 ||
+ usage.objectCount !== 1 ||
+ usage.bytesUsed !== secondBytes.byteLength
+ ) {
+ throw new Error(`Unexpected workspace usage: ${JSON.stringify(usage)}`)
+ }
+ await client.deleteDocument(document.id)
+ if ((await client.listDocuments(workspaceBody.workspace.id)).length !== 0) {
+ throw new Error('Soft-deleted document remained in the workspace listing')
+ }
+ const documentCleanup = await createDocumentCleanupService(
+ database,
+ objects
+ ).cleanupDeletedDocuments({
+ batchSize: 1,
+ leaseDurationMs: 5 * 60 * 1000,
+ retentionMs: 0
+ })
+ if (
+ documentCleanup.cleaned !== 1 ||
+ documentCleanup.objectsDeleted !== 2 ||
+ documentCleanup.bytesReclaimed !== firstBytes.byteLength + secondBytes.byteLength
+ ) {
+ throw new Error(
+ `Document cleanup returned unexpected results: ${JSON.stringify(documentCleanup)}`
+ )
+ }
+ if (
+ await database
+ .selectFrom('document')
+ .select('id')
+ .where('id', '=', document.id)
+ .executeTakeFirst()
+ ) {
+ throw new Error('Retained document metadata was not removed')
+ }
+ console.log('Cloud full-stack E2E passed (PostgreSQL, single PUT, multipart, conflict, cleanup)')
+} finally {
+ await database.destroy()
+}
diff --git a/packages/cloud/tests/e2e/compose.mailpit.yml b/packages/cloud/tests/e2e/compose.mailpit.yml
new file mode 100644
index 000000000..0de6276a5
--- /dev/null
+++ b/packages/cloud/tests/e2e/compose.mailpit.yml
@@ -0,0 +1,4 @@
+services:
+ mailpit:
+ ports:
+ - '127.0.0.1:${MAILPIT_SMTP_PORT}:1025'
diff --git a/packages/cloud/tests/e2e/garage.ts b/packages/cloud/tests/e2e/garage.ts
new file mode 100644
index 000000000..3fa1fe5c0
--- /dev/null
+++ b/packages/cloud/tests/e2e/garage.ts
@@ -0,0 +1,28 @@
+import { cloudDeployPath, cloudPackagePath } from '#cloud-tests/helpers/paths'
+import { composeCommand, runProcess } from '#cloud-tests/helpers/process'
+
+const deployDirectory = cloudDeployPath()
+const objectStoreTest = cloudPackagePath('tests/e2e/object-store.ts')
+const projectName = `openpencil-cloud-garage-e2e-${process.pid}`
+const compose = composeCommand(projectName, 'compose.garage.yml')
+const environment = {
+ ...process.env,
+ S3_COMPAT_PROVIDER: 'Garage',
+ S3_ENDPOINT: 'http://localhost:3900',
+ S3_REGION: 'garage',
+ S3_BUCKET: process.env.GARAGE_BUCKET ?? 'openpencil',
+ S3_ACCESS_KEY_ID: process.env.GARAGE_ACCESS_KEY_ID ?? 'GKopenpencildevelopment0000000000',
+ S3_SECRET_ACCESS_KEY:
+ process.env.GARAGE_SECRET_ACCESS_KEY ?? 'openpencil-garage-development-secret-key'
+}
+
+async function run(command: string[], cwd = deployDirectory): Promise<void> {
+ await runProcess(command, { cwd, environment })
+}
+
+try {
+ await run([...compose, 'up', '-d', '--wait'])
+ await run(['bun', objectStoreTest], cloudPackagePath('tests/e2e'))
+} finally {
+ await run([...compose, 'down', '--volumes'])
+}
diff --git a/packages/cloud/tests/e2e/object-store.ts b/packages/cloud/tests/e2e/object-store.ts
new file mode 100644
index 000000000..ff446d71c
--- /dev/null
+++ b/packages/cloud/tests/e2e/object-store.ts
@@ -0,0 +1,122 @@
+import { createHash } from 'node:crypto'
+
+import { createS3ObjectStore } from '#cloud/runtime/node'
+import { parseCloudServerConfig } from '#cloud/server'
+import { CreateBucketCommand, S3Client } from '@aws-sdk/client-s3'
+
+const endpoint = process.env.S3_ENDPOINT ?? 'http://localhost:8333'
+const bucket = process.env.S3_BUCKET ?? 'openpencil-smoke'
+const accessKeyId = process.env.S3_ACCESS_KEY_ID ?? 'openpencil'
+const secretAccessKey = process.env.S3_SECRET_ACCESS_KEY ?? 'openpencil-development-secret'
+const provider = process.env.S3_COMPAT_PROVIDER ?? 'S3-compatible storage'
+
+const config = parseCloudServerConfig({
+ deployment: 'self-hosted',
+ publicURL: 'http://localhost:8787',
+ databaseURL: 'postgresql://openpencil:openpencil-development-password@localhost/openpencil',
+ authSecret: 'object-store-smoke-secret-at-least-32-characters',
+ s3Endpoint: endpoint,
+ s3Region: process.env.S3_REGION ?? 'us-east-1',
+ s3Bucket: bucket,
+ s3AccessKeyId: accessKeyId,
+ s3SecretAccessKey: secretAccessKey,
+ s3ForcePathStyle: true,
+ s3ChecksumVerification: 'metadata'
+})
+
+const client = new S3Client({
+ endpoint,
+ region: process.env.S3_REGION ?? 'us-east-1',
+ forcePathStyle: true,
+ credentials: { accessKeyId, secretAccessKey }
+})
+try {
+ await client.send(new CreateBucketCommand({ Bucket: bucket }))
+} catch (error) {
+ const name = error instanceof Error ? error.name : ''
+ if (name !== 'BucketAlreadyOwnedByYou' && name !== 'BucketAlreadyExists') throw error
+}
+
+const store = createS3ObjectStore(config)
+const readiness = await store.checkReadiness()
+if (!readiness.ok || readiness.checksumVerification !== 'metadata') {
+ throw new Error(`Unexpected object-store readiness: ${JSON.stringify(readiness)}`)
+}
+
+const singleBytes = new TextEncoder().encode(`OpenPencil Cloud ${provider} smoke`)
+const singleChecksum = createHash('sha256').update(singleBytes).digest('base64')
+const singleKey = `smoke/${crypto.randomUUID()}-single.fig`
+const singleUpload = await store.createUpload({
+ key: singleKey,
+ byteSize: singleBytes.byteLength,
+ checksum: singleChecksum,
+ contentType: 'application/octet-stream',
+ expiresAt: new Date(Date.now() + 10 * 60 * 1000)
+})
+if (singleUpload.kind !== 'single') throw new Error('Expected single-part upload')
+const singleResponse = await fetch(singleUpload.url, {
+ method: singleUpload.method,
+ headers: singleUpload.headers,
+ body: singleBytes
+})
+if (!singleResponse.ok) throw new Error(`Single upload failed: ${singleResponse.status}`)
+const singleStored = await store.head(singleKey)
+if (
+ !singleStored ||
+ singleStored.byteSize !== singleBytes.byteLength ||
+ singleStored.checksum !== singleChecksum
+) {
+ throw new Error(`Single object verification failed: ${JSON.stringify(singleStored)}`)
+}
+await store.delete(singleKey)
+
+const byteSize = 33 * 1024 * 1024
+const bytes = new Uint8Array(byteSize)
+for (let index = 0; index < bytes.length; index++) bytes[index] = index % 251
+const checksum = createHash('sha256').update(bytes).digest('base64')
+const key = `smoke/${crypto.randomUUID()}.fig`
+const upload = await store.createUpload({
+ key,
+ byteSize,
+ checksum,
+ contentType: 'application/octet-stream',
+ expiresAt: new Date(Date.now() + 10 * 60 * 1000)
+})
+if (upload.kind !== 'multipart') throw new Error('Expected multipart upload')
+
+const parts = []
+for (const part of upload.parts) {
+ const start = (part.partNumber - 1) * upload.partSize
+ const end = Math.min(bytes.length, start + upload.partSize)
+ const response = await fetch(part.url, {
+ method: part.method,
+ headers: part.headers,
+ body: Uint8Array.from(bytes.subarray(start, end))
+ })
+ if (!response.ok) throw new Error(`Part ${part.partNumber} failed: ${response.status}`)
+ const etag = response.headers.get('etag')
+ if (!etag) throw new Error(`Part ${part.partNumber} did not return an ETag`)
+ parts.push({ partNumber: part.partNumber, etag })
+}
+await store.completeUpload({ key, uploadId: upload.uploadId, parts })
+const stored = await store.head(key)
+if (!stored || stored.byteSize !== byteSize || stored.checksum !== checksum) {
+ throw new Error(`Stored object verification failed: ${JSON.stringify(stored)}`)
+}
+const download = await store.createDownload({
+ key,
+ expiresAt: new Date(Date.now() + 10 * 60 * 1000)
+})
+const downloadResponse = await fetch(download.url, {
+ method: download.method,
+ headers: download.headers
+})
+if (!downloadResponse.ok) throw new Error(`Download failed: ${downloadResponse.status}`)
+const downloadedChecksum = createHash('sha256')
+ .update(new Uint8Array(await downloadResponse.arrayBuffer()))
+ .digest('base64')
+if (downloadedChecksum !== checksum) throw new Error('Downloaded object checksum did not match')
+await store.delete(key)
+console.log(
+ `${provider} smoke passed (single PUT, ${parts.length} multipart parts, verified GET, ${byteSize} bytes)`
+)
diff --git a/packages/cloud/tests/e2e/run.ts b/packages/cloud/tests/e2e/run.ts
new file mode 100644
index 000000000..668a43ead
--- /dev/null
+++ b/packages/cloud/tests/e2e/run.ts
@@ -0,0 +1,29 @@
+import { cloudDeployPath, cloudPackagePath } from '#cloud-tests/helpers/paths'
+import { composeCommand, runProcess } from '#cloud-tests/helpers/process'
+
+const deployDirectory = cloudDeployPath()
+const e2ePath = (...segments: string[]) => cloudPackagePath('tests/e2e', ...segments)
+const compose = composeCommand(`openpencil-cloud-e2e-${process.pid}`, 'compose.yml')
+const portOffset = process.pid % 1_000
+const environment = {
+ ...process.env,
+ S3_BUCKET: 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),
+ DATABASE_URL: `postgresql://openpencil:[email protected]:${20_000 + portOffset}/openpencil`,
+ S3_ENDPOINT: `http://127.0.0.1:${21_000 + portOffset}`
+}
+
+async function run(command: string[], cwd = deployDirectory): Promise<void> {
+ await runProcess(command, { cwd, environment })
+}
+
+try {
+ await run([...compose, 'up', '-d', '--wait', 'postgres', 'seaweedfs'])
+ await run([...compose, 'run', '--rm', 'seaweedfs-init'])
+ await run(['bun', e2ePath('object-store.ts')], e2ePath())
+ await run(['bun', e2ePath('cloud.ts')], e2ePath())
+} finally {
+ await run([...compose, 'down', '--volumes'])
+}
diff --git a/packages/cloud/tests/e2e/session.ts b/packages/cloud/tests/e2e/session.ts
new file mode 100644
index 000000000..a84abd01a
--- /dev/null
+++ b/packages/cloud/tests/e2e/session.ts
@@ -0,0 +1,49 @@
+import type {
+ CloudActor,
+ CloudIdentity,
+ CloudIdentityResolver,
+ CloudSessionResolver
+} from '#cloud/server'
+
+const TEST_SESSION_COOKIE = 'openpencil-cloud-e2e-session'
+
+export const cloudE2EActors = {
+ owner: {
+ userId: '11111111-1111-4111-8111-111111111111',
+ email: '[email protected]',
+ name: 'Cloud Owner',
+ deploymentRole: 'admin'
+ },
+ recipient: {
+ userId: '22222222-2222-4222-8222-222222222222',
+ email: '[email protected]',
+ name: 'Cloud Recipient'
+ },
+ pending: {
+ userId: '33333333-3333-4333-8333-333333333333',
+ email: '[email protected]',
+ name: 'Pending User'
+ }
+} satisfies Record<string, CloudActor>
+
+function requestIdentity(request: Request): CloudIdentity | null {
+ const cookie = request.headers.get('cookie') ?? ''
+ const session = cookie
+ .split(';')
+ .map((part) => part.trim().split('='))
+ .find(([name]) => name === TEST_SESSION_COOKIE)?.[1]
+ return session === 'owner' || session === 'recipient' || session === 'pending'
+ ? cloudE2EActors[session]
+ : null
+}
+
+export function createCloudE2EIdentityResolver(): CloudIdentityResolver {
+ return async (request) => requestIdentity(request)
+}
+
+export function createCloudE2ESessionResolver(): CloudSessionResolver {
+ return async (request) => {
+ const identity = requestIdentity(request)
+ return identity?.userId === cloudE2EActors.pending.userId ? null : identity
+ }
+}
diff --git a/packages/cloud/tests/helpers/account-authentication.ts b/packages/cloud/tests/helpers/account-authentication.ts
new file mode 100644
index 000000000..5926c9ee7
--- /dev/null
+++ b/packages/cloud/tests/helpers/account-authentication.ts
@@ -0,0 +1,152 @@
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createCloudApp, createBetterAuthAdapter, parseCloudServerConfig } from '#cloud/server'
+
+export const accountAuthenticationConfig = parseCloudServerConfig({
+ deployment: 'self-hosted',
+ publicURL: 'https://cloud.example.com',
+ databaseURL: 'postgresql://test:test@localhost/test',
+ authSecret: 'account-authentication-test-secret-at-least-32-characters',
+ enrollmentMode: 'approval',
+ emailPasswordEnabled: true,
+ emailTransport: 'smtp',
+ emailFrom: '[email protected]',
+ smtpHost: 'smtp.example.com',
+ smtpPort: 465,
+ smtpSecure: true,
+ s3Endpoint: 'https://objects.example.com',
+ s3Region: 'us-east-1',
+ s3Bucket: 'openpencil',
+ s3AccessKeyId: 'access-key',
+ s3SecretAccessKey: 'secret-key'
+})
+
+const ignore = async (): Promise<void> => {
+ await Promise.resolve()
+}
+
+export function accountAuthenticationRequest(
+ path: string,
+ body?: object,
+ cookie?: string
+): Request {
+ const headers = new Headers()
+ if (body) headers.set('Content-Type', 'application/json')
+ if (cookie) headers.set('Cookie', cookie)
+ return new Request(new URL(path, accountAuthenticationConfig.publicURL), {
+ method: body ? 'POST' : 'GET',
+ headers,
+ body: body ? JSON.stringify(body) : undefined
+ })
+}
+
+export function authenticationCookie(response: Response): string {
+ const value = response.headers.get('set-cookie')?.split(';', 1)[0]
+ if (!value) throw new Error('Authentication response did not set a cookie')
+ return value
+}
+
+export function accountAuthenticationObjects() {
+ return {
+ capabilities: { nativeSHA256: true, multipartUpload: false, conditionalWrites: false },
+ async checkReadiness() {
+ return { ok: true, checksumVerification: 'native' as const }
+ },
+ async createDownload() {
+ throw new Error('not used')
+ },
+ async createUpload() {
+ throw new Error('not used')
+ },
+ completeUpload: ignore,
+ abortUpload: ignore,
+ async head() {
+ return null
+ },
+ delete: ignore
+ }
+}
+
+export async function createAccountAuthenticationFixture(
+ options: {
+ config?: typeof accountAuthenticationConfig
+ onPasswordChanged?: () => void
+ } = {}
+) {
+ const config = options.config ?? accountAuthenticationConfig
+ const runtime = await createCloudTestDatabase()
+ const auth = createBetterAuthAdapter(config, runtime.database, undefined, {
+ email: {
+ sendVerification: ignore,
+ sendPasswordReset: ignore,
+ async sendPasswordChanged() {
+ options.onPasswordChanged?.()
+ }
+ }
+ })
+ return {
+ ...runtime,
+ app: createCloudApp({
+ config,
+ database: runtime.database,
+ auth,
+ objects: accountAuthenticationObjects()
+ })
+ }
+}
+
+export async function approveAccount(
+ database: Awaited<ReturnType<typeof createAccountAuthenticationFixture>>['database'],
+ input: { email: string; name: string; userId: string }
+): Promise<void> {
+ await database
+ .insertInto('cloudEnrollment')
+ .values({
+ id: crypto.randomUUID(),
+ emailNormalized: input.email,
+ name: input.name,
+ reason: null,
+ status: 'approved',
+ reviewedAt: new Date(),
+ reviewedBy: 'admin',
+ reviewNote: null,
+ approvedUserId: input.userId
+ })
+ .execute()
+}
+
+export async function createVerifiedCredentialAccount(
+ fixture: Awaited<ReturnType<typeof createAccountAuthenticationFixture>>,
+ input: { email: string; name: string; password: string; approved: boolean }
+): Promise<{ userId: string; sessionCookie: string }> {
+ await fixture.app.fetch(
+ accountAuthenticationRequest('/api/auth/sign-up/email', {
+ name: input.name,
+ email: input.email,
+ password: input.password
+ })
+ )
+ const user = await fixture.database
+ .selectFrom('user')
+ .select('id')
+ .where('email', '=', input.email)
+ .executeTakeFirstOrThrow()
+ await fixture.database
+ .updateTable('user')
+ .set({ emailVerified: true })
+ .where('id', '=', user.id)
+ .execute()
+ if (input.approved) {
+ await approveAccount(fixture.database, {
+ email: input.email,
+ name: input.name,
+ userId: user.id
+ })
+ }
+ const signIn = await fixture.app.fetch(
+ accountAuthenticationRequest('/api/auth/sign-in/email', {
+ email: input.email,
+ password: input.password
+ })
+ )
+ return { userId: user.id, sessionCookie: authenticationCookie(signIn) }
+}
diff --git a/packages/cloud/tests/helpers/database.ts b/packages/cloud/tests/helpers/database.ts
new file mode 100644
index 000000000..19c59dfd7
--- /dev/null
+++ b/packages/cloud/tests/helpers/database.ts
@@ -0,0 +1,40 @@
+import {
+ createBetterAuthAdapter,
+ createCloudDatabase,
+ migrateCloudDatabase,
+ parseCloudServerConfig
+} from '#cloud/server'
+import { PGlite } from '@electric-sql/pglite'
+import { PGliteDialect } from 'kysely-pglite-dialect'
+
+export type CloudTestDatabase = {
+ database: ReturnType<typeof createCloudDatabase>
+ close(): Promise<void>
+}
+
+const testConfig = parseCloudServerConfig({
+ deployment: 'self-hosted',
+ publicURL: 'http://localhost:8787',
+ databaseURL: 'postgresql://test:test@localhost/test',
+ authSecret: 'integration-test-secret-at-least-32-characters',
+ s3Endpoint: 'http://localhost:9000',
+ s3Region: 'us-east-1',
+ s3Bucket: 'openpencil',
+ s3AccessKeyId: 'openpencil',
+ s3SecretAccessKey: 'openpencil-secret'
+})
+
+export async function createCloudTestDatabase(): Promise<CloudTestDatabase> {
+ const pglite = await PGlite.create({ dataDir: 'memory://' })
+ const database = createCloudDatabase({
+ dialect: new PGliteDialect(pglite)
+ })
+ const auth = createBetterAuthAdapter(testConfig, database)
+ await migrateCloudDatabase(database, { run: auth.migrate, schemaVersion: auth.schemaVersion })
+ return {
+ database,
+ async close() {
+ await database.destroy()
+ }
+ }
+}
diff --git a/packages/cloud/tests/helpers/objects.ts b/packages/cloud/tests/helpers/objects.ts
new file mode 100644
index 000000000..f0c2c0575
--- /dev/null
+++ b/packages/cloud/tests/helpers/objects.ts
@@ -0,0 +1,52 @@
+import type { ObjectStore, StoredObject } from '#cloud/server'
+
+export function createMemoryObjectStore() {
+ const stored = new Map<string, StoredObject>()
+ const deletedKeys: string[] = []
+ const store: ObjectStore = {
+ capabilities: {
+ nativeSHA256: true,
+ multipartUpload: false,
+ conditionalWrites: false
+ },
+ async checkReadiness() {
+ return { ok: true, checksumVerification: 'native' }
+ },
+ async createDownload(input) {
+ return {
+ url: `https://objects.example.com/${input.key}`,
+ method: 'GET',
+ headers: {},
+ expiresAt: input.expiresAt.toISOString()
+ }
+ },
+ async createUpload(input) {
+ return {
+ kind: 'single',
+ url: `https://objects.example.com/${input.key}`,
+ method: 'PUT',
+ headers: {
+ 'Content-Type': input.contentType,
+ 'x-amz-checksum-sha256': input.checksum
+ },
+ expiresAt: input.expiresAt.toISOString()
+ }
+ },
+ completeUpload: async () => undefined,
+ abortUpload: async () => undefined,
+ async head(key) {
+ return stored.get(key) ?? null
+ },
+ async delete(key) {
+ stored.delete(key)
+ deletedKeys.push(key)
+ }
+ }
+ return {
+ store,
+ deletedKeys,
+ put(key: string, object: StoredObject) {
+ stored.set(key, object)
+ }
+ }
+}
diff --git a/packages/cloud/tests/helpers/paths.ts b/packages/cloud/tests/helpers/paths.ts
new file mode 100644
index 000000000..91362c882
--- /dev/null
+++ b/packages/cloud/tests/helpers/paths.ts
@@ -0,0 +1,17 @@
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const cloudPackageRoot = dirname(dirname(dirname(fileURLToPath(import.meta.url))))
+const repositoryRoot = dirname(dirname(cloudPackageRoot))
+
+export function cloudPackagePath(...segments: string[]): string {
+ return join(cloudPackageRoot, ...segments)
+}
+
+export function repositoryPath(...segments: string[]): string {
+ return join(repositoryRoot, ...segments)
+}
+
+export function cloudDeployPath(...segments: string[]): string {
+ return cloudPackagePath('deploy', ...segments)
+}
diff --git a/packages/cloud/tests/helpers/process.ts b/packages/cloud/tests/helpers/process.ts
new file mode 100644
index 000000000..7d4bb202f
--- /dev/null
+++ b/packages/cloud/tests/helpers/process.ts
@@ -0,0 +1,27 @@
+export type RunProcessOptions = {
+ cwd: string
+ environment?: Record<string, string | undefined>
+ stdout?: 'inherit' | 'pipe'
+}
+
+export async function runProcess(command: string[], options: RunProcessOptions): Promise<void> {
+ const child = Bun.spawn(command, {
+ cwd: options.cwd,
+ env: options.environment ?? process.env,
+ stderr: 'inherit',
+ stdout: options.stdout ?? 'inherit'
+ })
+ const exitCode = await child.exited
+ if (exitCode !== 0) throw new Error(`${command.join(' ')} exited with code ${exitCode}`)
+}
+
+export function composeCommand(projectName: string, composeFiles: string | string[]): string[] {
+ const files = typeof composeFiles === 'string' ? [composeFiles] : composeFiles
+ return [
+ 'docker',
+ 'compose',
+ '--project-name',
+ projectName,
+ ...files.flatMap((file) => ['-f', file])
+ ]
+}
diff --git a/packages/cloud/tests/helpers/response.ts b/packages/cloud/tests/helpers/response.ts
new file mode 100644
index 000000000..7a18f8976
--- /dev/null
+++ b/packages/cloud/tests/helpers/response.ts
@@ -0,0 +1,8 @@
+import * as v from 'valibot'
+
+export async function responseJSON<TSchema extends v.GenericSchema>(
+ response: Response,
+ schema: TSchema
+): Promise<v.InferOutput<TSchema>> {
+ return v.parse(v.pipe(v.string(), v.parseJson(), schema), await response.text())
+}
diff --git a/packages/cloud/tests/helpers/sharing.ts b/packages/cloud/tests/helpers/sharing.ts
new file mode 100644
index 000000000..fc1b373f2
--- /dev/null
+++ b/packages/cloud/tests/helpers/sharing.ts
@@ -0,0 +1,64 @@
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import {
+ CLOUD_FEATURE_KEYS,
+ createDefaultCloudPolicy,
+ createDocumentSharingService,
+ EntitlementOpenFeatureProvider,
+ StaticEntitlementSource
+} from '#cloud/server'
+
+export async function seedSharing() {
+ const runtime = await createCloudTestDatabase()
+ const workspaceId = crypto.randomUUID()
+ const documentId = crypto.randomUUID()
+ await runtime.database
+ .insertInto('workspace')
+ .values({ id: workspaceId, name: 'Design', slug: `design-${workspaceId}`, createdBy: 'owner' })
+ .execute()
+ await runtime.database
+ .insertInto('workspaceMember')
+ .values([
+ { workspaceId, userId: 'owner', role: 'admin' },
+ { workspaceId, userId: 'viewer', role: 'viewer' }
+ ])
+ .execute()
+ await runtime.database
+ .insertInto('document')
+ .values({ id: documentId, workspaceId, name: 'Homepage', createdBy: 'owner' })
+ .execute()
+ return { runtime, documentId, sharing: createDocumentSharingService(runtime.database) }
+}
+
+export function sharingWithPolicy(
+ context: Awaited<ReturnType<typeof seedSharing>>,
+ values: Record<string, boolean>,
+ deploymentMode: 'official' | 'self-hosted' = 'self-hosted'
+) {
+ const policy = createDefaultCloudPolicy(
+ new EntitlementOpenFeatureProvider(new StaticEntitlementSource(values))
+ )
+ return createDocumentSharingService(context.runtime.database, { policy, deploymentMode })
+}
+
+export async function assignOwnerUser(
+ context: Awaited<ReturnType<typeof seedSharing>>,
+ input: { id: string; name: string; email: string }
+): Promise<void> {
+ await context.runtime.database
+ .insertInto('user')
+ .values({ ...input, emailVerified: true, image: null })
+ .execute()
+ const workspace = await context.runtime.database
+ .selectFrom('document')
+ .select('workspaceId')
+ .where('id', '=', context.documentId)
+ .executeTakeFirstOrThrow()
+ await context.runtime.database
+ .updateTable('workspaceMember')
+ .set({ userId: input.id })
+ .where('workspaceId', '=', workspace.workspaceId)
+ .where('userId', '=', 'owner')
+ .execute()
+}
+
+export { CLOUD_FEATURE_KEYS }
diff --git a/packages/cloud/tests/integration/admin/email/service.test.ts b/packages/cloud/tests/integration/admin/email/service.test.ts
new file mode 100644
index 000000000..fd6481e03
--- /dev/null
+++ b/packages/cloud/tests/integration/admin/email/service.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import {
+ createAdminEmailService,
+ createTransactionalEmailService,
+ AdminDomainError
+} from '#cloud/server'
+
+describe('admin email regeneration', () => {
+ test('regenerates an enrollment message from authoritative enrollment state', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ await runtime.database
+ .insertInto('cloudEnrollment')
+ .values({
+ id: crypto.randomUUID(),
+ emailNormalized: '[email protected]',
+ name: 'Person',
+ reason: null,
+ status: 'approved',
+ reviewedAt: new Date(),
+ reviewedBy: 'admin',
+ reviewNote: null,
+ approvedUserId: null
+ })
+ .execute()
+ const email = createTransactionalEmailService(runtime.database, {
+ encryptionSecret: 'regeneration-secret-at-least-32-characters',
+ })
+ const original = await email.enqueue({
+ idempotencyKey: 'original',
+ kind: 'enrollment-approved',
+ recipientEmail: '[email protected]',
+ payload: { name: 'Person', actionURL: 'https://cloud.example.com' }
+ })
+ await runtime.database
+ .updateTable('transactionalEmail')
+ .set({ status: 'failed', payloadEncrypted: null })
+ .where('id', '=', original)
+ .execute()
+ await createAdminEmailService(
+ runtime.database,
+ email,
+ 'https://cloud.example.com'
+ ).regenerate('admin', original)
+ const rows = await runtime.database
+ .selectFrom('transactionalEmail')
+ .select(['id', 'kind', 'status'])
+ .orderBy('createdAt')
+ .execute()
+ expect(rows).toHaveLength(2)
+ expect(rows[1]).toMatchObject({ kind: 'enrollment-approved', status: 'pending' })
+ expect(
+ await runtime.database
+ .selectFrom('cloudAdminAuditEvent')
+ .select('action')
+ .executeTakeFirstOrThrow()
+ ).toEqual({ action: 'email.regenerated' })
+ } finally {
+ await runtime.close()
+ }
+ })
+ test('rejects regeneration when authoritative data is unavailable', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const email = createTransactionalEmailService(runtime.database, {
+ encryptionSecret: 'regeneration-secret-at-least-32-characters',
+ })
+ const id = await email.enqueue({
+ idempotencyKey: 'invitation',
+ kind: 'document-invitation',
+ recipientEmail: '[email protected]',
+ payload: {
+ inviterName: 'A',
+ documentName: 'D',
+ permission: 'view',
+ expiresAt: new Date().toISOString(),
+ acceptanceURL: 'https://example.com'
+ }
+ })
+ await expect(
+ createAdminEmailService(runtime.database, email, 'https://cloud.example.com').regenerate(
+ 'admin',
+ id
+ )
+ ).rejects.toBeInstanceOf(AdminDomainError)
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('refuses to resend a message the enrollment no longer matches', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ await runtime.database
+ .insertInto('cloudEnrollment')
+ .values({
+ id: crypto.randomUUID(),
+ emailNormalized: '[email protected]',
+ name: 'Revoked',
+ reason: null,
+ status: 'revoked',
+ reviewedAt: new Date(),
+ reviewedBy: 'admin',
+ reviewNote: null,
+ approvedUserId: null
+ })
+ .execute()
+ const email = createTransactionalEmailService(runtime.database, {
+ encryptionSecret: 'regeneration-secret-at-least-32-characters',
+ })
+ const approval = await email.enqueue({
+ idempotencyKey: 'stale-approval',
+ kind: 'enrollment-approved',
+ recipientEmail: '[email protected]',
+ payload: { name: 'Revoked', actionURL: 'https://cloud.example.com' }
+ })
+ await expect(
+ createAdminEmailService(runtime.database, email, 'https://cloud.example.com').regenerate(
+ 'admin',
+ approval
+ )
+ ).rejects.toBeInstanceOf(AdminDomainError)
+ const queued = await runtime.database
+ .selectFrom('transactionalEmail')
+ .select('id')
+ .where('recipientEmailNormalized', '=', '[email protected]')
+ .execute()
+ expect(queued).toHaveLength(1)
+ } finally {
+ await runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/admin/enrollment/service.test.ts b/packages/cloud/tests/integration/admin/enrollment/service.test.ts
new file mode 100644
index 000000000..1740abe8d
--- /dev/null
+++ b/packages/cloud/tests/integration/admin/enrollment/service.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import {
+ createEnrollmentService,
+ createTransactionalEmailService,
+ PostgresRateLimitStore
+} from '#cloud/server'
+
+describe('Cloud enrollment integration', () => {
+ test('deduplicates requests and applies audited reviews', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const enrollment = createEnrollmentService(runtime.database)
+ await enrollment.request({ email: '[email protected]', name: 'Person', reason: 'Design' })
+ await enrollment.request({ email: '[email protected]', name: 'Duplicate' })
+ const [pending] = await enrollment.list('pending')
+ expect(pending).toMatchObject({
+ email: '[email protected]',
+ name: 'Person',
+ status: 'pending'
+ })
+ if (!pending) throw new Error('Expected pending enrollment')
+ await runtime.database
+ .insertInto('user')
+ .values({
+ id: '44444444-4444-4444-8444-444444444444',
+ name: 'Person',
+ email: '[email protected]',
+ emailVerified: true,
+ image: null,
+ role: 'user',
+ banned: false
+ })
+ .execute()
+ expect(
+ await enrollment.review('admin-user', pending.id, 'approved', { note: 'Early access' })
+ ).toMatchObject({
+ status: 'approved',
+ approvedUserId: '44444444-4444-4444-8444-444444444444',
+ reviewedBy: 'admin-user',
+ reviewNote: 'Early access'
+ })
+ expect(await enrollment.isApproved('[email protected]')).toBe(true)
+ expect(await enrollment.statusForEmail('[email protected]')).toBe('approved')
+ expect(
+ await runtime.database
+ .selectFrom('cloudAdminAuditEvent')
+ .select('action')
+ .executeTakeFirstOrThrow()
+ ).toEqual({ action: 'enrollment.approved' })
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('reopens rejected requests, enforces transitions, and enqueues review email', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const email = createTransactionalEmailService(runtime.database, {
+ encryptionSecret: 'enrollment-test-secret-at-least-32-characters',
+ })
+ const enrollment = createEnrollmentService(runtime.database, {
+ appURL: 'https://cloud.example.com',
+ adminRecipients: ['[email protected]'],
+ email
+ })
+ await enrollment.request({ email: '[email protected]', name: 'Person', reason: 'Design' })
+ let [record] = await enrollment.list()
+ if (!record) throw new Error('Expected enrollment')
+ expect(record.requestRevision).toBe(1)
+ expect(
+ await runtime.database
+ .selectFrom('transactionalEmail')
+ .select(({ fn }) => fn.countAll<number>().as('count'))
+ .executeTakeFirstOrThrow()
+ ).toEqual({ count: 2 })
+ await enrollment.review('admin-user', record.id, 'rejected', {})
+ await expect(enrollment.review('admin-user', record.id, 'revoked', {})).rejects.toThrow(
+ 'Enrollment cannot transition'
+ )
+ await enrollment.request({ email: '[email protected]', reason: 'Try again' })
+ ;[record] = await enrollment.list()
+ expect(record).toMatchObject({ status: 'pending', requestRevision: 2, reason: 'Try again' })
+ if (!record) throw new Error('Expected reopened enrollment')
+ await enrollment.review('admin-user', record.id, 'approved', {})
+ expect(
+ await runtime.database
+ .selectFrom('transactionalEmail')
+ .select(({ fn }) => fn.countAll<number>().as('count'))
+ .executeTakeFirstOrThrow()
+ ).toEqual({ count: 6 })
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('persists atomic rate limits without storing raw keys', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const store = new PostgresRateLimitStore(runtime.database, 'secret', 'enrollment-email', {
+ windowMs: 60_000
+ })
+ const results = await Promise.all(
+ Array.from({ length: 20 }, () => store.increment('[email protected]'))
+ )
+ expect(Math.max(...results.map((result) => result.totalHits))).toBe(20)
+ expect(
+ await runtime.database
+ .selectFrom('cloudRateLimit')
+ .select(['keyHash', 'requestCount'])
+ .executeTakeFirstOrThrow()
+ ).toMatchObject({
+ requestCount: 20,
+ keyHash: expect.not.stringContaining('[email protected]')
+ })
+ } finally {
+ await runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/admin/users/service.test.ts b/packages/cloud/tests/integration/admin/users/service.test.ts
new file mode 100644
index 000000000..d257f11b9
--- /dev/null
+++ b/packages/cloud/tests/integration/admin/users/service.test.ts
@@ -0,0 +1,135 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createAdminUserService } from '#cloud/server'
+
+const ADMIN_ID = '11111111-1111-4111-8111-111111111111'
+const USER_ID = '22222222-2222-4222-8222-222222222222'
+
+function complete(): Promise<void> {
+ return Promise.resolve()
+}
+
+function authAdapter() {
+ return {
+ schemaVersion: 'test',
+ async listUsers() {
+ return { users: [], total: 0 }
+ },
+ async banUser() {
+ return complete()
+ },
+ async unbanUser() {
+ return complete()
+ },
+ async revokeUserSessions() {
+ return complete()
+ },
+ async setRole() {
+ return complete()
+ },
+ async handler() {
+ return new Response()
+ },
+ async resolveIdentity() {
+ return null
+ },
+ async resolveSession() {
+ return null
+ },
+ async listAuthenticationMethods() {
+ return []
+ },
+ async changePassword() {
+ return complete()
+ },
+ async startSocialLink() {
+ return 'https://accounts.example.com/link'
+ },
+ async unlinkAuthenticationMethod() {
+ return complete()
+ },
+ async mfaStatus() {
+ return null
+ },
+ async enableTOTP() {
+ return { totpURI: '', backupCodes: [] }
+ },
+ async verifyTOTP() {
+ return undefined
+ },
+ async verifyRecoveryCode() {
+ return undefined
+ },
+ async generateRecoveryCodes() {
+ return []
+ },
+ async disableTOTP() {
+ return complete()
+ },
+ async listPasskeys() {
+ return []
+ },
+ async deletePasskey() {
+ return complete()
+ },
+ async migrate() {
+ return complete()
+ }
+ }
+}
+
+describe('deployment admin user safety', () => {
+ test('prevents self-ban and removal of the last administrator', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ await runtime.database
+ .insertInto('user')
+ .values([
+ {
+ id: ADMIN_ID,
+ name: 'Admin',
+ email: '[email protected]',
+ emailVerified: true,
+ image: null,
+ role: 'admin',
+ banned: false
+ },
+ {
+ id: USER_ID,
+ name: 'User',
+ email: '[email protected]',
+ emailVerified: true,
+ image: null,
+ role: 'user',
+ banned: false
+ }
+ ])
+ .execute()
+ const service = createAdminUserService(runtime.database, authAdapter())
+ await expect(service.ban(new Headers(), ADMIN_ID, ADMIN_ID)).rejects.toThrow(
+ 'cannot ban themselves'
+ )
+ await expect(service.setAdmin(new Headers(), 'other-admin', ADMIN_ID, false)).rejects.toThrow(
+ 'last deployment administrator'
+ )
+
+ const protectedService = createAdminUserService(runtime.database, authAdapter(), {
+ requireMFA: true
+ })
+ await expect(
+ protectedService.setAdmin(new Headers(), ADMIN_ID, USER_ID, true)
+ ).rejects.toThrow('enroll MFA')
+ await runtime.database
+ .updateTable('user')
+ .set({ twoFactorEnabled: true })
+ .where('id', '=', USER_ID)
+ .execute()
+ await expect(
+ protectedService.setAdmin(new Headers(), ADMIN_ID, USER_ID, true)
+ ).resolves.toBeUndefined()
+ } finally {
+ await runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/app.test.ts b/packages/cloud/tests/integration/server/app.test.ts
new file mode 100644
index 000000000..2d9d30efa
--- /dev/null
+++ b/packages/cloud/tests/integration/server/app.test.ts
@@ -0,0 +1,473 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { CLOUD_PROTOCOL_VERSION } from '#cloud/contract'
+import {
+ createCloudApp,
+ createBetterAuthAdapter,
+ createEnrollmentService,
+ parseCloudServerConfig,
+ type CloudDatabase
+} from '#cloud/server'
+import {
+ DummyDriver,
+ Kysely,
+ PostgresAdapter,
+ PostgresIntrospector,
+ PostgresQueryCompiler,
+ type CompiledQuery,
+ type DatabaseConnection,
+ type Dialect,
+ type QueryResult
+} from 'kysely'
+
+function dummyPostgresDialect(): Dialect {
+ return {
+ createAdapter: () => new PostgresAdapter(),
+ createDriver: () => new DummyDriver(),
+ createIntrospector: (database) => new PostgresIntrospector(database),
+ createQueryCompiler: () => new PostgresQueryCompiler()
+ }
+}
+
+const completed = Promise.resolve()
+const noOperation = () => completed
+
+function failingPostgresDialect(): Dialect {
+ const dialect = dummyPostgresDialect()
+ return {
+ ...dialect,
+ createDriver: () => ({
+ init: noOperation,
+ async acquireConnection(): Promise<DatabaseConnection> {
+ return {
+ executeQuery<R>(_query: CompiledQuery): Promise<QueryResult<R>> {
+ return Promise.reject(new Error('database unavailable'))
+ },
+ streamQuery<R>(): AsyncIterableIterator<QueryResult<R>> {
+ throw new Error('database unavailable')
+ }
+ }
+ },
+ beginTransaction: noOperation,
+ commitTransaction: noOperation,
+ rollbackTransaction: noOperation,
+ releaseConnection: noOperation,
+ destroy: noOperation
+ })
+ }
+}
+
+const config = parseCloudServerConfig({
+ deployment: 'self-hosted',
+ publicURL: 'https://pencil.example.com',
+ databaseURL: 'postgresql://openpencil:secret@database/openpencil',
+ authSecret: 'a-secure-auth-secret-with-at-least-32-characters',
+ googleClientId: 'google-client',
+ googleClientSecret: 'google-secret',
+ trustedOrigins: ['https://app.example.com'],
+ s3Endpoint: 'https://objects.example.com',
+ s3Region: 'us-east-1',
+ s3Bucket: 'openpencil',
+ s3AccessKeyId: 'access-key',
+ s3SecretAccessKey: 'secret-key'
+})
+
+function services() {
+ const database = new Kysely<CloudDatabase>({ dialect: dummyPostgresDialect() })
+ return {
+ config,
+ database,
+ auth: createBetterAuthAdapter(config, database),
+ objects: {
+ capabilities: {
+ nativeSHA256: true,
+ multipartUpload: false,
+ conditionalWrites: false
+ },
+ async checkReadiness() {
+ return { ok: true, checksumVerification: 'native' as const }
+ },
+ async createDownload() {
+ throw new Error('not used')
+ },
+ async createUpload() {
+ throw new Error('not used')
+ },
+ completeUpload: noOperation,
+ abortUpload: noOperation,
+ async head() {
+ return null
+ },
+ delete: noOperation
+ }
+ }
+}
+
+describe('createCloudApp', () => {
+ test('materializes enrollment from an authenticated identity and protects admin routes', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const approvalConfig = parseCloudServerConfig({ ...config, enrollmentMode: 'approval' })
+ const app = createCloudApp({
+ ...services(),
+ config: approvalConfig,
+ database: runtime.database,
+ auth: createBetterAuthAdapter(approvalConfig, runtime.database),
+ resolveIdentity: async () => ({
+ userId: 'pending-user',
+ email: '[email protected]',
+ name: 'Pending User'
+ })
+ })
+ expect((await app.request('/api/enrollment/request', { method: 'POST' })).status).toBe(401)
+ expect(await (await app.request('/api/account/status')).json()).toEqual({
+ user: {
+ userId: 'pending-user',
+ email: '[email protected]',
+ name: 'Pending User'
+ },
+ state: 'pending'
+ })
+ expect(
+ await runtime.database
+ .selectFrom('cloudEnrollment')
+ .select(['emailNormalized', 'status'])
+ .executeTakeFirstOrThrow()
+ ).toEqual({ emailNormalized: '[email protected]', status: 'pending' })
+ expect((await app.request('/api/admin/enrollments')).status).toBe(401)
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('requires MFA assurance only for deployment administration', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const enforcedConfig = parseCloudServerConfig({
+ ...config,
+ deploymentAdminMFARequired: true,
+ totpEnabled: true
+ })
+ const auth = createBetterAuthAdapter(enforcedConfig, runtime.database)
+ const app = createCloudApp({
+ ...services(),
+ config: enforcedConfig,
+ database: runtime.database,
+ auth,
+ resolveSession: async () => ({
+ userId: 'admin-user',
+ email: '[email protected]',
+ name: 'Admin',
+ deploymentRole: 'admin'
+ })
+ })
+ expect((await app.request('/api/session')).status).toBe(200)
+ expect((await app.request('/api/admin/operations')).status).toBe(403)
+ expect(await (await app.request('/api/admin/operations')).json()).toEqual({
+ error: { code: 'mfa_required' }
+ })
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('allows only deployment administrators to use admin routes', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const adminApp = createCloudApp({
+ ...services(),
+ database: runtime.database,
+ auth: createBetterAuthAdapter(config, runtime.database),
+ resolveSession: async () => ({
+ userId: 'admin-user',
+ email: '[email protected]',
+ name: 'Admin',
+ deploymentRole: 'admin'
+ })
+ })
+ const userApp = createCloudApp({
+ ...services(),
+ database: runtime.database,
+ auth: createBetterAuthAdapter(config, runtime.database),
+ resolveSession: async () => ({
+ userId: 'ordinary-user',
+ email: '[email protected]',
+ name: 'User',
+ deploymentRole: 'user'
+ })
+ })
+ expect(
+ (
+ await userApp.request('/api/admin/operations', {
+ headers: { Origin: 'https://pencil.example.com' }
+ })
+ ).status
+ ).toBe(403)
+ expect(
+ (
+ await adminApp.request('/api/admin/enrollments/missing/approve', {
+ method: 'POST',
+ headers: {
+ Origin: 'https://untrusted.example.com',
+ 'Content-Type': 'application/json'
+ },
+ body: '{}'
+ })
+ ).status
+ ).toBe(403)
+ const response = await adminApp.request('/api/admin/operations')
+ expect(response.status).toBe(200)
+ expect(await response.json()).toMatchObject({
+ enrollmentMode: 'open',
+ pendingEnrollment: 0
+ })
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('answers malformed admin input and unknown IDs with client errors', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const adminApp = createCloudApp({
+ ...services(),
+ database: runtime.database,
+ auth: createBetterAuthAdapter(config, runtime.database),
+ resolveSession: async () => ({
+ userId: 'admin-user',
+ email: '[email protected]',
+ name: 'Admin',
+ deploymentRole: 'admin'
+ })
+ })
+ for (const path of [
+ '/api/admin/audit?limit=many',
+ '/api/admin/email?limit=-1',
+ '/api/admin/users?offset=1.5',
+ '/api/admin/enrollments?status=sideways'
+ ]) {
+ const response = await adminApp.request(path)
+ expect(response.status).toBe(400)
+ expect(await response.json()).toEqual({ error: { code: 'invalid_request' } })
+ }
+ const review = await adminApp.request(
+ `/api/admin/enrollments/${crypto.randomUUID()}/approve`,
+ {
+ method: 'POST',
+ headers: { Origin: 'https://pencil.example.com', 'Content-Type': 'application/json' },
+ body: '{}'
+ }
+ )
+ expect(review.status).toBe(404)
+ expect(await review.json()).toEqual({ error: { code: 'not_found' } })
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('exposes restricted account state without authorizing product APIs', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const approvalConfig = parseCloudServerConfig({ ...config, enrollmentMode: 'approval' })
+ const pendingIdentity = {
+ userId: 'pending-user',
+ email: '[email protected]',
+ name: 'Pending User',
+ deploymentRole: 'user' as const
+ }
+ const app = createCloudApp({
+ ...services(),
+ config: approvalConfig,
+ database: runtime.database,
+ auth: createBetterAuthAdapter(approvalConfig, runtime.database),
+ resolveIdentity: async () => pendingIdentity,
+ resolveSession: async () => null
+ })
+ await createEnrollmentService(runtime.database).request({
+ email: pendingIdentity.email,
+ name: pendingIdentity.name
+ })
+
+ expect(await (await app.request('/api/account/status')).json()).toEqual({
+ user: pendingIdentity,
+ state: 'pending'
+ })
+ expect((await app.request('/api/session')).status).toBe(401)
+ expect((await app.request('/api/admin/enrollments')).status).toBe(401)
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('keeps Better Auth routes outside the OpenPencil rate limiter', async () => {
+ const runtime = await createCloudTestDatabase()
+ let authCalls = 0
+ try {
+ const base = services()
+ const app = createCloudApp({
+ ...base,
+ database: runtime.database,
+ auth: {
+ ...base.auth,
+ async handler() {
+ authCalls++
+ return Response.json({ ok: true })
+ }
+ }
+ })
+ for (let index = 0; index < 8; index++) {
+ expect((await app.request('/api/auth/test', { method: 'POST' })).status).toBe(200)
+ }
+ expect(authCalls).toBe(8)
+ expect(
+ await runtime.database
+ .selectFrom('cloudRateLimit')
+ .select(({ fn }) => fn.countAll<number>().as('count'))
+ .executeTakeFirstOrThrow()
+ ).toEqual({ count: 0 })
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('serves indexing policy through robots and response headers', async () => {
+ const denied = createCloudApp(services())
+ const robots = await denied.request('/robots.txt')
+ expect(await robots.text()).toBe('User-agent: *\nDisallow: /\n')
+ expect((await denied.request('/health')).headers.get('X-Robots-Tag')).toBe(
+ 'noindex, nofollow, noarchive'
+ )
+
+ const allowedServices = services()
+ allowedServices.config = { ...allowedServices.config, indexingPolicy: 'allow' }
+ const allowed = createCloudApp(allowedServices)
+ expect(await (await allowed.request('/robots.txt')).text()).toContain('Disallow: /admin')
+ expect((await allowed.request('/health')).headers.get('X-Robots-Tag')).toBeNull()
+ expect((await allowed.request('/api/session')).headers.get('X-Robots-Tag')).toBe(
+ 'noindex, nofollow, noarchive'
+ )
+ })
+
+ test('serves a health response without starting a listener', async () => {
+ const response = await createCloudApp(services()).request('/health')
+
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({
+ status: 'ok',
+ protocolVersion: CLOUD_PROTOCOL_VERSION
+ })
+ })
+
+ test('derives discovery from validated server capabilities', async () => {
+ const response = await createCloudApp(services()).request('/.well-known/openpencil')
+
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({
+ protocolVersion: CLOUD_PROTOCOL_VERSION,
+ deployment: 'self-hosted',
+ apiURL: 'https://pencil.example.com/api',
+ authURL: 'https://pencil.example.com/api/auth',
+ appURL: 'https://pencil.example.com',
+ authentication: {
+ socialProviders: ['google'],
+ enterpriseSSO: false,
+ enrollmentMode: 'open'
+ },
+ capabilities: {
+ documents: true,
+ workspaces: true,
+ collaboration: true
+ }
+ })
+ })
+
+ test('allows credentialed CORS for trusted origins only', async () => {
+ const cloud = createCloudApp(services())
+ const trustedDiscovery = await cloud.request('/.well-known/openpencil', {
+ headers: { Origin: 'https://app.example.com' }
+ })
+ expect(trustedDiscovery.headers.get('access-control-allow-origin')).toBe(
+ 'https://app.example.com'
+ )
+
+ const trusted = await createCloudApp(services()).request('/api/session', {
+ method: 'OPTIONS',
+ headers: {
+ Origin: 'https://app.example.com',
+ 'Access-Control-Request-Method': 'GET',
+ 'Access-Control-Request-Headers': 'authorization'
+ }
+ })
+ expect(trusted.status).toBe(204)
+ expect(trusted.headers.get('access-control-allow-origin')).toBe('https://app.example.com')
+ expect(trusted.headers.get('access-control-allow-credentials')).toBe('true')
+ // Editors signed in with a device code send its token as a bearer header.
+ expect(trusted.headers.get('access-control-allow-headers')).toContain('Authorization')
+
+ const untrusted = await createCloudApp(services()).request('/api/session', {
+ method: 'OPTIONS',
+ headers: {
+ Origin: 'https://malicious.example.com',
+ 'Access-Control-Request-Method': 'GET'
+ }
+ })
+ expect(untrusted.headers.get('access-control-allow-origin')).toBeNull()
+ })
+
+ test('reports object storage capabilities when ready', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const available = services()
+ available.database = runtime.database
+ const response = await createCloudApp(available).request('/ready')
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({
+ status: 'ready',
+ objectStorage: { checksumVerification: 'native', multipartUpload: false }
+ })
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('reports unavailable readiness when the database cannot execute', async () => {
+ const unavailable = services()
+ unavailable.database = new Kysely<CloudDatabase>({ dialect: failingPostgresDialect() })
+ const response = await createCloudApp(unavailable).request('/ready')
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ status: 'unavailable' })
+ })
+
+ test('limits guest collaboration tickets on their own budget', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const proxied = parseCloudServerConfig({
+ ...config,
+ authTrustedIPHeaders: ['x-forwarded-for']
+ })
+ const app = createCloudApp({
+ ...services(),
+ config: proxied,
+ database: runtime.database,
+ auth: createBetterAuthAdapter(proxied, runtime.database)
+ })
+ const shareId = crypto.randomUUID()
+ const headers = { 'content-type': 'application/json', 'x-forwarded-for': '203.0.113.7' }
+ const ticket = await app.request(`/api/shares/${shareId}/collaboration-ticket`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({ secret: 'a'.repeat(64) })
+ })
+ const share = await app.request(`/api/shares/${shareId}`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({ secret: 'a'.repeat(64) })
+ })
+ expect(ticket.headers.get('ratelimit-policy')).toContain('60;w=60')
+ expect(share.headers.get('ratelimit-policy')).toContain('30;w=60')
+ } finally {
+ await runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/auth/account-methods.test.ts b/packages/cloud/tests/integration/server/auth/account-methods.test.ts
new file mode 100644
index 000000000..5504688e7
--- /dev/null
+++ b/packages/cloud/tests/integration/server/auth/account-methods.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ accountAuthenticationRequest,
+ createAccountAuthenticationFixture,
+ createVerifiedCredentialAccount
+} from '#cloud-tests/helpers/account-authentication'
+import { cloudAuthenticationMethodsResponseSchema } from '#cloud/contract'
+import * as v from 'valibot'
+
+describe('account authentication methods', () => {
+ test('lists and unlinks methods while preserving another sign-in method', async () => {
+ const fixture = await createAccountAuthenticationFixture()
+ try {
+ const account = await createVerifiedCredentialAccount(fixture, {
+ email: '[email protected]',
+ name: 'Active Person',
+ password: 'the original long password',
+ approved: true
+ })
+ await fixture.database
+ .insertInto('account')
+ .values({
+ id: crypto.randomUUID(),
+ userId: account.userId,
+ providerId: 'google',
+ accountId: 'google-account',
+ createdAt: new Date(),
+ updatedAt: new Date()
+ })
+ .execute()
+ const response = await fixture.app.fetch(
+ accountAuthenticationRequest(
+ '/api/account/authentication',
+ undefined,
+ account.sessionCookie
+ )
+ )
+ const body = v.parse(cloudAuthenticationMethodsResponseSchema, await response.json())
+ expect(body.methods).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ provider: 'credential', canUnlink: true }),
+ expect.objectContaining({ provider: 'google', canUnlink: true })
+ ])
+ )
+ expect(body.availableSocialProviders).toEqual([])
+ const google = body.methods.find((method) => method.provider === 'google')
+ if (!google) throw new Error('Expected a linked Google method')
+ expect(
+ (
+ await fixture.app.fetch(
+ accountAuthenticationRequest(
+ '/api/account/authentication/unlink',
+ { methodId: google.id },
+ account.sessionCookie
+ )
+ )
+ ).status
+ ).toBe(200)
+ } finally {
+ await fixture.close()
+ }
+ })
+
+ test('blocks restricted identities and protects the final sign-in method', async () => {
+ const fixture = await createAccountAuthenticationFixture()
+ try {
+ const account = await createVerifiedCredentialAccount(fixture, {
+ email: '[email protected]',
+ name: 'Person',
+ password: 'a sufficiently long password',
+ approved: false
+ })
+ expect(
+ (
+ await fixture.app.fetch(
+ accountAuthenticationRequest(
+ '/api/account/authentication',
+ undefined,
+ account.sessionCookie
+ )
+ )
+ ).status
+ ).toBe(401)
+ expect(
+ (
+ await fixture.app.fetch(
+ accountAuthenticationRequest(
+ '/api/auth/list-accounts',
+ undefined,
+ account.sessionCookie
+ )
+ )
+ ).status
+ ).toBe(401)
+
+ await fixture.database
+ .insertInto('cloudEnrollment')
+ .values({
+ id: crypto.randomUUID(),
+ emailNormalized: '[email protected]',
+ name: 'Person',
+ reason: null,
+ status: 'approved',
+ reviewedAt: new Date(),
+ reviewedBy: 'admin',
+ reviewNote: null,
+ approvedUserId: account.userId
+ })
+ .execute()
+ const methodsResponse = await fixture.app.fetch(
+ accountAuthenticationRequest(
+ '/api/account/authentication',
+ undefined,
+ account.sessionCookie
+ )
+ )
+ const methods = v.parse(
+ cloudAuthenticationMethodsResponseSchema,
+ await methodsResponse.json()
+ )
+ expect(methods.methods).toHaveLength(1)
+ expect(methods.methods[0]).toMatchObject({ provider: 'credential', canUnlink: false })
+ const method = methods.methods[0]
+ if (!method) throw new Error('Expected a credential method')
+ expect(
+ (
+ await fixture.app.fetch(
+ accountAuthenticationRequest(
+ '/api/account/authentication/unlink',
+ { methodId: method.id },
+ account.sessionCookie
+ )
+ )
+ ).status
+ ).toBe(400)
+ } finally {
+ await fixture.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/auth/device-authorization.test.ts b/packages/cloud/tests/integration/server/auth/device-authorization.test.ts
new file mode 100644
index 000000000..2dd1c1550
--- /dev/null
+++ b/packages/cloud/tests/integration/server/auth/device-authorization.test.ts
@@ -0,0 +1,116 @@
+import { expect, test } from 'bun:test'
+
+import {
+ accountAuthenticationConfig,
+ accountAuthenticationRequest,
+ createAccountAuthenticationFixture,
+ createVerifiedCredentialAccount
+} from '#cloud-tests/helpers/account-authentication'
+import { responseJSON } from '#cloud-tests/helpers/response'
+import { signOutFromCloud } from '#cloud/client'
+import { parseCloudDiscovery } from '#cloud/contract'
+import * as v from 'valibot'
+
+test('email-only desktop authorization stays on its issuing instance with a separate editor', async () => {
+ const fixture = await createAccountAuthenticationFixture({
+ config: {
+ ...accountAuthenticationConfig,
+ appURL: 'https://editor.example.com',
+ trustedOrigins: ['https://editor.example.com']
+ }
+ })
+ try {
+ const clientId = 'openpencil-desktop:test-connection'
+ const issued = await fixture.app.fetch(
+ accountAuthenticationRequest('/api/auth/device/code', {
+ client_id: clientId,
+ scope: 'openid profile'
+ })
+ )
+ expect(issued.status).toBe(200)
+ const authorization = await responseJSON(
+ issued,
+ v.object({
+ user_code: v.string(),
+ device_code: v.string(),
+ verification_uri: v.string(),
+ verification_uri_complete: v.string()
+ })
+ )
+ expect(authorization.verification_uri).toBe('https://cloud.example.com/cloud/device')
+ expect(new URL(authorization.verification_uri_complete).origin).toBe(
+ 'https://cloud.example.com'
+ )
+ const user = await createVerifiedCredentialAccount(fixture, {
+ email: '[email protected]',
+ name: 'Desktop user',
+ password: 'desktop-password-long-enough',
+ approved: true
+ })
+ const inspected = await fixture.app.fetch(
+ accountAuthenticationRequest(
+ `/api/auth/device?user_code=${authorization.user_code}`,
+ undefined,
+ user.sessionCookie
+ )
+ )
+ expect(inspected.status).toBe(200)
+ const approved = await fixture.app.fetch(
+ accountAuthenticationRequest(
+ '/api/auth/device/approve',
+ { userCode: authorization.user_code },
+ user.sessionCookie
+ )
+ )
+ expect({ status: approved.status, body: await approved.json() }).toMatchObject({ status: 200 })
+ const token = await fixture.app.fetch(
+ accountAuthenticationRequest('/api/auth/device/token', {
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
+ device_code: authorization.device_code,
+ client_id: clientId
+ })
+ )
+ expect(token.status).toBe(200)
+ const tokenBody = await responseJSON(
+ token,
+ v.object({ access_token: v.string(), token_type: v.string() })
+ )
+ expect(tokenBody.token_type).toBe('Bearer')
+ expect(typeof tokenBody.access_token).toBe('string')
+ const stored = await fixture.database
+ .selectFrom('session')
+ .select(['userId', 'expiresAt'])
+ .where('token', '=', tokenBody.access_token)
+ .executeTakeFirst()
+ expect(stored?.userId).toBe(user.userId)
+ expect(new Date(stored?.expiresAt ?? 0).getTime()).toBeGreaterThan(Date.now())
+ const discoveryResponse = await fixture.app.fetch(
+ accountAuthenticationRequest('/.well-known/openpencil')
+ )
+ const discovery = parseCloudDiscovery(await discoveryResponse.json())
+ const session = await fixture.app.fetch(
+ new Request('https://cloud.example.com/api/session', {
+ headers: { Authorization: `Bearer ${tokenBody.access_token}` }
+ })
+ )
+ expect(session.status).toBe(200)
+ const invalid = await fixture.app.fetch(
+ new Request('https://cloud.example.com/api/session', {
+ headers: { Authorization: `Bearer ${crypto.randomUUID()}` }
+ })
+ )
+ expect(invalid.status).toBe(401)
+ await signOutFromCloud(discovery, {
+ accessToken: tokenBody.access_token,
+ fetch: async (input, init) => fixture.app.fetch(new Request(input, init))
+ })
+ const revoked = await fixture.app.fetch(
+ new Request('https://cloud.example.com/api/session', {
+ headers: { Authorization: `Bearer ${tokenBody.access_token}` }
+ })
+ )
+ expect(revoked.status).toBe(401)
+ } finally {
+ await fixture.close()
+ }
+})
diff --git a/packages/cloud/tests/integration/server/auth/email-outbox.test.ts b/packages/cloud/tests/integration/server/auth/email-outbox.test.ts
new file mode 100644
index 000000000..272cf6255
--- /dev/null
+++ b/packages/cloud/tests/integration/server/auth/email-outbox.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createAuthenticationEmailService, createTransactionalEmailService } from '#cloud/server'
+
+describe('authentication email outbox', () => {
+ test('enqueues verification, reset, and password-change messages without storing raw tokens', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const email = createTransactionalEmailService(runtime.database, {
+ encryptionSecret: 'authentication-email-test-secret-at-least-32-characters',
+ })
+ const service = createAuthenticationEmailService(email, 'https://cloud.example.com')
+ await service.sendVerification({
+ email: '[email protected]',
+ name: 'Person',
+ token: 'verification-token',
+ url: 'https://cloud.example.com/api/auth/verify-email?token=verification-token'
+ })
+ await service.sendPasswordReset({
+ email: '[email protected]',
+ name: 'Person',
+ token: 'reset-token',
+ url: 'https://cloud.example.com/api/auth/reset-password/reset-token'
+ })
+ await service.sendPasswordChanged({
+ email: '[email protected]',
+ name: 'Person',
+ userId: '11111111-1111-4111-8111-111111111111',
+ url: 'https://cloud.example.com'
+ })
+ const messages = await runtime.database
+ .selectFrom('transactionalEmail')
+ .select(['kind', 'idempotencyKey', 'payloadEncrypted'])
+ .orderBy('createdAt')
+ .execute()
+ expect(messages.map((message) => message.kind)).toEqual([
+ 'email-verification',
+ 'password-reset',
+ 'password-changed'
+ ])
+ expect(JSON.stringify(messages)).not.toContain('verification-token')
+ expect(JSON.stringify(messages)).not.toContain('reset-token')
+ expect(messages.every((message) => Boolean(message.payloadEncrypted))).toBe(true)
+ } finally {
+ await runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/auth/email-password.test.ts b/packages/cloud/tests/integration/server/auth/email-password.test.ts
new file mode 100644
index 000000000..ad06df03c
--- /dev/null
+++ b/packages/cloud/tests/integration/server/auth/email-password.test.ts
@@ -0,0 +1,293 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import {
+ createAuthenticationEmailService,
+ createBetterAuthAdapter,
+ createEnrollmentService,
+ createTransactionalEmailService,
+ parseCloudServerConfig,
+ type AuthenticationEmailService
+} from '#cloud/server'
+import * as v from 'valibot'
+
+const config = parseCloudServerConfig({
+ deployment: 'self-hosted',
+ publicURL: 'https://cloud.example.com',
+ databaseURL: 'postgresql://test:test@localhost/test',
+ authSecret: 'email-password-test-secret-at-least-32-characters',
+ enrollmentMode: 'approval',
+ emailPasswordEnabled: true,
+ emailPasswordMinimumLength: 15,
+ emailTransport: 'smtp',
+ emailFrom: '[email protected]',
+ smtpHost: 'smtp.example.com',
+ smtpPort: 465,
+ smtpSecure: true,
+ s3Endpoint: 'https://objects.example.com',
+ s3Region: 'us-east-1',
+ s3Bucket: 'openpencil',
+ s3AccessKeyId: 'access-key',
+ s3SecretAccessKey: 'secret-key'
+})
+
+async function runtime(authenticationEmail?: AuthenticationEmailService) {
+ const databaseRuntime = await createCloudTestDatabase()
+ const email = createTransactionalEmailService(databaseRuntime.database, {
+ encryptionSecret: config.authSecret,
+ from: config.emailFrom ?? ''
+ })
+ const enrollment = createEnrollmentService(databaseRuntime.database, {
+ appURL: config.publicURL,
+ adminRecipients: [],
+ email
+ })
+ const auth = createBetterAuthAdapter(config, databaseRuntime.database, enrollment, {
+ email: authenticationEmail ?? createAuthenticationEmailService(email, config.publicURL)
+ })
+ return { ...databaseRuntime, auth, enrollment }
+}
+
+function authRequest(path: string, body: object): Request {
+ return new Request(new URL(`/api/auth${path}`, config.publicURL), {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', Origin: config.publicURL },
+ body: JSON.stringify(body)
+ })
+}
+
+async function ignoreAuthenticationEmail(): Promise<void> {
+ await Promise.resolve()
+}
+
+function sessionHeaders(response: Response): Headers {
+ const setCookie = response.headers.get('set-cookie')
+ const cookie = setCookie?.split(';', 1)[0]
+ if (!cookie) throw new Error('Authentication response did not set a session cookie')
+ return new Headers({ Cookie: cookie })
+}
+
+describe('email and password authentication', () => {
+ test('enrolls credential accounts only after email verification', async () => {
+ let verificationURL = ''
+ const app = await runtime({
+ async sendVerification(input) {
+ verificationURL = input.url
+ },
+ sendPasswordReset: ignoreAuthenticationEmail,
+ sendPasswordChanged: ignoreAuthenticationEmail
+ })
+ try {
+ const response = await app.auth.handler(
+ authRequest('/sign-up/email', {
+ name: 'Person',
+ email: '[email protected]',
+ password: 'a sufficiently long password',
+ callbackURL: 'https://cloud.example.com/auth/verify-email?state=verified'
+ })
+ )
+ expect(response.status).toBe(200)
+ expect(await response.json()).toMatchObject({ token: null })
+ expect(await app.enrollment.statusForEmail('[email protected]')).toBeNull()
+ expect(
+ await app.database
+ .selectFrom('user')
+ .select(['email', 'emailVerified'])
+ .where('email', '=', '[email protected]')
+ .executeTakeFirstOrThrow()
+ ).toEqual({ email: '[email protected]', emailVerified: false })
+ expect(verificationURL).toContain('/api/auth/verify-email?token=')
+ expect(
+ await app.database
+ .selectFrom('transactionalEmail')
+ .select(({ fn }) => fn.countAll<number>().as('count'))
+ .executeTakeFirstOrThrow()
+ ).toEqual({ count: 0 })
+
+ const verification = await app.auth.handler(new Request(verificationURL))
+ expect(verification.status).toBe(302)
+ expect(await app.enrollment.statusForEmail('[email protected]')).toBe('pending')
+ } finally {
+ await app.close()
+ }
+ })
+
+ test('signs in with a bearer token and turns away an unconfirmed email without mailing again', async () => {
+ const verificationURLs: string[] = []
+ const app = await runtime({
+ async sendVerification(input) {
+ verificationURLs.push(input.url)
+ },
+ sendPasswordReset: ignoreAuthenticationEmail,
+ sendPasswordChanged: ignoreAuthenticationEmail
+ })
+ const credentials = { email: '[email protected]', password: 'a sufficiently long password' }
+ try {
+ await app.auth.handler(authRequest('/sign-up/email', { ...credentials, name: 'Person' }))
+
+ const unconfirmed = await app.auth.handler(authRequest('/sign-in/email', credentials))
+ expect(unconfirmed.status).toBe(403)
+ expect(await unconfirmed.json()).toMatchObject({ code: 'EMAIL_NOT_VERIFIED' })
+ expect(verificationURLs).toHaveLength(1)
+
+ await app.auth.handler(new Request(verificationURLs[0] ?? ''))
+ const signedIn = await app.auth.handler(authRequest('/sign-in/email', credentials))
+ const { token } = v.parse(v.object({ token: v.string() }), await signedIn.json())
+ const session = await app.auth.handler(
+ new Request(new URL('/api/auth/get-session', config.publicURL), {
+ headers: { Authorization: `Bearer ${token}` }
+ })
+ )
+ expect(await session.json()).toMatchObject({ user: { email: '[email protected]' } })
+ } finally {
+ await app.close()
+ }
+ })
+
+ test('revokes existing sessions and notifies after a password reset', async () => {
+ let verificationURL = ''
+ let resetToken = ''
+ let passwordChanged = false
+ const app = await runtime({
+ async sendVerification(input) {
+ verificationURL = input.url
+ },
+ async sendPasswordReset(input) {
+ resetToken = input.token
+ },
+ async sendPasswordChanged() {
+ passwordChanged = true
+ }
+ })
+ try {
+ await app.auth.handler(
+ authRequest('/sign-up/email', {
+ name: 'Reset Person',
+ email: '[email protected]',
+ password: 'the original long password',
+ callbackURL: 'https://cloud.example.com/auth/verify-email?state=verified'
+ })
+ )
+ await app.auth.handler(new Request(verificationURL))
+ const signIn = await app.auth.handler(
+ authRequest('/sign-in/email', {
+ email: '[email protected]',
+ password: 'the original long password'
+ })
+ )
+ expect(signIn.status).toBe(200)
+ const headers = sessionHeaders(signIn)
+ expect(await app.auth.resolveIdentity(headers)).toMatchObject({
+ })
+
+ const request = await app.auth.handler(
+ authRequest('/request-password-reset', {
+ email: '[email protected]',
+ redirectTo: 'https://cloud.example.com/auth/reset-password'
+ })
+ )
+ expect(request.status).toBe(200)
+ expect(resetToken).not.toBe('')
+ const reset = await app.auth.handler(
+ authRequest('/reset-password', {
+ token: resetToken,
+ newPassword: 'the replacement long password'
+ })
+ )
+ expect(reset.status).toBe(200)
+ expect(passwordChanged).toBe(true)
+ expect(await app.auth.resolveIdentity(headers)).toBeNull()
+
+ const reusedToken = await app.auth.handler(
+ authRequest('/reset-password', {
+ token: resetToken,
+ newPassword: 'another sufficiently long password'
+ })
+ )
+ expect(reusedToken.status).toBe(400)
+ expect(await reusedToken.json()).toMatchObject({ code: 'INVALID_TOKEN' })
+ const newSignIn = await app.auth.handler(
+ authRequest('/sign-in/email', {
+ email: '[email protected]',
+ password: 'the replacement long password'
+ })
+ )
+ expect(newSignIn.status).toBe(200)
+ } finally {
+ await app.close()
+ }
+ })
+
+ test('returns an indistinguishable sign-up response for an existing email', async () => {
+ const app = await runtime({
+ sendVerification: ignoreAuthenticationEmail,
+ sendPasswordReset: ignoreAuthenticationEmail,
+ sendPasswordChanged: ignoreAuthenticationEmail
+ })
+ try {
+ const first = await app.auth.handler(
+ authRequest('/sign-up/email', {
+ name: 'Existing Person',
+ email: '[email protected]',
+ password: 'a sufficiently long password',
+ callbackURL: 'https://cloud.example.com/auth/verify-email?state=verified'
+ })
+ )
+ const duplicate = await app.auth.handler(
+ authRequest('/sign-up/email', {
+ name: 'Different Name',
+ email: '[email protected]',
+ password: 'another sufficiently long password',
+ callbackURL: 'https://cloud.example.com/auth/verify-email?state=verified'
+ })
+ )
+ expect(first.status).toBe(200)
+ expect(duplicate.status).toBe(200)
+ expect(await duplicate.json()).toMatchObject({
+ token: null,
+ user: { email: '[email protected]', emailVerified: false }
+ })
+ } finally {
+ await app.close()
+ }
+ })
+
+ test('returns the same credential error for unknown users and wrong passwords', async () => {
+ const app = await runtime()
+ try {
+ const unknown = await app.auth.handler(
+ authRequest('/sign-in/email', {
+ email: '[email protected]',
+ password: 'a sufficiently long password'
+ })
+ )
+ expect(unknown.status).toBe(401)
+ expect(await unknown.json()).toMatchObject({ code: 'INVALID_EMAIL_OR_PASSWORD' })
+ } finally {
+ await app.close()
+ }
+ })
+
+ test('returns an opaque password-reset result for unknown users', async () => {
+ const app = await runtime()
+ try {
+ const response = await app.auth.handler(
+ authRequest('/request-password-reset', {
+ email: '[email protected]',
+ redirectTo: 'https://cloud.example.com/auth/reset-password'
+ })
+ )
+ expect(response.status).toBe(200)
+ expect(await response.json()).toMatchObject({ status: true })
+ expect(
+ await app.database
+ .selectFrom('transactionalEmail')
+ .select(({ fn }) => fn.countAll<number>().as('count'))
+ .executeTakeFirstOrThrow()
+ ).toEqual({ count: 0 })
+ } finally {
+ await app.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/auth/mfa-assurance.test.ts b/packages/cloud/tests/integration/server/auth/mfa-assurance.test.ts
new file mode 100644
index 000000000..6970ff07a
--- /dev/null
+++ b/packages/cloud/tests/integration/server/auth/mfa-assurance.test.ts
@@ -0,0 +1,202 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ accountAuthenticationRequest,
+ authenticationCookie,
+ createAccountAuthenticationFixture,
+ createVerifiedCredentialAccount
+} from '#cloud-tests/helpers/account-authentication'
+import { responseJSON } from '#cloud-tests/helpers/response'
+import { parseCloudServerConfig } from '#cloud/server'
+import { base32 } from '@better-auth/utils/base32'
+import { createOTP } from '@better-auth/utils/otp'
+import { sql } from 'kysely'
+import * as v from 'valibot'
+
+const mfaConfig = parseCloudServerConfig({
+ deployment: 'self-hosted',
+ publicURL: 'https://cloud.example.com',
+ databaseURL: 'postgresql://test:test@localhost/test',
+ authSecret: 'mfa-assurance-test-secret-at-least-32-characters',
+ enrollmentMode: 'approval',
+ deploymentAdminMFARequired: true,
+ totpEnabled: true,
+ recoveryCodesEnabled: true,
+ emailPasswordEnabled: true,
+ emailTransport: 'smtp',
+ emailFrom: '[email protected]',
+ smtpHost: 'smtp.example.com',
+ smtpPort: 465,
+ smtpSecure: true,
+ s3Endpoint: 'https://objects.example.com',
+ s3Region: 'us-east-1',
+ s3Bucket: 'openpencil',
+ s3AccessKeyId: 'access-key',
+ s3SecretAccessKey: 'secret-key'
+})
+
+describe('deployment administrator MFA assurance', () => {
+ test('requires and records TOTP step-up before admin access', async () => {
+ const fixture = await createAccountAuthenticationFixture({ config: mfaConfig })
+ try {
+ const account = await createVerifiedCredentialAccount(fixture, {
+ email: '[email protected]',
+ name: 'Admin',
+ password: 'a sufficiently long password',
+ approved: true
+ })
+ await fixture.database
+ .updateTable('user')
+ .set({ role: 'admin' })
+ .where('id', '=', account.userId)
+ .execute()
+ const signIn = await fixture.app.fetch(
+ accountAuthenticationRequest('/api/auth/sign-in/email', {
+ email: '[email protected]',
+ password: 'a sufficiently long password'
+ })
+ )
+ const sessionCookie = authenticationCookie(signIn)
+ expect(
+ (
+ await fixture.app.fetch(
+ accountAuthenticationRequest('/api/admin/operations', undefined, sessionCookie)
+ )
+ ).status
+ ).toBe(403)
+
+ const enabled = await fixture.app.fetch(
+ accountAuthenticationRequest(
+ '/api/account/mfa/totp/enable',
+ { password: 'a sufficiently long password' },
+ sessionCookie
+ )
+ )
+ const setup = await responseJSON(enabled, v.object({ totpURI: v.string() }))
+ const secret = new URL(setup.totpURI).searchParams.get('secret')
+ if (!secret) throw new Error('Expected a TOTP secret')
+ const rawSecret = new TextDecoder().decode(base32.decode(secret))
+ const code = await createOTP(rawSecret).totp()
+ const verificationResponse = await fixture.app.fetch(
+ accountAuthenticationRequest('/api/account/mfa/totp/verify', { code }, sessionCookie)
+ )
+ expect(verificationResponse.status).toBe(200)
+ const setCookie = verificationResponse.headers.get('set-cookie')
+ if (!setCookie) throw new Error('Expected a verified MFA session cookie')
+ const cookieMatch = setCookie.match(/(?:^|,\s*)([^;,]*better-auth\.session_token=[^;]+)/)
+ const verifiedCookie = cookieMatch?.[1]
+ if (!verifiedCookie) throw new Error('Expected a verified MFA session cookie')
+ expect(
+ (
+ await fixture.app.fetch(
+ accountAuthenticationRequest('/api/admin/operations', undefined, verifiedCookie)
+ )
+ ).status
+ ).toBe(200)
+
+ expect(
+ (
+ await fixture.app.fetch(
+ accountAuthenticationRequest(
+ '/api/account/mfa/totp/disable',
+ { password: 'a sufficiently long password' },
+ verifiedCookie
+ )
+ )
+ ).status
+ ).toBe(403)
+ expect(
+ (
+ await fixture.app.fetch(
+ accountAuthenticationRequest(
+ '/api/auth/two-factor/disable',
+ { password: 'a sufficiently long password' },
+ verifiedCookie
+ )
+ )
+ ).status
+ ).toBe(403)
+ } finally {
+ await fixture.close()
+ }
+ })
+
+ test('keeps an administrator from deleting their last second factor', async () => {
+ const fixture = await createAccountAuthenticationFixture({ config: mfaConfig })
+ try {
+ const account = await createVerifiedCredentialAccount(fixture, {
+ email: '[email protected]',
+ name: 'Passkey Admin',
+ password: 'a sufficiently long password',
+ approved: true
+ })
+ await fixture.database
+ .updateTable('user')
+ .set({ role: 'admin' })
+ .where('id', '=', account.userId)
+ .execute()
+ const addPasskey = async (credential: string) => {
+ const id = crypto.randomUUID()
+ await sql`
+ insert into passkey (id, name, public_key, user_id, credential_id, counter, device_type, backed_up)
+ values (${id}, ${credential}, 'public-key', ${account.userId}, ${credential}, 0, 'singleDevice', false)
+ `.execute(fixture.database)
+ return id
+ }
+ const deletePasskey = (id: string) =>
+ fixture.app.fetch(
+ accountAuthenticationRequest(
+ '/api/account/mfa/passkeys/delete',
+ { id },
+ account.sessionCookie
+ )
+ )
+
+ const only = await addPasskey('only')
+ const refused = await deletePasskey(only)
+ expect(refused.status).toBe(403)
+ expect(await refused.json()).toEqual({ error: { code: 'mfa_required' } })
+
+ const spare = await addPasskey('spare')
+ expect((await deletePasskey(only)).status).toBe(200)
+ expect((await deletePasskey(spare)).status).toBe(403)
+ } finally {
+ await fixture.close()
+ }
+ })
+
+ test('refuses Better Auth admin endpoints outside the Cloud admin API', async () => {
+ const fixture = await createAccountAuthenticationFixture({ config: mfaConfig })
+ try {
+ const account = await createVerifiedCredentialAccount(fixture, {
+ email: '[email protected]',
+ name: 'Direct Admin',
+ password: 'a sufficiently long password',
+ approved: true
+ })
+ await fixture.database
+ .updateTable('user')
+ .set({ role: 'admin' })
+ .where('id', '=', account.userId)
+ .execute()
+ for (const path of ['/api/auth/admin/set-role', '/api/auth/admin/impersonate-user']) {
+ const response = await fixture.app.fetch(
+ accountAuthenticationRequest(
+ path,
+ { userId: account.userId, role: 'user' },
+ account.sessionCookie
+ )
+ )
+ expect(response.status).toBe(403)
+ }
+ const user = await fixture.database
+ .selectFrom('user')
+ .select('role')
+ .where('id', '=', account.userId)
+ .executeTakeFirstOrThrow()
+ expect(user.role).toBe('admin')
+ } finally {
+ await fixture.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/auth/password-change.test.ts b/packages/cloud/tests/integration/server/auth/password-change.test.ts
new file mode 100644
index 000000000..631b1bbaa
--- /dev/null
+++ b/packages/cloud/tests/integration/server/auth/password-change.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ accountAuthenticationRequest,
+ createAccountAuthenticationFixture,
+ createVerifiedCredentialAccount
+} from '#cloud-tests/helpers/account-authentication'
+
+describe('account password changes', () => {
+ test('changes the password, revokes other sessions, and sends a notification', async () => {
+ let passwordChanged = false
+ const fixture = await createAccountAuthenticationFixture({
+ onPasswordChanged() {
+ passwordChanged = true
+ }
+ })
+ try {
+ const account = await createVerifiedCredentialAccount(fixture, {
+ email: '[email protected]',
+ name: 'Password Person',
+ password: 'the original long password',
+ approved: true
+ })
+ await fixture.app.fetch(
+ accountAuthenticationRequest('/api/auth/sign-in/email', {
+ email: '[email protected]',
+ password: 'the original long password'
+ })
+ )
+ const before = await fixture.database
+ .selectFrom('session')
+ .select(({ fn }) => fn.countAll<number>().as('count'))
+ .where('userId', '=', account.userId)
+ .executeTakeFirstOrThrow()
+ expect(Number(before.count)).toBeGreaterThan(1)
+
+ const response = await fixture.app.fetch(
+ accountAuthenticationRequest(
+ '/api/account/authentication/change-password',
+ {
+ currentPassword: 'the original long password',
+ newPassword: 'the replacement long password'
+ },
+ account.sessionCookie
+ )
+ )
+ expect(response.status).toBe(200)
+ expect(passwordChanged).toBe(true)
+ const after = await fixture.database
+ .selectFrom('session')
+ .select(({ fn }) => fn.countAll<number>().as('count'))
+ .where('userId', '=', account.userId)
+ .executeTakeFirstOrThrow()
+ expect(Number(after.count)).toBe(1)
+ expect(
+ await fixture.app.fetch(
+ accountAuthenticationRequest('/api/account/status', undefined, account.sessionCookie)
+ )
+ ).toHaveProperty('status', 200)
+ } finally {
+ await fixture.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/cleanup/documents.test.ts b/packages/cloud/tests/integration/server/cleanup/documents.test.ts
new file mode 100644
index 000000000..f2dcc7915
--- /dev/null
+++ b/packages/cloud/tests/integration/server/cleanup/documents.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createMemoryObjectStore } from '#cloud-tests/helpers/objects'
+import { createDocumentCleanupService } from '#cloud/server'
+
+async function deletedDocument() {
+ const runtime = await createCloudTestDatabase()
+ const workspaceId = crypto.randomUUID()
+ const documentId = crypto.randomUUID()
+ const storageObjectId = crypto.randomUUID()
+ const revisionId = crypto.randomUUID()
+ const objectKey = `documents/${workspaceId}/${documentId}/revision.fig`
+ await runtime.database
+ .insertInto('workspace')
+ .values({
+ id: workspaceId,
+ name: 'Cleanup',
+ slug: `cleanup-${crypto.randomUUID()}`,
+ createdBy: 'alice'
+ })
+ .execute()
+ await runtime.database
+ .insertInto('document')
+ .values({ id: documentId, workspaceId, name: 'Deleted.fig', createdBy: 'alice' })
+ .execute()
+ await runtime.database
+ .insertInto('storageObject')
+ .values({
+ id: storageObjectId,
+ objectKey,
+ checksum: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',
+ byteSize: 128,
+ contentType: 'application/octet-stream'
+ })
+ .execute()
+ await runtime.database
+ .insertInto('documentRevision')
+ .values({
+ id: revisionId,
+ documentId,
+ parentRevisionId: null,
+ storageObjectId,
+ createdBy: 'alice'
+ })
+ .execute()
+ await runtime.database
+ .updateTable('document')
+ .set({ currentRevisionId: revisionId, deletedAt: new Date(Date.now() - 60_000) })
+ .where('id', '=', documentId)
+ .execute()
+ return { runtime, documentId, objectKey }
+}
+
+describe('document cleanup', () => {
+ test('retains recently deleted documents', async () => {
+ const context = await deletedDocument()
+ try {
+ const cleanup = createDocumentCleanupService(
+ context.runtime.database,
+ createMemoryObjectStore().store
+ )
+ expect(
+ await cleanup.cleanupDeletedDocuments({
+ batchSize: 10,
+ leaseDurationMs: 60_000,
+ retentionMs: 120_000
+ })
+ ).toEqual({ claimed: 0, cleaned: 0, failed: 0, objectsDeleted: 0, bytesReclaimed: 0 })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('removes retained revision objects and hard-deletes the document', async () => {
+ const context = await deletedDocument()
+ const objects = createMemoryObjectStore()
+ try {
+ const cleanup = createDocumentCleanupService(context.runtime.database, objects.store)
+ expect(
+ await cleanup.cleanupDeletedDocuments({
+ batchSize: 10,
+ leaseDurationMs: 60_000,
+ retentionMs: 0
+ })
+ ).toEqual({ claimed: 1, cleaned: 1, failed: 0, objectsDeleted: 1, bytesReclaimed: 128 })
+ expect(objects.deletedKeys).toEqual([context.objectKey])
+ expect(
+ await context.runtime.database
+ .selectFrom('document')
+ .select('id')
+ .where('id', '=', context.documentId)
+ .executeTakeFirst()
+ ).toBeUndefined()
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/cleanup/uploads.test.ts b/packages/cloud/tests/integration/server/cleanup/uploads.test.ts
new file mode 100644
index 000000000..caafade6a
--- /dev/null
+++ b/packages/cloud/tests/integration/server/cleanup/uploads.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createMemoryObjectStore } from '#cloud-tests/helpers/objects'
+import { createUploadCleanupService } from '#cloud/server'
+
+async function insertExpiredUploads(count: number, multipartUploadId: string | null = null) {
+ const runtime = await createCloudTestDatabase()
+ const workspaceId = crypto.randomUUID()
+ const documentId = crypto.randomUUID()
+ await runtime.database
+ .insertInto('workspace')
+ .values({
+ id: workspaceId,
+ name: 'Cleanup',
+ slug: `cleanup-${crypto.randomUUID()}`,
+ createdBy: 'alice'
+ })
+ .execute()
+ await runtime.database
+ .insertInto('document')
+ .values({ id: documentId, workspaceId, name: 'Cleanup.fig', createdBy: 'alice' })
+ .execute()
+ const uploads = Array.from({ length: count }, () => ({
+ id: crypto.randomUUID(),
+ documentId,
+ baseRevisionId: null,
+ objectKey: `cleanup/${crypto.randomUUID()}.fig`,
+ checksum: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',
+ byteSize: 1,
+ contentType: 'application/octet-stream',
+ multipartUploadId,
+ status: 'pending' as const,
+ finalizationStartedAt: null,
+ createdBy: 'alice',
+ expiresAt: new Date(Date.now() - 60_000)
+ }))
+ await runtime.database.insertInto('upload').values(uploads).execute()
+ return { runtime, uploads }
+}
+
+describe('upload cleanup', () => {
+ test('limits each cleanup batch', async () => {
+ const context = await insertExpiredUploads(3)
+ const objects = createMemoryObjectStore()
+ try {
+ const cleanup = createUploadCleanupService(context.runtime.database, objects.store)
+ expect(
+ await cleanup.cleanupExpiredUploads({ batchSize: 2, leaseDurationMs: 60_000 })
+ ).toEqual({
+ claimed: 2,
+ cleaned: 2,
+ failed: 0
+ })
+ expect(objects.deletedKeys).toHaveLength(2)
+ expect(
+ await context.runtime.database
+ .selectFrom('upload')
+ .select(({ fn }) => fn.countAll<number>().as('count'))
+ .where('status', '=', 'pending')
+ .executeTakeFirstOrThrow()
+ ).toEqual({ count: 1 })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('removes a completed multipart upload whose commit never landed', async () => {
+ const context = await insertExpiredUploads(1, 'multipart-upload')
+ const objects = createMemoryObjectStore()
+ try {
+ const cleanup = createUploadCleanupService(context.runtime.database, objects.store)
+ await cleanup.cleanupExpiredUploads({ batchSize: 10, leaseDurationMs: 60_000 })
+ expect(objects.deletedKeys).toEqual(context.uploads.map((upload) => upload.objectKey))
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('reclaims stale finalization leases', async () => {
+ const context = await insertExpiredUploads(1)
+ const objects = createMemoryObjectStore()
+ try {
+ await context.runtime.database
+ .updateTable('upload')
+ .set({
+ status: 'finalizing',
+ finalizationStartedAt: new Date(Date.now() - 120_000),
+ expiresAt: new Date(Date.now() + 60_000)
+ })
+ .execute()
+ const cleanup = createUploadCleanupService(context.runtime.database, objects.store)
+ expect(
+ await cleanup.cleanupExpiredUploads({ batchSize: 1, leaseDurationMs: 60_000 })
+ ).toEqual({ claimed: 1, cleaned: 1, failed: 0 })
+ expect(
+ await context.runtime.database
+ .selectFrom('upload')
+ .select('status')
+ .executeTakeFirstOrThrow()
+ ).toEqual({ status: 'abandoned' })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('reclaims stale cleanup leases', async () => {
+ const context = await insertExpiredUploads(1)
+ const objects = createMemoryObjectStore()
+ try {
+ await context.runtime.database
+ .updateTable('upload')
+ .set({
+ status: 'cleaning',
+ cleanupClaimId: crypto.randomUUID(),
+ cleanupClaimedAt: new Date(Date.now() - 120_000)
+ })
+ .execute()
+ const cleanup = createUploadCleanupService(context.runtime.database, objects.store)
+ expect(
+ await cleanup.cleanupExpiredUploads({ batchSize: 1, leaseDurationMs: 60_000 })
+ ).toEqual({
+ claimed: 1,
+ cleaned: 1,
+ failed: 0
+ })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/collaboration/service.test.ts b/packages/cloud/tests/integration/server/collaboration/service.test.ts
new file mode 100644
index 000000000..feb5788c2
--- /dev/null
+++ b/packages/cloud/tests/integration/server/collaboration/service.test.ts
@@ -0,0 +1,132 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createCollaborationTicketService, createDocumentSharingService } from '#cloud/server'
+import { decodeJwt } from 'jose'
+
+const authSecret = 'collaboration-test-secret-at-least-32-characters'
+
+async function seed() {
+ const runtime = await createCloudTestDatabase()
+ const workspaceId = crypto.randomUUID()
+ const documentId = crypto.randomUUID()
+ await runtime.database
+ .insertInto('workspace')
+ .values({ id: workspaceId, name: 'Design', slug: `design-${workspaceId}`, createdBy: 'owner' })
+ .execute()
+ await runtime.database
+ .insertInto('workspaceMember')
+ .values([
+ { workspaceId, userId: 'owner', role: 'admin' },
+ { workspaceId, userId: 'viewer', role: 'viewer' }
+ ])
+ .execute()
+ await runtime.database
+ .insertInto('document')
+ .values({ id: documentId, workspaceId, name: 'Homepage', createdBy: 'owner' })
+ .execute()
+ const sharing = createDocumentSharingService(runtime.database)
+ return {
+ runtime,
+ documentId,
+ sharing,
+ tickets: createCollaborationTicketService({
+ database: runtime.database,
+ sharing,
+ authSecret
+ })
+ }
+}
+
+describe('collaboration tickets', () => {
+ test('issues signed tickets from authenticated document permissions', async () => {
+ const context = await seed()
+ try {
+ const ticket = await context.tickets.issueUserTicket(
+ { userId: 'viewer', name: 'Viewer', email: '[email protected]' },
+ context.documentId
+ )
+ expect(ticket).toMatchObject({
+ documentId: context.documentId,
+ permission: 'view',
+ roomEpoch: 0,
+ serverEnforcedWrites: false,
+ principal: { kind: 'user', userId: 'viewer' }
+ })
+ expect(ticket.roomId).toBe(`cloud:${context.documentId}:0`)
+ expect(ticket.roomKey.length).toBeGreaterThanOrEqual(43)
+ expect(decodeJwt(ticket.token)).toMatchObject({
+ documentId: context.documentId,
+ permission: 'view',
+ serverEnforcedWrites: false
+ })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('binds guest tickets to capability permissions and rotated room epochs', async () => {
+ const context = await seed()
+ try {
+ const capability = await context.sharing.createShare('owner', context.documentId, {
+ permission: 'edit'
+ })
+ await context.runtime.database
+ .updateTable('document')
+ .set({ collaborationEpoch: capability.share.roomEpoch })
+ .where('id', '=', context.documentId)
+ .execute()
+ const rotated = await context.sharing.rotateShare(
+ 'owner',
+ context.documentId,
+ capability.share.id
+ )
+ const ticket = await context.tickets.issueShareTicket(capability.share.id, {
+ secret: rotated.secret,
+ guestName: 'Guest editor',
+ guestId: 'stable-guest-identity'
+ })
+ expect(ticket).toMatchObject({
+ permission: 'edit',
+ roomEpoch: 0,
+ roomId: `cloud:${context.documentId}:0`,
+ principal: {
+ kind: 'guest',
+ guestId: 'stable-guest-identity',
+ name: 'Guest editor'
+ },
+ serverEnforcedWrites: false
+ })
+ const ownerTicket = await context.tickets.issueUserTicket(
+ { userId: 'owner', name: 'Owner', email: '[email protected]' },
+ context.documentId
+ )
+ expect(ownerTicket).toMatchObject({
+ roomEpoch: 0,
+ roomId: `cloud:${context.documentId}:0`,
+ principal: { kind: 'user', userId: 'owner' }
+ })
+ const secondCapability = await context.sharing.createShare('owner', context.documentId, {
+ permission: 'view'
+ })
+ expect(secondCapability.share.roomEpoch).toBe(0)
+ const secondTicket = await context.tickets.issueShareTicket(secondCapability.share.id, {
+ secret: secondCapability.secret,
+ guestName: 'Guest viewer',
+ guestId: 'stable-guest-viewer'
+ })
+ expect(secondTicket).toMatchObject({ roomEpoch: 0, roomId: `cloud:${context.documentId}:0` })
+ await context.sharing.revokeShare('owner', context.documentId, secondCapability.share.id)
+ const afterRevocation = await context.tickets.issueUserTicket(
+ { userId: 'owner', name: 'Owner', email: '[email protected]' },
+ context.documentId
+ )
+ expect(afterRevocation).toMatchObject({
+ roomEpoch: 1,
+ roomId: `cloud:${context.documentId}:1`
+ })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/db/auth-schema.test.ts b/packages/cloud/tests/integration/server/db/auth-schema.test.ts
new file mode 100644
index 000000000..9c1eb45a5
--- /dev/null
+++ b/packages/cloud/tests/integration/server/db/auth-schema.test.ts
@@ -0,0 +1,220 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudDatabase, migrateCloudDatabase } from '#cloud/server'
+import { up as relaxAccountIssuer } from '#cloud/server/db/migrations/019_better_auth_account_issuer'
+import { PGlite } from '@electric-sql/pglite'
+import { CamelCasePlugin, Kysely, sql } from 'kysely'
+import { PGliteDialect } from 'kysely-pglite-dialect'
+
+async function testDatabase(pglite?: PGlite) {
+ const store = pglite ?? (await PGlite.create({ dataDir: 'memory://' }))
+ return createCloudDatabase({ dialect: new PGliteDialect(store) })
+}
+
+async function createRequiredAuthSchema(database: Awaited<ReturnType<typeof testDatabase>>) {
+ const tables: Array<[string, Array<[string, string]>]> = [
+ [
+ 'user',
+ [
+ ['id', 'uuid'],
+ ['name', 'text'],
+ ['email', 'text'],
+ ['email_verified', 'boolean'],
+ ['created_at', 'timestamptz'],
+ ['updated_at', 'timestamptz'],
+ ['role', 'text'],
+ ['banned', 'boolean'],
+ ['two_factor_enabled', 'boolean']
+ ]
+ ],
+ [
+ 'session',
+ [
+ ['id', 'uuid'],
+ ['expires_at', 'timestamptz'],
+ ['token', 'text'],
+ ['user_id', 'uuid'],
+ ['impersonated_by', 'text']
+ ]
+ ],
+ [
+ 'account',
+ [
+ ['id', 'uuid'],
+ ['account_id', 'text'],
+ ['provider_id', 'text'],
+ ['user_id', 'uuid']
+ ]
+ ],
+ [
+ 'verification',
+ [
+ ['id', 'text'],
+ ['identifier', 'text'],
+ ['value', 'text'],
+ ['expires_at', 'timestamptz']
+ ]
+ ],
+ [
+ 'device_code',
+ [
+ ['id', 'text'],
+ ['device_code', 'text'],
+ ['user_code', 'text'],
+ ['status', 'text'],
+ ['client_id', 'text']
+ ]
+ ],
+ [
+ 'two_factor',
+ [
+ ['id', 'uuid'],
+ ['secret', 'text'],
+ ['backup_codes', 'text'],
+ ['user_id', 'uuid'],
+ ['verified', 'boolean'],
+ ['failed_verification_count', 'integer'],
+ ['locked_until', 'timestamptz']
+ ]
+ ],
+ [
+ 'passkey',
+ [
+ ['id', 'uuid'],
+ ['public_key', 'text'],
+ ['user_id', 'uuid'],
+ ['credential_id', 'text'],
+ ['counter', 'integer'],
+ ['device_type', 'text'],
+ ['backed_up', 'boolean']
+ ]
+ ],
+ [
+ 'rate_limit',
+ [
+ ['id', 'text'],
+ ['key', 'text'],
+ ['count', 'integer'],
+ ['last_request', 'bigint']
+ ]
+ ]
+ ]
+ for (const [table, columns] of tables) {
+ let builder = database.schema.createTable(table)
+ for (const [column, type] of columns) {
+ builder = builder.addColumn(column, type as 'text' | 'uuid')
+ }
+ await builder.execute()
+ }
+}
+
+describe('Better Auth schema ledger', () => {
+ test('bootstraps an empty schema once and records its version', async () => {
+ const database = await testDatabase()
+ let runs = 0
+ const migration = {
+ schemaVersion: '1.7.7+mfa.1',
+ async run() {
+ runs++
+ await createRequiredAuthSchema(database)
+ }
+ }
+ try {
+ await migrateCloudDatabase(database, migration)
+ await migrateCloudDatabase(database, migration)
+ expect(runs).toBe(1)
+ expect(
+ await database.selectFrom('cloudAuthSchema').selectAll().executeTakeFirstOrThrow()
+ ).toMatchObject({ id: 'better-auth', version: '1.7.7+mfa.1' })
+ } finally {
+ await database.destroy()
+ }
+ })
+
+ test('adopts a complete pre-ledger schema without rerunning Better Auth', async () => {
+ const database = await testDatabase()
+ try {
+ await migrateCloudDatabase(database)
+ await createRequiredAuthSchema(database)
+ await migrateCloudDatabase(database, {
+ schemaVersion: '1.7.7+mfa.1',
+ run: () => {
+ throw new Error('Complete schemas must be adopted')
+ }
+ })
+ expect(
+ await database.selectFrom('cloudAuthSchema').select('version').executeTakeFirstOrThrow()
+ ).toEqual({ version: '1.7.7+mfa.1' })
+ } finally {
+ await database.destroy()
+ }
+ })
+
+ test('rejects partial and unreviewed upgraded schemas', async () => {
+ const database = await testDatabase()
+ try {
+ await migrateCloudDatabase(database)
+ await database.schema.createTable('user').addColumn('id', 'uuid').execute()
+ await expect(
+ migrateCloudDatabase(database, { schemaVersion: '1.7.2', run: async () => undefined })
+ ).rejects.toThrow('Existing Better Auth schema is incomplete')
+ await database
+ .insertInto('cloudAuthSchema')
+ .values({ id: 'better-auth', version: '1.7.2', updatedAt: new Date() })
+ .execute()
+ await expect(
+ migrateCloudDatabase(database, { schemaVersion: '1.8.0', run: async () => undefined })
+ ).rejects.toThrow('requires an explicit migration')
+ } finally {
+ await database.destroy()
+ }
+ })
+
+ test('lets a schema from Better Auth 1.7.2 create accounts without an issuer', async () => {
+ const pglite = await PGlite.create({ dataDir: 'memory://' })
+ const database = await testDatabase(pglite)
+ // Migrations run untyped, the way the migrator calls them, with the database's plugins.
+ const untyped = new Kysely<unknown>({
+ dialect: new PGliteDialect(pglite),
+ plugins: [new CamelCasePlugin()]
+ })
+ try {
+ await migrateCloudDatabase(database)
+ await database.schema
+ .createTable('account')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('issuer', 'text', (column) => column.notNull())
+ .addColumn('account_id', 'text', (column) => column.notNull())
+ .addColumn('provider_id', 'text', (column) => column.notNull())
+ .execute()
+ await database.schema
+ .createIndex('account_issuer_accountId_uidx')
+ .on('account')
+ .columns(['issuer', 'account_id'])
+ .unique()
+ .execute()
+ await database
+ .insertInto('cloudAuthSchema')
+ .values({ id: 'better-auth', version: '1.7.2+mfa.1', updatedAt: new Date() })
+ .execute()
+
+ await relaxAccountIssuer(untyped)
+
+ expect(
+ await database.selectFrom('cloudAuthSchema').select('version').executeTakeFirstOrThrow()
+ ).toEqual({ version: '1.7.7+mfa.1' })
+ const account = (await database.introspection.getTables()).find(
+ (table) => table.name === 'account'
+ )
+ expect(account?.columns.find((column) => column.name === 'issuer')?.isNullable).toBe(true)
+ const indexes = await sql<{ indexname: string }>`
+ select indexname from pg_indexes where tablename = 'account'
+ `.execute(database)
+ expect(indexes.rows.map((row) => row.indexname)).not.toContain(
+ 'account_issuer_accountId_uidx'
+ )
+ } finally {
+ await database.destroy()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/db/database.test.ts b/packages/cloud/tests/integration/server/db/database.test.ts
new file mode 100644
index 000000000..f6ed69d79
--- /dev/null
+++ b/packages/cloud/tests/integration/server/db/database.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createCloudDatabase } from '#cloud/server'
+import {
+ DummyDriver,
+ PostgresAdapter,
+ PostgresIntrospector,
+ PostgresQueryCompiler,
+ sql,
+ type Dialect
+} from 'kysely'
+
+function testDialect(): Dialect {
+ return {
+ createAdapter: () => new PostgresAdapter(),
+ createDriver: () => new DummyDriver(),
+ createIntrospector: (database) => new PostgresIntrospector(database),
+ createQueryCompiler: () => new PostgresQueryCompiler()
+ }
+}
+
+function testDatabase() {
+ return createCloudDatabase({ dialect: testDialect() })
+}
+
+describe('Cloud database', () => {
+ test('stamps timestamp defaults when a row is written, not when the migration ran', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const fixed = await sql<{ table: string; column: string; fallback: string }>`
+ select table_name as "table", column_name as "column", column_default as fallback
+ from information_schema.columns
+ where table_schema = 'public' and data_type like 'timestamp%' and column_default like '''%'
+ `.execute(runtime.database)
+ expect(fixed.rows).toEqual([])
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('runs migrations and application queries in embedded PostgreSQL', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const workspaceId = crypto.randomUUID()
+ await runtime.database
+ .insertInto('workspace')
+ .values({
+ id: workspaceId,
+ name: 'Test workspace',
+ slug: `test-${workspaceId}`,
+ createdBy: 'user-1'
+ })
+ .execute()
+ await runtime.database
+ .insertInto('workspaceMember')
+ .values({ workspaceId, userId: 'user-1', role: 'admin' })
+ .execute()
+
+ const workspace = await runtime.database
+ .selectFrom('workspace')
+ .innerJoin('workspaceMember', 'workspaceMember.workspaceId', 'workspace.id')
+ .select(['workspace.id', 'workspace.name', 'workspaceMember.role'])
+ .where('workspaceMember.userId', '=', 'user-1')
+ .executeTakeFirstOrThrow()
+
+ expect(workspace).toMatchObject({
+ id: workspaceId,
+ name: 'Test workspace',
+ role: 'admin'
+ })
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('uses camel-case application fields with snake-case SQL identifiers', () => {
+ const database = testDatabase()
+ const query = database
+ .selectFrom('workspaceMember')
+ .select(['workspaceId', 'userId'])
+ .where('userId', '=', 'user-1')
+ .compile()
+
+ expect(query.sql).toBe(
+ 'select "workspace_id", "user_id" from "workspace_member" where "user_id" = $1'
+ )
+ expect(query.parameters).toEqual(['user-1'])
+ })
+
+ test('compiles immutable revision insertion against PostgreSQL', () => {
+ const database = testDatabase()
+ const query = database
+ .insertInto('documentRevision')
+ .values({
+ id: '01900000-0000-7000-8000-000000000001',
+ documentId: '01900000-0000-7000-8000-000000000002',
+ parentRevisionId: null,
+ storageObjectId: '01900000-0000-7000-8000-000000000003',
+ createdBy: 'user-1'
+ })
+ .compile()
+
+ expect(query.sql).toContain('insert into "document_revision"')
+ expect(query.sql).toContain('"storage_object_id"')
+ })
+})
diff --git a/packages/cloud/tests/integration/server/documents/access.test.ts b/packages/cloud/tests/integration/server/documents/access.test.ts
new file mode 100644
index 000000000..069b98c2b
--- /dev/null
+++ b/packages/cloud/tests/integration/server/documents/access.test.ts
@@ -0,0 +1,148 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createMemoryObjectStore } from '#cloud-tests/helpers/objects'
+import { createDocumentService, DocumentForbiddenError, resolveDocumentAccess } from '#cloud/server'
+
+async function seedDocument() {
+ const runtime = await createCloudTestDatabase()
+ const workspaceId = crypto.randomUUID()
+ const documentId = crypto.randomUUID()
+ await runtime.database
+ .insertInto('workspace')
+ .values({ id: workspaceId, name: 'Design', slug: `design-${workspaceId}`, createdBy: 'owner' })
+ .execute()
+ await runtime.database
+ .insertInto('workspaceMember')
+ .values([
+ { workspaceId, userId: 'owner', role: 'admin' },
+ { workspaceId, userId: 'editor', role: 'editor' },
+ { workspaceId, userId: 'viewer', role: 'viewer' },
+ { workspaceId, userId: 'promoted', role: 'viewer' }
+ ])
+ .execute()
+ await runtime.database
+ .insertInto('document')
+ .values({ id: documentId, workspaceId, name: 'Homepage', createdBy: 'owner' })
+ .execute()
+ return { runtime, documentId }
+}
+
+describe('document access resolution', () => {
+ test('combines owner, workspace, and direct grant sources using strongest access', async () => {
+ const context = await seedDocument()
+ try {
+ await context.runtime.database
+ .insertInto('documentGrant')
+ .values({
+ id: crypto.randomUUID(),
+ documentId: context.documentId,
+ userId: 'promoted',
+ permission: 'edit',
+ createdBy: 'owner'
+ })
+ .execute()
+
+ expect(
+ await resolveDocumentAccess(context.runtime.database, 'owner', context.documentId)
+ ).toEqual({
+ permission: 'edit',
+ canManageSharing: true,
+ sources: ['owner', 'workspace']
+ })
+ expect(
+ await resolveDocumentAccess(context.runtime.database, 'viewer', context.documentId)
+ ).toEqual({
+ permission: 'view',
+ canManageSharing: false,
+ sources: ['workspace']
+ })
+ expect(
+ await resolveDocumentAccess(context.runtime.database, 'promoted', context.documentId)
+ ).toEqual({
+ permission: 'edit',
+ canManageSharing: true,
+ sources: ['workspace', 'direct-grant']
+ })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('supports direct grants outside a workspace and ignores revoked grants', async () => {
+ const context = await seedDocument()
+ try {
+ const grantId = crypto.randomUUID()
+ await context.runtime.database
+ .insertInto('documentGrant')
+ .values({
+ id: grantId,
+ documentId: context.documentId,
+ userId: 'guest-user',
+ permission: 'view',
+ createdBy: 'owner'
+ })
+ .execute()
+ expect(
+ await resolveDocumentAccess(context.runtime.database, 'guest-user', context.documentId)
+ ).toMatchObject({
+ permission: 'view',
+ sources: ['direct-grant']
+ })
+
+ await context.runtime.database
+ .updateTable('documentGrant')
+ .set({ revokedAt: new Date() })
+ .where('id', '=', grantId)
+ .execute()
+ expect(
+ await resolveDocumentAccess(context.runtime.database, 'guest-user', context.documentId)
+ ).toBeUndefined()
+ expect(
+ await resolveDocumentAccess(context.runtime.database, 'stranger', context.documentId)
+ ).toBeUndefined()
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('lets only the owner and workspace admins and editors delete a document', async () => {
+ const context = await seedDocument()
+ try {
+ await context.runtime.database
+ .insertInto('documentGrant')
+ .values([
+ {
+ id: crypto.randomUUID(),
+ documentId: context.documentId,
+ userId: 'promoted',
+ permission: 'edit',
+ createdBy: 'owner'
+ },
+ {
+ id: crypto.randomUUID(),
+ documentId: context.documentId,
+ userId: 'invited',
+ permission: 'edit',
+ createdBy: 'owner'
+ }
+ ])
+ .execute()
+ const documents = createDocumentService(
+ context.runtime.database,
+ createMemoryObjectStore().store
+ )
+ for (const userId of ['promoted', 'invited', 'viewer']) {
+ await expect(documents.remove(userId, context.documentId)).rejects.toBeInstanceOf(
+ DocumentForbiddenError
+ )
+ }
+ await documents.remove('editor', context.documentId)
+ expect(
+ await resolveDocumentAccess(context.runtime.database, 'owner', context.documentId)
+ ).toBeUndefined()
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/documents/routes.test.ts b/packages/cloud/tests/integration/server/documents/routes.test.ts
new file mode 100644
index 000000000..7c5adce47
--- /dev/null
+++ b/packages/cloud/tests/integration/server/documents/routes.test.ts
@@ -0,0 +1,414 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createMemoryObjectStore } from '#cloud-tests/helpers/objects'
+import { responseJSON } from '#cloud-tests/helpers/response'
+import {
+ createCloudApp,
+ createBetterAuthAdapter,
+ createDocumentService,
+ parseCloudServerConfig,
+ type CloudActor
+} from '#cloud/server'
+import * as v from 'valibot'
+
+const config = parseCloudServerConfig({
+ deployment: 'self-hosted',
+ publicURL: 'http://localhost:8787',
+ databaseURL: 'postgresql://test:test@localhost/test',
+ authSecret: 'integration-test-secret-at-least-32-characters',
+ s3Endpoint: 'http://localhost:9000',
+ s3Region: 'us-east-1',
+ s3Bucket: 'openpencil',
+ s3AccessKeyId: 'openpencil',
+ s3SecretAccessKey: 'openpencil-secret'
+})
+
+const actor: CloudActor = {
+ userId: 'alice',
+ email: '[email protected]',
+ name: 'Alice'
+}
+const checksum = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='
+
+async function testApp(initialActor: CloudActor = actor) {
+ let currentActor = initialActor
+ const runtime = await createCloudTestDatabase()
+ const objects = createMemoryObjectStore()
+ const app = createCloudApp({
+ config,
+ database: runtime.database,
+ auth: createBetterAuthAdapter(config, runtime.database),
+ objects: objects.store,
+ resolveSession: async () => currentActor
+ })
+ const workspaceResponse = await app.request('/api/workspaces', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'Documents', slug: 'documents-team' })
+ })
+ const workspace = await responseJSON(
+ workspaceResponse,
+ v.object({ workspace: v.object({ id: v.string() }) })
+ )
+ return {
+ runtime,
+ objects,
+ app,
+ workspaceId: workspace.workspace.id,
+ setActor: (value: CloudActor) => {
+ currentActor = value
+ }
+ }
+}
+
+describe('Cloud document routes', () => {
+ test('creates and lists document metadata', async () => {
+ const context = await testApp()
+ try {
+ const create = await context.app.request(`/api/workspaces/${context.workspaceId}/documents`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'Homepage' })
+ })
+ expect(create.status).toBe(201)
+ const created = await responseJSON(
+ create,
+ v.object({ document: v.object({ id: v.string(), version: v.number() }) })
+ )
+ expect(created.document.version).toBe(0)
+
+ const list = await context.app.request(`/api/workspaces/${context.workspaceId}/documents`)
+ expect(list.status).toBe(200)
+ expect(await list.json()).toMatchObject({
+ documents: [{ id: created.document.id, name: 'Homepage', currentRevisionId: null }]
+ })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test.each([false, true])(
+ 'commits immutable revisions with direct grant: %s',
+ async (directGrant) => {
+ const context = await testApp()
+ try {
+ const create = await context.app.request(
+ `/api/workspaces/${context.workspaceId}/documents`,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'Homepage' })
+ }
+ )
+ const document = await responseJSON(
+ create,
+ v.object({ document: v.object({ id: v.string() }) })
+ )
+ if (directGrant) {
+ const grant = await context.app.request(
+ `/api/documents/${document.document.id}/grants/bob`,
+ {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ permission: 'edit' })
+ }
+ )
+ expect(grant.status).toBe(200)
+ context.setActor({ userId: 'bob', email: '[email protected]', name: 'Bob' })
+ const listing = await context.app.request(
+ `/api/workspaces/${context.workspaceId}/documents`
+ )
+ expect(listing.status).toBe(404)
+ }
+ const uploadResponse = await context.app.request(
+ `/api/documents/${document.document.id}/uploads`,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ baseRevisionId: null,
+ byteSize: 128,
+ checksum,
+ contentType: 'application/octet-stream'
+ })
+ }
+ )
+ expect(uploadResponse.status).toBe(201)
+
+ const upload = await responseJSON(
+ uploadResponse,
+ v.object({
+ id: v.string(),
+ upload: v.object({
+ kind: v.string(),
+ url: v.string(),
+ headers: v.record(v.string(), v.string())
+ })
+ })
+ )
+ const uploadRow = await context.runtime.database
+ .selectFrom('upload')
+ .select('objectKey')
+ .where('id', '=', upload.id)
+ .executeTakeFirstOrThrow()
+ context.objects.put(uploadRow.objectKey, {
+ byteSize: 128,
+ checksum,
+ checksumVerification: 'native',
+ contentType: 'application/octet-stream'
+ })
+
+ const commit = await context.app.request(`/api/uploads/${upload.id}/commit`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ checksum })
+ })
+ expect(commit.status).toBe(200)
+ const committed = await responseJSON(
+ commit,
+ v.object({ document: v.object({ currentRevisionId: v.string(), version: v.number() }) })
+ )
+ expect(committed.document.currentRevisionId).toBeString()
+ expect(committed.document.version).toBe(1)
+
+ const repeatedCommit = await context.app.request(`/api/uploads/${upload.id}/commit`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ checksum })
+ })
+ expect(repeatedCommit.status).toBe(200)
+ expect(await repeatedCommit.json()).toMatchObject({
+ document: {
+ currentRevisionId: committed.document.currentRevisionId,
+ version: 1
+ }
+ })
+
+ context.setActor(actor)
+ const usageResponse = await context.app.request(
+ `/api/workspaces/${context.workspaceId}/usage`
+ )
+ expect(usageResponse.status).toBe(200)
+ expect(await usageResponse.json()).toEqual({
+ usage: { bytesUsed: 128, objectCount: 1, documentCount: 1 }
+ })
+
+ const downloadResponse = await context.app.request(`/api/documents/${document.document.id}`)
+ expect(downloadResponse.status).toBe(200)
+ expect(await downloadResponse.json()).toMatchObject({
+ document: {
+ document: { id: document.document.id, version: 1 },
+ revisionId: committed.document.currentRevisionId,
+ byteSize: 128,
+ checksum,
+ download: { method: 'GET' }
+ }
+ })
+
+ const revision = await context.runtime.database
+ .selectFrom('documentRevision')
+ .select(['parentRevisionId'])
+ .executeTakeFirstOrThrow()
+ expect(revision.parentRevisionId).toBeNull()
+ } finally {
+ await context.runtime.close()
+ }
+ }
+ )
+
+ test('abandons and deletes expired pending uploads', async () => {
+ const context = await testApp()
+ try {
+ const create = await context.app.request(`/api/workspaces/${context.workspaceId}/documents`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'Homepage' })
+ })
+ const document = await responseJSON(
+ create,
+ v.object({ document: v.object({ id: v.string() }) })
+ )
+ const uploadResponse = await context.app.request(
+ `/api/documents/${document.document.id}/uploads`,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ baseRevisionId: null,
+ byteSize: 128,
+ checksum,
+ contentType: 'application/octet-stream'
+ })
+ }
+ )
+ const upload = await responseJSON(uploadResponse, v.object({ id: v.string() }))
+ const row = await context.runtime.database
+ .selectFrom('upload')
+ .select('objectKey')
+ .where('id', '=', upload.id)
+ .executeTakeFirstOrThrow()
+ const service = createDocumentService(context.runtime.database, context.objects.store)
+ expect(await service.cleanupExpiredUploads(new Date(Date.now() + 16 * 60 * 1000))).toBe(1)
+ expect(context.objects.deletedKeys).toEqual([row.objectKey])
+ expect(
+ await context.runtime.database
+ .selectFrom('upload')
+ .select('status')
+ .where('id', '=', upload.id)
+ .executeTakeFirstOrThrow()
+ ).toEqual({ status: 'abandoned' })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('rejects stale base revisions and unverified uploads', async () => {
+ const context = await testApp()
+ try {
+ const create = await context.app.request(`/api/workspaces/${context.workspaceId}/documents`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'Homepage' })
+ })
+ const document = await responseJSON(
+ create,
+ v.object({ document: v.object({ id: v.string() }) })
+ )
+ const stale = await context.app.request(`/api/documents/${document.document.id}/uploads`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ baseRevisionId: crypto.randomUUID(),
+ byteSize: 128,
+ checksum,
+ contentType: 'application/octet-stream'
+ })
+ })
+ expect(stale.status).toBe(409)
+
+ const pending = await context.app.request(`/api/documents/${document.document.id}/uploads`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ baseRevisionId: null,
+ byteSize: 128,
+ checksum,
+ contentType: 'application/octet-stream'
+ })
+ })
+ const upload = await responseJSON(pending, v.object({ id: v.string() }))
+ const commit = await context.app.request(`/api/uploads/${upload.id}/commit`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ checksum })
+ })
+ expect(commit.status).toBe(422)
+ expect(await commit.json()).toEqual({ error: { code: 'invalid_upload' } })
+ expect(
+ await context.runtime.database
+ .selectFrom('upload')
+ .select('status')
+ .where('id', '=', upload.id)
+ .executeTakeFirstOrThrow()
+ ).toEqual({ status: 'pending' })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
+
+describe('documents shared with a person', () => {
+ const bob: CloudActor = { userId: 'bob', email: '[email protected]', name: 'Bob' }
+ const SharedDocuments = v.object({
+ documents: v.array(
+ v.object({
+ id: v.string(),
+ name: v.string(),
+ workspaceName: v.string(),
+ permission: v.string(),
+ sharedBy: v.nullable(v.object({ name: v.string() }))
+ })
+ )
+ })
+
+ test('lists direct grants outside the person’s workspaces until they are revoked', async () => {
+ const aliceAccount = crypto.randomUUID()
+ const context = await testApp({ ...actor, userId: aliceAccount })
+ try {
+ const now = new Date()
+ await context.runtime.database
+ .insertInto('user')
+ .values({
+ id: aliceAccount,
+ name: 'Alice',
+ email: '[email protected]',
+ emailVerified: true,
+ image: null,
+ banExpires: null,
+ createdAt: now,
+ updatedAt: now
+ })
+ .execute()
+ const create = await context.app.request(`/api/workspaces/${context.workspaceId}/documents`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'Brief' })
+ })
+ const created = await responseJSON(
+ create,
+ v.object({ document: v.object({ id: v.string() }) })
+ )
+ const documentId = created.document.id
+ const grant = await context.app.request(`/api/documents/${documentId}/grants/bob`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ permission: 'view' })
+ })
+ expect(grant.status).toBe(200)
+
+ context.setActor(bob)
+ const shared = await responseJSON(
+ await context.app.request('/api/shared-documents'),
+ SharedDocuments
+ )
+ expect(shared.documents).toEqual([
+ {
+ id: documentId,
+ name: 'Brief',
+ workspaceName: 'Documents',
+ permission: 'view',
+ sharedBy: { name: 'Alice' }
+ }
+ ])
+
+ await context.runtime.database
+ .insertInto('workspaceMember')
+ .values({ workspaceId: context.workspaceId, userId: 'bob', role: 'viewer' })
+ .execute()
+ const asMember = await responseJSON(
+ await context.app.request('/api/shared-documents'),
+ SharedDocuments
+ )
+ expect(asMember.documents).toEqual([])
+
+ await context.runtime.database
+ .deleteFrom('workspaceMember')
+ .where('userId', '=', 'bob')
+ .execute()
+ context.setActor({ ...actor, userId: aliceAccount })
+ const revoke = await context.app.request(`/api/documents/${documentId}/grants/bob`, {
+ method: 'DELETE'
+ })
+ expect(revoke.status).toBeLessThan(300)
+ context.setActor(bob)
+ const afterRevoke = await responseJSON(
+ await context.app.request('/api/shared-documents'),
+ SharedDocuments
+ )
+ expect(afterRevoke.documents).toEqual([])
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/email/service.test.ts b/packages/cloud/tests/integration/server/email/service.test.ts
new file mode 100644
index 000000000..d7b8f06b5
--- /dev/null
+++ b/packages/cloud/tests/integration/server/email/service.test.ts
@@ -0,0 +1,148 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createTransactionalEmailService, TransactionalEmailTransportError } from '#cloud/server'
+
+const secret = 'transactional-email-test-secret-at-least-32-characters'
+const invitation = {
+ inviterName: 'Alice',
+ documentName: 'Homepage',
+ permission: 'view' as const,
+ expiresAt: '2026-01-08T00:00:00.000Z',
+ acceptanceURL: 'https://app.example.com/cloud/invitations/id#secret-token'
+}
+
+describe('transactional email outbox', () => {
+ test('encrypts payloads and deduplicates logical messages', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const email = createTransactionalEmailService(runtime.database, {
+ encryptionSecret: secret,
+ from: 'OpenPencil <[email protected]>'
+ })
+ const input = {
+ idempotencyKey: 'document-invitation/invitation-id',
+ kind: 'document-invitation' as const,
+ recipientEmail: '[email protected]',
+ payload: invitation
+ }
+ const first = await email.enqueue(input)
+ expect(await email.enqueue(input)).toBe(first)
+ const rows = await runtime.database.selectFrom('transactionalEmail').selectAll().execute()
+ expect(rows).toHaveLength(1)
+ expect(rows[0]?.recipientEmailNormalized).toBe('[email protected]')
+ const encryptedPayload = rows[0]?.payloadEncrypted
+ if (!encryptedPayload) throw new Error('Expected an encrypted transactional email payload')
+ expect(encryptedPayload).not.toContain('secret-token')
+ expect(encryptedPayload.split('.')).toHaveLength(5)
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('claims, renders, and records transport acceptance', async () => {
+ const runtime = await createCloudTestDatabase()
+ const sent: unknown[] = []
+ try {
+ const email = createTransactionalEmailService(runtime.database, {
+ encryptionSecret: secret,
+ from: 'OpenPencil <[email protected]>',
+ transport: {
+ id: 'memory',
+ async send(message) {
+ sent.push(message)
+ return { transportMessageId: 'message-id', acceptedAt: '2026-01-01T00:00:00.000Z' }
+ }
+ }
+ })
+ await email.enqueue({
+ idempotencyKey: 'document-invitation/accepted',
+ kind: 'document-invitation',
+ recipientEmail: '[email protected]',
+ payload: invitation
+ })
+ expect(await email.deliverPending({ batchSize: 10, leaseDurationMs: 60_000 })).toEqual({
+ claimed: 1,
+ accepted: 1,
+ retrying: 0,
+ failed: 0,
+ suppressed: 0
+ })
+ expect(sent).toHaveLength(1)
+ expect(sent[0]).toMatchObject({
+ subject: 'Alice invited you to view Homepage'
+ })
+ expect(
+ await runtime.database
+ .selectFrom('transactionalEmail')
+ .select(['status', 'attemptCount', 'transport', 'transportMessageId', 'payloadEncrypted'])
+ .executeTakeFirstOrThrow()
+ ).toMatchObject({
+ status: 'accepted',
+ attemptCount: 1,
+ transport: 'memory',
+ transportMessageId: 'message-id',
+ payloadEncrypted: null
+ })
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('retries transient failures and terminates suppressed recipients', async () => {
+ const runtime = await createCloudTestDatabase()
+ let suppressed = false
+ try {
+ const email = createTransactionalEmailService(runtime.database, {
+ encryptionSecret: secret,
+ from: 'OpenPencil <[email protected]>',
+ transport: {
+ id: 'memory',
+ async send() {
+ throw new TransactionalEmailTransportError(
+ suppressed ? 'suppressed' : 'transient',
+ suppressed ? 'suppressed' : 'temporary',
+ 'Rejected'
+ )
+ }
+ }
+ })
+ await email.enqueue({
+ idempotencyKey: 'document-invitation/retry',
+ kind: 'document-invitation',
+ recipientEmail: '[email protected]',
+ payload: invitation
+ })
+ const now = new Date(Date.now() + 1000)
+ expect(await email.deliverPending({ batchSize: 1, leaseDurationMs: 60_000, now })).toEqual({
+ claimed: 1,
+ accepted: 0,
+ retrying: 1,
+ failed: 0,
+ suppressed: 0
+ })
+ suppressed = true
+ expect(
+ await email.deliverPending({
+ batchSize: 1,
+ leaseDurationMs: 60_000,
+ now: new Date(now.getTime() + 60_000)
+ })
+ ).toEqual({ claimed: 1, accepted: 0, retrying: 0, failed: 0, suppressed: 1 })
+ expect(
+ await runtime.database
+ .selectFrom('transactionalEmail')
+ .select(['status', 'attemptCount', 'lastErrorCode', 'payloadEncrypted'])
+ .executeTakeFirstOrThrow()
+ ).toEqual({
+ status: 'suppressed',
+ attemptCount: 2,
+ lastErrorCode: 'suppressed',
+ payloadEncrypted: null
+ })
+ } finally {
+ await runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/policy/database.test.ts b/packages/cloud/tests/integration/server/policy/database.test.ts
new file mode 100644
index 000000000..3fcc51c01
--- /dev/null
+++ b/packages/cloud/tests/integration/server/policy/database.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createWorkspaceEntitlementRepository, DatabaseEntitlementSource } from '#cloud/server'
+
+async function seed() {
+ const runtime = await createCloudTestDatabase()
+ const workspaceId = crypto.randomUUID()
+ await runtime.database
+ .insertInto('workspace')
+ .values({ id: workspaceId, name: 'W', slug: `w-${workspaceId}`, createdBy: 'u' })
+ .execute()
+ return { runtime, workspaceId }
+}
+
+describe('database entitlement source', () => {
+ test('stores structured values with revisions and resolves canonical keys', async () => {
+ const context = await seed()
+ try {
+ const repository = createWorkspaceEntitlementRepository(context.runtime.database)
+ await repository.set(
+ context.workspaceId,
+ {
+ documents: { maximumFileBytes: 100 },
+ sharing: { anonymousEdit: false },
+ storage: {},
+ collaboration: {}
+ },
+ 'test'
+ )
+ await repository.set(
+ context.workspaceId,
+ {
+ documents: { maximumFileBytes: 200 },
+ sharing: { anonymousEdit: true },
+ storage: {},
+ collaboration: {}
+ },
+ 'test'
+ )
+ expect(await repository.get(context.workspaceId)).toMatchObject({
+ revision: 2,
+ source: 'test'
+ })
+ const source = new DatabaseEntitlementSource(context.runtime.database)
+ const subject = { type: 'workspace' as const, id: context.workspaceId }
+ expect(await source.number(subject, 'cloud.documents.maximum-file-bytes')).toBe(200)
+ expect(await source.boolean(subject, 'cloud.sharing.anonymous-edit')).toBe(true)
+ expect(await source.boolean(subject, 'unknown')).toBeNull()
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/policy/service.test.ts b/packages/cloud/tests/integration/server/policy/service.test.ts
new file mode 100644
index 000000000..4f52a6a1a
--- /dev/null
+++ b/packages/cloud/tests/integration/server/policy/service.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import {
+ CLOUD_FEATURE_KEYS,
+ createDefaultCloudPolicy,
+ createEntitlementService,
+ EntitlementOpenFeatureProvider,
+ StaticEntitlementSource
+} from '#cloud/server'
+
+async function workspaceLimits(participants: number, technicalMaximumParticipants: number) {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const workspaceId = crypto.randomUUID()
+ await runtime.database
+ .insertInto('workspace')
+ .values({ id: workspaceId, name: 'W', slug: `w-${workspaceId}`, createdBy: 'owner' })
+ .execute()
+ await runtime.database
+ .insertInto('workspaceMember')
+ .values({ workspaceId, userId: 'owner', role: 'admin' })
+ .execute()
+ const policy = createDefaultCloudPolicy(
+ new EntitlementOpenFeatureProvider(
+ new StaticEntitlementSource({ [CLOUD_FEATURE_KEYS.maximumParticipants]: participants })
+ )
+ )
+ const service = createEntitlementService(
+ runtime.database,
+ policy,
+ 1_000_000,
+ technicalMaximumParticipants
+ )
+ return (await service.workspace('owner', workspaceId)).limits
+ } finally {
+ await runtime.close()
+ }
+}
+
+describe('workspace entitlements', () => {
+ test('never report more participants than a room accepts', async () => {
+ expect((await workspaceLimits(5000, 1000)).maximumParticipants).toBe(1000)
+ expect((await workspaceLimits(10, 1000)).maximumParticipants).toBe(10)
+ })
+})
diff --git a/packages/cloud/tests/integration/server/quota/reconcile.test.ts b/packages/cloud/tests/integration/server/quota/reconcile.test.ts
new file mode 100644
index 000000000..f370861ad
--- /dev/null
+++ b/packages/cloud/tests/integration/server/quota/reconcile.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createStorageReconciliationService } from '#cloud/server'
+
+async function seed() {
+ const runtime = await createCloudTestDatabase()
+ const workspaceId = crypto.randomUUID()
+ const documentId = crypto.randomUUID()
+ const objectId = crypto.randomUUID()
+ await runtime.database
+ .insertInto('workspace')
+ .values({ id: workspaceId, name: 'W', slug: `w-${workspaceId}`, createdBy: 'u' })
+ .execute()
+ await runtime.database
+ .insertInto('document')
+ .values({ id: documentId, workspaceId, name: 'D', createdBy: 'u' })
+ .execute()
+ await runtime.database
+ .insertInto('storageObject')
+ .values({
+ id: objectId,
+ objectKey: 'object',
+ checksum: 'sum',
+ byteSize: 128,
+ contentType: 'application/octet-stream'
+ })
+ .execute()
+ await runtime.database
+ .insertInto('documentRevision')
+ .values({
+ id: crypto.randomUUID(),
+ documentId,
+ parentRevisionId: null,
+ storageObjectId: objectId,
+ createdBy: 'u'
+ })
+ .execute()
+ return { runtime, workspaceId }
+}
+
+describe('storage reconciliation', () => {
+ test('reports and repairs committed-byte drift', async () => {
+ const context = await seed()
+ try {
+ const service = createStorageReconciliationService(context.runtime.database)
+ expect(await service.reconcile({ dryRun: true })).toEqual([
+ {
+ workspaceId: context.workspaceId,
+ recordedBytes: 0,
+ calculatedBytes: 128,
+ corrected: true
+ }
+ ])
+ await service.reconcile({ dryRun: false })
+ expect(
+ await context.runtime.database
+ .selectFrom('workspaceStorageUsage')
+ .select('committedBytes')
+ .where('workspaceId', '=', context.workspaceId)
+ .executeTakeFirst()
+ ).toEqual({ committedBytes: 128 })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/quota/storage.test.ts b/packages/cloud/tests/integration/server/quota/storage.test.ts
new file mode 100644
index 000000000..594671da7
--- /dev/null
+++ b/packages/cloud/tests/integration/server/quota/storage.test.ts
@@ -0,0 +1,128 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createStorageQuotaService, StorageQuotaExceededError } from '#cloud/server'
+
+async function seed() {
+ const runtime = await createCloudTestDatabase()
+ const workspaceId = crypto.randomUUID()
+ const documentId = crypto.randomUUID()
+ await runtime.database
+ .insertInto('workspace')
+ .values({
+ id: workspaceId,
+ name: 'Workspace',
+ slug: `workspace-${workspaceId}`,
+ createdBy: 'u'
+ })
+ .execute()
+ await runtime.database
+ .insertInto('document')
+ .values({ id: documentId, workspaceId, name: 'Document', createdBy: 'u' })
+ .execute()
+ async function upload(uploadId: string) {
+ await runtime.database
+ .insertInto('upload')
+ .values({
+ id: uploadId,
+ documentId,
+ baseRevisionId: null,
+ objectKey: `uploads/${uploadId}`,
+ checksum: 'checksum',
+ byteSize: 60,
+ contentType: 'application/octet-stream',
+ multipartUploadId: null,
+ status: 'pending',
+ finalizationStartedAt: null,
+ createdBy: 'u',
+ expiresAt: new Date(Date.now() + 60_000)
+ })
+ .execute()
+ }
+ return { runtime, workspaceId, upload }
+}
+
+describe('storage quota reservations', () => {
+ test('rolls back an owning upload insert when reservation fails', async () => {
+ const context = await seed()
+ try {
+ const quota = createStorageQuotaService(context.runtime.database)
+ const uploadId = crypto.randomUUID()
+ await expect(
+ context.runtime.database.transaction().execute(async (transaction) => {
+ await transaction
+ .insertInto('upload')
+ .values({
+ id: uploadId,
+ documentId: await transaction
+ .selectFrom('document')
+ .select('id')
+ .executeTakeFirstOrThrow()
+ .then((document) => document.id),
+ baseRevisionId: null,
+ objectKey: `uploads/${uploadId}`,
+ checksum: 'checksum',
+ byteSize: 60,
+ contentType: 'application/octet-stream',
+ multipartUploadId: null,
+ status: 'pending',
+ finalizationStartedAt: null,
+ createdBy: 'u',
+ expiresAt: new Date(Date.now() + 60_000)
+ })
+ .execute()
+ await quota.reserveInTransaction(transaction, {
+ workspaceId: context.workspaceId,
+ uploadId,
+ bytes: 60,
+ expiresAt: new Date(Date.now() + 60_000),
+ maximumBytes: 0
+ })
+ })
+ ).rejects.toBeInstanceOf(StorageQuotaExceededError)
+ expect(
+ await context.runtime.database
+ .selectFrom('upload')
+ .select('id')
+ .where('id', '=', uploadId)
+ .executeTakeFirst()
+ ).toBeUndefined()
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('atomically accounts for reserved and committed storage', async () => {
+ const context = await seed()
+ try {
+ const quota = createStorageQuotaService(context.runtime.database)
+ const first = crypto.randomUUID()
+ const second = crypto.randomUUID()
+ await context.upload(first)
+ await context.upload(second)
+ await quota.reserve({
+ workspaceId: context.workspaceId,
+ uploadId: first,
+ bytes: 60,
+ expiresAt: new Date(Date.now() + 60_000),
+ maximumBytes: 100
+ })
+ await expect(
+ quota.reserve({
+ workspaceId: context.workspaceId,
+ uploadId: second,
+ bytes: 60,
+ expiresAt: new Date(Date.now() + 60_000),
+ maximumBytes: 100
+ })
+ ).rejects.toBeInstanceOf(StorageQuotaExceededError)
+ await quota.commit(first)
+ expect(await quota.snapshot(context.workspaceId)).toEqual({
+ committedBytes: 60,
+ reservedBytes: 0
+ })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/rate-limit/cleanup.test.ts b/packages/cloud/tests/integration/server/rate-limit/cleanup.test.ts
new file mode 100644
index 000000000..87a99a03a
--- /dev/null
+++ b/packages/cloud/tests/integration/server/rate-limit/cleanup.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createRateLimitCleanupService } from '#cloud/server'
+
+describe('Cloud rate-limit cleanup', () => {
+ test('removes expired counters and keeps active windows', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ await runtime.database
+ .insertInto('cloudRateLimit')
+ .values([
+ { keyHash: 'old', windowStartedAt: new Date('2025-01-01'), requestCount: 1 },
+ { keyHash: 'active', windowStartedAt: new Date('2026-01-02'), requestCount: 1 }
+ ])
+ .execute()
+ expect(
+ await createRateLimitCleanupService(runtime.database).cleanupExpired(new Date('2026-01-01'))
+ ).toBe(1)
+ expect(
+ await runtime.database.selectFrom('cloudRateLimit').select('keyHash').execute()
+ ).toEqual([{ keyHash: 'active' }])
+ } finally {
+ await runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/sharing/capabilities/service.test.ts b/packages/cloud/tests/integration/server/sharing/capabilities/service.test.ts
new file mode 100644
index 000000000..7aca20284
--- /dev/null
+++ b/packages/cloud/tests/integration/server/sharing/capabilities/service.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, test } from 'bun:test'
+
+import { CLOUD_FEATURE_KEYS, seedSharing, sharingWithPolicy } from '#cloud-tests/helpers/sharing'
+import {
+ DocumentForbiddenError,
+ DocumentNotFoundError,
+ DocumentShareInvalidError
+} from '#cloud/server'
+
+describe('document sharing capabilities integration', () => {
+ test('creates hash-only capabilities and resolves user and guest principals', async () => {
+ const context = await seedSharing()
+ try {
+ const capability = await context.sharing.createShare('owner', context.documentId, {
+ permission: 'view'
+ })
+ expect(capability.secret).toMatch(/^[0-9a-f]{48}$/)
+ expect(capability.path).toBe(`/share/${capability.share.id}#${capability.secret}`)
+ const stored = await context.runtime.database
+ .selectFrom('documentShare')
+ .select(['secretHash', 'lastUsedAt'])
+ .where('id', '=', capability.share.id)
+ .executeTakeFirstOrThrow()
+ expect(stored.secretHash).not.toContain(capability.secret)
+ expect(stored.lastUsedAt).toBeNull()
+ expect(
+ await context.sharing.resolveShare(capability.share.id, {
+ secret: capability.secret,
+ guestName: 'Visitor'
+ })
+ ).toMatchObject({
+ documentId: context.documentId,
+ permission: 'view',
+ principal: { kind: 'guest', name: 'Visitor' }
+ })
+ const user = await context.sharing.resolveShare(
+ capability.share.id,
+ { secret: capability.secret },
+ { userId: 'alice', name: 'Alice', email: '[email protected]' }
+ )
+ expect(user.principal).toEqual({
+ kind: 'user',
+ userId: 'alice',
+ name: 'Alice',
+ })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('rotates and revokes capabilities without exposing prior secrets', async () => {
+ const context = await seedSharing()
+ try {
+ const original = await context.sharing.createShare('owner', context.documentId, {
+ permission: 'edit'
+ })
+ const rotated = await context.sharing.rotateShare(
+ 'owner',
+ context.documentId,
+ original.share.id
+ )
+ expect(rotated.secret).not.toBe(original.secret)
+ expect(rotated.share.roomEpoch).toBe(0)
+ await expect(
+ context.sharing.resolveShare(original.share.id, { secret: original.secret })
+ ).rejects.toBeInstanceOf(DocumentShareInvalidError)
+ expect(
+ await context.sharing.resolveShare(original.share.id, { secret: rotated.secret })
+ ).toMatchObject({ permission: 'edit', roomEpoch: 0 })
+ await context.sharing.revokeShare('owner', context.documentId, original.share.id)
+ await expect(
+ context.sharing.resolveShare(original.share.id, { secret: rotated.secret })
+ ).rejects.toBeInstanceOf(DocumentShareInvalidError)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('enforces capability policy on share updates', async () => {
+ const context = await seedSharing()
+ try {
+ const enabled = sharingWithPolicy(context, {
+ [CLOUD_FEATURE_KEYS.capabilityLinks]: true,
+ [CLOUD_FEATURE_KEYS.anonymousEdit]: false
+ })
+ const capability = await enabled.createShare('owner', context.documentId, {
+ permission: 'view'
+ })
+ await expect(
+ enabled.updateShare('owner', context.documentId, capability.share.id, {
+ permission: 'edit'
+ })
+ ).rejects.toBeInstanceOf(DocumentForbiddenError)
+ expect(
+ await enabled.updateShare('owner', context.documentId, capability.share.id, {
+ permission: 'view'
+ })
+ ).toMatchObject({ permission: 'view' })
+ for (const deploymentMode of ['official', 'self-hosted'] as const) {
+ const disabled = sharingWithPolicy(
+ context,
+ {
+ [CLOUD_FEATURE_KEYS.capabilityLinks]: false,
+ [CLOUD_FEATURE_KEYS.anonymousEdit]: true
+ },
+ deploymentMode
+ )
+ await expect(
+ disabled.updateShare('owner', context.documentId, capability.share.id, {
+ permission: 'view'
+ })
+ ).rejects.toBeInstanceOf(DocumentForbiddenError)
+ }
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('checks sharing access before it looks up a share to update', async () => {
+ const context = await seedSharing()
+ try {
+ const capability = await context.sharing.createShare('owner', context.documentId, {
+ permission: 'view'
+ })
+ await expect(
+ context.sharing.updateShare('viewer', context.documentId, capability.share.id, {
+ expiresAt: null
+ })
+ ).rejects.toBeInstanceOf(DocumentForbiddenError)
+ await expect(
+ context.sharing.updateShare('owner', context.documentId, crypto.randomUUID(), {
+ expiresAt: null
+ })
+ ).rejects.toBeInstanceOf(DocumentNotFoundError)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/sharing/grants/service.test.ts b/packages/cloud/tests/integration/server/sharing/grants/service.test.ts
new file mode 100644
index 000000000..85e70035d
--- /dev/null
+++ b/packages/cloud/tests/integration/server/sharing/grants/service.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, test } from 'bun:test'
+
+import { seedSharing } from '#cloud-tests/helpers/sharing'
+import { DocumentShareInvalidError } from '#cloud/server'
+
+describe('document sharing grants integration', () => {
+ test('manages direct grants', async () => {
+ const context = await seedSharing()
+ try {
+ const grant = await context.sharing.putGrant('owner', context.documentId, 'outside-user', {
+ permission: 'view'
+ })
+ expect(grant).toMatchObject({ userId: 'outside-user', permission: 'view' })
+ expect(await context.sharing.listGrants('owner', context.documentId)).toHaveLength(1)
+ await context.sharing.revokeGrant('owner', context.documentId, 'outside-user')
+ expect(await context.sharing.listGrants('owner', context.documentId)).toEqual([])
+ // Revoking access advances the epoch, so tickets and room keys issued before stop working.
+ expect(
+ await context.runtime.database
+ .selectFrom('document')
+ .select('collaborationEpoch')
+ .where('id', '=', context.documentId)
+ .executeTakeFirstOrThrow()
+ ).toEqual({ collaborationEpoch: 1 })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('accepts an invitation into a direct grant only once', async () => {
+ const context = await seedSharing()
+ try {
+ const created = await context.sharing.createInvitation('owner', context.documentId, {
+ email: '[email protected]',
+ permission: 'edit'
+ })
+ const accepted = await context.sharing.acceptInvitation(
+ { userId: 'invited-user', name: 'Invited', email: '[email protected]' },
+ created.invitation.id,
+ { token: created.token }
+ )
+ // The grant names the inviter, so "shared by" shows who shared it.
+ expect(accepted).toMatchObject({
+ kind: 'document',
+ grant: { userId: 'invited-user', permission: 'edit', createdBy: 'owner' }
+ })
+ await expect(
+ context.sharing.acceptInvitation(
+ { userId: 'second-user', name: 'Second', email: '[email protected]' },
+ created.invitation.id,
+ { token: created.token }
+ )
+ ).rejects.toBeInstanceOf(DocumentShareInvalidError)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/sharing/invitations/service.test.ts b/packages/cloud/tests/integration/server/sharing/invitations/service.test.ts
new file mode 100644
index 000000000..6e6a5c075
--- /dev/null
+++ b/packages/cloud/tests/integration/server/sharing/invitations/service.test.ts
@@ -0,0 +1,205 @@
+import { describe, expect, test } from 'bun:test'
+
+import { assignOwnerUser, seedSharing } from '#cloud-tests/helpers/sharing'
+import {
+ createDocumentSharingService,
+ createInvitationOutbox,
+ createTransactionalEmailService,
+ DocumentShareInvalidError
+} from '#cloud/server'
+
+const OWNER_ID = '11111111-1111-4111-8111-111111111111'
+
+describe('document sharing invitations integration', () => {
+ test('manages pending invitations', async () => {
+ const context = await seedSharing()
+ try {
+ const created = await context.sharing.createInvitation('owner', context.documentId, {
+ email: '[email protected]',
+ permission: 'edit'
+ })
+ expect(created.token).toMatch(/^[0-9a-f]{48}$/)
+ expect(created.invitation).toMatchObject({
+ email: '[email protected]',
+ permission: 'edit'
+ })
+ expect(await context.sharing.listInvitations('owner', context.documentId)).toHaveLength(1)
+ const pending = await context.sharing.createInvitation('owner', context.documentId, {
+ email: '[email protected]',
+ permission: 'view'
+ })
+ await context.sharing.revokeInvitation('owner', context.documentId, pending.invitation.id)
+ expect(await context.sharing.listInvitations('owner', context.documentId)).toHaveLength(1)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('delivers fragment-protected invitation URLs without storing raw tokens', async () => {
+ const context = await seedSharing()
+ const delivered: Array<{
+ recipientEmail: string
+ inviterName: string
+ documentName: string
+ acceptanceURL: string
+ }> = []
+ try {
+ await assignOwnerUser(context, {
+ id: OWNER_ID,
+ name: 'Owner Name',
+ })
+ const sharing = createDocumentSharingService(context.runtime.database, {
+ publicURL: 'https://cloud.example.com',
+ appURL: 'https://app.example.com',
+ delivery: {
+ async sendDocumentInvitation(message) {
+ delivered.push(message)
+ }
+ }
+ })
+ const created = await sharing.createInvitation(OWNER_ID, context.documentId, {
+ email: '[email protected]',
+ permission: 'edit'
+ })
+ expect(delivered).toHaveLength(1)
+ expect(delivered[0]).toMatchObject({
+ recipientEmail: '[email protected]',
+ inviterName: 'Owner Name',
+ documentName: 'Homepage'
+ })
+ const deliveryURL = new URL(delivered[0]?.acceptanceURL ?? '')
+ expect(
+ await sharing.previewInvitation(created.invitation.id, { token: created.token })
+ ).toEqual({
+ kind: 'document',
+ documentName: 'Homepage',
+ inviterName: 'Owner Name',
+ permission: 'edit',
+ expiresAt: created.invitation.expiresAt,
+ recipientHint: 'pe****@example.com'
+ })
+ expect(deliveryURL.origin).toBe('https://app.example.com')
+ expect(deliveryURL.pathname).toBe(`/cloud/invitations/${created.invitation.id}`)
+ expect(deliveryURL.searchParams.get('server')).toBe('https://cloud.example.com')
+ expect(deliveryURL.hash).toBe(`#${created.token}`)
+ const stored = await context.runtime.database
+ .selectFrom('documentInvitation')
+ .select('tokenHash')
+ .where('id', '=', created.invitation.id)
+ .executeTakeFirstOrThrow()
+ expect(stored.tokenHash).not.toContain(created.token)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('stores invitation and encrypted outbox message atomically', async () => {
+ const context = await seedSharing()
+ try {
+ await assignOwnerUser(context, {
+ id: OWNER_ID,
+ name: 'Owner Name',
+ })
+ const email = createTransactionalEmailService(context.runtime.database, {
+ encryptionSecret: 'outbox-test-secret-at-least-32-characters',
+ from: 'OpenPencil <[email protected]>'
+ })
+ const sharing = createDocumentSharingService(context.runtime.database, {
+ publicURL: 'https://cloud.example.com',
+ appURL: 'https://app.example.com',
+ outbox: createInvitationOutbox(email)
+ })
+ const created = await sharing.createInvitation(OWNER_ID, context.documentId, {
+ email: '[email protected]',
+ permission: 'view'
+ })
+ expect(
+ await context.runtime.database
+ .selectFrom('transactionalEmail')
+ .select(['idempotencyKey', 'status', 'payloadEncrypted'])
+ .executeTakeFirstOrThrow()
+ ).toMatchObject({
+ idempotencyKey: `document-invitation/${created.invitation.id}`,
+ status: 'pending',
+ payloadEncrypted: expect.not.stringContaining(created.token)
+ })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('encrypts and consumes OAuth invitation continuations once', async () => {
+ const context = await seedSharing()
+ try {
+ await assignOwnerUser(context, {
+ id: OWNER_ID,
+ name: 'Owner',
+ })
+ const sharing = createDocumentSharingService(context.runtime.database, {
+ continuationSecret: 'continuation-test-secret-at-least-32-characters'
+ })
+ const created = await sharing.createInvitation(OWNER_ID, context.documentId, {
+ email: '[email protected]',
+ permission: 'view'
+ })
+ const continuation = await sharing.createInvitationContinuation({
+ invitationId: created.invitation.id,
+ token: created.token
+ })
+ const stored = await context.runtime.database
+ .selectFrom('invitationContinuation')
+ .select('tokenEncrypted')
+ .where('id', '=', continuation.id)
+ .executeTakeFirstOrThrow()
+ expect(stored.tokenEncrypted).not.toContain(created.token)
+ expect(stored.tokenEncrypted.split('.')).toHaveLength(5)
+ expect(await sharing.consumeInvitationContinuation(continuation.id)).toEqual({
+ invitationId: created.invitation.id,
+ token: created.token
+ })
+ await expect(sharing.consumeInvitationContinuation(continuation.id)).rejects.toBeInstanceOf(
+ DocumentShareInvalidError
+ )
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('revokes invitations when synchronous compatibility delivery fails', async () => {
+ const context = await seedSharing()
+ try {
+ await assignOwnerUser(context, {
+ id: OWNER_ID,
+ name: 'Owner',
+ })
+ const sharing = createDocumentSharingService(context.runtime.database, {
+ publicURL: 'https://cloud.example.com',
+ appURL: 'https://app.example.com',
+ delivery: {
+ async sendDocumentInvitation() {
+ throw new Error('SMTP unavailable')
+ }
+ }
+ })
+ await expect(
+ sharing.createInvitation(OWNER_ID, context.documentId, {
+ email: '[email protected]',
+ permission: 'view'
+ })
+ ).rejects.toThrow('Invitation delivery failed')
+ expect(
+ await context.runtime.database
+ .selectFrom('documentInvitation')
+ .select('revokedAt')
+ .where('emailNormalized', '=', '[email protected]')
+ .executeTakeFirstOrThrow()
+ ).toMatchObject({ revokedAt: expect.any(Date) })
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/sharing/service.test.ts b/packages/cloud/tests/integration/server/sharing/service.test.ts
new file mode 100644
index 000000000..27b3d9695
--- /dev/null
+++ b/packages/cloud/tests/integration/server/sharing/service.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, test } from 'bun:test'
+
+import { seedSharing } from '#cloud-tests/helpers/sharing'
+import { DocumentForbiddenError } from '#cloud/server'
+
+describe('document sharing facade integration', () => {
+ test('prevents viewers from managing sharing', async () => {
+ const context = await seedSharing()
+ try {
+ await expect(
+ context.sharing.createShare('viewer', context.documentId, { permission: 'view' })
+ ).rejects.toBeInstanceOf(DocumentForbiddenError)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('shows profiles only of people connected to the document', async () => {
+ const context = await seedSharing()
+ const outsider = crypto.randomUUID()
+ const stranger = crypto.randomUUID()
+ try {
+ await context.runtime.database
+ .insertInto('user')
+ .values([
+ {
+ id: outsider,
+ name: 'Outside',
+ email: '[email protected]',
+ emailVerified: true,
+ image: null
+ },
+ {
+ id: stranger,
+ name: 'Stranger',
+ email: '[email protected]',
+ emailVerified: true,
+ image: null
+ }
+ ])
+ .execute()
+ await context.sharing.putGrant('owner', context.documentId, outsider, {
+ permission: 'view'
+ })
+ expect(
+ await context.sharing.userProfile('owner', context.documentId, outsider)
+ ).toMatchObject({ id: outsider, email: '[email protected]' })
+ expect(await context.sharing.userProfile('owner', context.documentId, stranger)).toBeNull()
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/workspaces/members.test.ts b/packages/cloud/tests/integration/server/workspaces/members.test.ts
new file mode 100644
index 000000000..8f1a55608
--- /dev/null
+++ b/packages/cloud/tests/integration/server/workspaces/members.test.ts
@@ -0,0 +1,252 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createMemoryObjectStore } from '#cloud-tests/helpers/objects'
+import { responseJSON } from '#cloud-tests/helpers/response'
+import {
+ createCloudApp,
+ createBetterAuthAdapter,
+ parseCloudServerConfig,
+ type CloudActor
+} from '#cloud/server'
+import * as v from 'valibot'
+
+const config = parseCloudServerConfig({
+ deployment: 'self-hosted',
+ publicURL: 'https://cloud.example.com',
+ appURL: 'https://app.example.com',
+ trustedOrigins: ['https://app.example.com'],
+ databaseURL: 'postgresql://test:test@localhost/test',
+ authSecret: 'integration-test-secret-at-least-32-characters',
+ s3Endpoint: 'http://localhost:9000',
+ s3Region: 'us-east-1',
+ s3Bucket: 'openpencil',
+ s3AccessKeyId: 'openpencil',
+ s3SecretAccessKey: 'openpencil-secret'
+})
+
+const people = {
+ alice: { userId: crypto.randomUUID(), email: '[email protected]', name: 'Alice' },
+ bob: { userId: crypto.randomUUID(), email: '[email protected]', name: 'Bob' },
+ carol: { userId: crypto.randomUUID(), email: '[email protected]', name: 'Carol' }
+} satisfies Record<string, CloudActor>
+
+async function testApp() {
+ const runtime = await createCloudTestDatabase()
+ await runtime.database
+ .insertInto('user')
+ .values(
+ Object.values(people).map((person) => ({
+ id: person.userId,
+ name: person.name,
+ email: person.email,
+ emailVerified: true,
+ image: null
+ }))
+ )
+ .execute()
+ let actor: CloudActor = people.alice
+ const app = createCloudApp({
+ config,
+ database: runtime.database,
+ auth: createBetterAuthAdapter(config, runtime.database),
+ objects: createMemoryObjectStore().store,
+ resolveSession: async () => actor
+ })
+ return {
+ runtime,
+ as(person: CloudActor) {
+ actor = person
+ return (path: string, init?: { method?: string; json?: unknown }) =>
+ app.request(path, {
+ method: init?.method ?? 'GET',
+ headers: { 'Content-Type': 'application/json', Origin: config.publicURL },
+ body: init?.json === undefined ? undefined : JSON.stringify(init.json)
+ })
+ }
+ }
+}
+
+const createdSchema = v.object({
+ invitation: v.object({ id: v.string(), email: v.string(), role: v.string() }),
+ acceptanceURL: v.string()
+})
+const membersSchema = v.object({
+ members: v.array(v.object({ email: v.string(), role: v.string() })),
+ invitations: v.array(v.object({ email: v.string() }))
+})
+
+describe('workspace members', () => {
+ test('invites by email, joins through the invitation link, and keeps an administrator', async () => {
+ const { runtime, as } = await testApp()
+ try {
+ const created = await responseJSON(
+ await as(people.alice)('/api/workspaces', { method: 'POST', json: { name: 'Studio' } }),
+ v.object({ workspace: v.object({ id: v.string(), role: v.string() }) })
+ )
+ const workspaceId = created.workspace.id
+ expect(created.workspace.role).toBe('admin')
+
+ const invited = await responseJSON(
+ await as(people.alice)(`/api/workspaces/${workspaceId}/invitations`, {
+ method: 'POST',
+ json: { email: ' [email protected] ', role: 'editor' }
+ }),
+ createdSchema
+ )
+ expect(invited.invitation).toMatchObject({ email: '[email protected]', role: 'editor' })
+ const link = new URL(invited.acceptanceURL)
+ expect(link.origin).toBe('https://app.example.com')
+ expect(link.pathname).toBe(`/cloud/invitations/${invited.invitation.id}`)
+ const token = link.hash.slice(1)
+
+ const listed = await responseJSON(
+ await as(people.alice)(`/api/workspaces/${workspaceId}/members`),
+ membersSchema
+ )
+ expect(listed.members.map((member) => member.email)).toEqual(['[email protected]'])
+ expect(listed.invitations.map((invitation) => invitation.email)).toEqual(['[email protected]'])
+
+ const preview = await as(people.bob)(
+ `/api/public/invitations/${invited.invitation.id}/preview`,
+ { method: 'POST', json: { token } }
+ )
+ expect(await preview.json()).toMatchObject({
+ invitation: {
+ kind: 'workspace',
+ workspaceName: 'Studio',
+ role: 'editor',
+ inviterName: 'Alice'
+ }
+ })
+
+ const wrongAccount = await as(people.carol)(
+ `/api/invitations/${invited.invitation.id}/accept`,
+ { method: 'POST', json: { token } }
+ )
+ expect(wrongAccount.status).toBe(404)
+
+ const accepted = await as(people.bob)(`/api/invitations/${invited.invitation.id}/accept`, {
+ method: 'POST',
+ json: { token }
+ })
+ expect(await accepted.json()).toEqual({
+ accepted: { kind: 'workspace', workspaceId, role: 'editor' }
+ })
+ const bobsWorkspaces = await responseJSON(
+ await as(people.bob)('/api/workspaces'),
+ v.object({ workspaces: v.array(v.object({ id: v.string() })) })
+ )
+ expect(bobsWorkspaces.workspaces.map((workspace) => workspace.id)).toContain(workspaceId)
+
+ // Members other than administrators see who is in, not who is invited.
+ const asMember = await responseJSON(
+ await as(people.bob)(`/api/workspaces/${workspaceId}/members`),
+ membersSchema
+ )
+ expect(asMember.members.map((member) => member.email)).toEqual([
+ ])
+ expect(asMember.invitations).toEqual([])
+ const notAdmin = await as(people.bob)(`/api/workspaces/${workspaceId}/invitations`, {
+ method: 'POST',
+ json: { email: '[email protected]', role: 'viewer' }
+ })
+ expect(notAdmin.status).toBe(403)
+
+ const lastAdmin = await as(people.alice)(
+ `/api/workspaces/${workspaceId}/members/${people.alice.userId}`,
+ { method: 'PATCH', json: { role: 'editor' } }
+ )
+ expect(lastAdmin.status).toBe(409)
+ const aliceLeaves = await as(people.alice)(
+ `/api/workspaces/${workspaceId}/members/${people.alice.userId}`,
+ { method: 'DELETE' }
+ )
+ expect(aliceLeaves.status).toBe(409)
+
+ const bobLeaves = await as(people.bob)(
+ `/api/workspaces/${workspaceId}/members/${people.bob.userId}`,
+ { method: 'DELETE' }
+ )
+ expect(bobLeaves.status).toBe(204)
+ const again = await as(people.bob)(`/api/workspaces/${workspaceId}/members`)
+ expect(again.status).toBe(404)
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('replaces an earlier invitation to the same address and lets an administrator withdraw it', async () => {
+ const { runtime, as } = await testApp()
+ try {
+ const created = await responseJSON(
+ await as(people.alice)('/api/workspaces', { method: 'POST', json: { name: 'Studio' } }),
+ v.object({ workspace: v.object({ id: v.string() }) })
+ )
+ const workspaceId = created.workspace.id
+ const invite = (role: string) =>
+ as(people.alice)(`/api/workspaces/${workspaceId}/invitations`, {
+ method: 'POST',
+ json: { email: '[email protected]', role }
+ })
+ const first = await responseJSON(await invite('viewer'), createdSchema)
+ const second = await responseJSON(await invite('editor'), createdSchema)
+
+ const stale = await as(people.bob)(`/api/invitations/${first.invitation.id}/accept`, {
+ method: 'POST',
+ json: { token: new URL(first.acceptanceURL).hash.slice(1) }
+ })
+ expect(stale.status).toBe(404)
+
+ const withdrawn = await as(people.alice)(
+ `/api/workspaces/${workspaceId}/invitations/${second.invitation.id}`,
+ { method: 'DELETE' }
+ )
+ expect(withdrawn.status).toBe(204)
+ const listed = await responseJSON(
+ await as(people.alice)(`/api/workspaces/${workspaceId}/members`),
+ membersSchema
+ )
+ expect(listed.invitations).toEqual([])
+ } finally {
+ await runtime.close()
+ }
+ })
+ test('deletes a workspace only once it holds no documents', async () => {
+ const { runtime, as } = await testApp()
+ try {
+ const created = await responseJSON(
+ await as(people.alice)('/api/workspaces', { method: 'POST', json: { name: 'Studio' } }),
+ v.object({ workspace: v.object({ id: v.string() }) })
+ )
+ const workspaceId = created.workspace.id
+ const documentId = crypto.randomUUID()
+ await runtime.database
+ .insertInto('document')
+ .values({ id: documentId, workspaceId, name: 'Poster', createdBy: people.alice.userId })
+ .execute()
+ const remove = () => as(people.alice)(`/api/workspaces/${workspaceId}`, { method: 'DELETE' })
+
+ const withDocument = await remove()
+ expect(withDocument.status).toBe(409)
+ expect(await withDocument.json()).toEqual({ error: { code: 'not_empty' } })
+
+ await runtime.database
+ .updateTable('document')
+ .set({ deletedAt: new Date() })
+ .where('id', '=', documentId)
+ .execute()
+ expect(await (await remove()).json()).toEqual({ error: { code: 'cleanup_pending' } })
+
+ await runtime.database.deleteFrom('document').where('id', '=', documentId).execute()
+ const notAdmin = await as(people.bob)(`/api/workspaces/${workspaceId}`, { method: 'DELETE' })
+ expect(notAdmin.status).toBe(404)
+ expect((await remove()).status).toBe(204)
+ expect((await as(people.alice)(`/api/workspaces/${workspaceId}`)).status).toBe(404)
+ } finally {
+ await runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/workspaces/routes.test.ts b/packages/cloud/tests/integration/server/workspaces/routes.test.ts
new file mode 100644
index 000000000..0b226311c
--- /dev/null
+++ b/packages/cloud/tests/integration/server/workspaces/routes.test.ts
@@ -0,0 +1,202 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createMemoryObjectStore } from '#cloud-tests/helpers/objects'
+import { responseJSON } from '#cloud-tests/helpers/response'
+import {
+ createCloudApp,
+ createBetterAuthAdapter,
+ parseCloudServerConfig,
+ type CloudActor
+} from '#cloud/server'
+import * as v from 'valibot'
+
+const config = parseCloudServerConfig({
+ deployment: 'self-hosted',
+ publicURL: 'http://localhost:8787',
+ databaseURL: 'postgresql://test:test@localhost/test',
+ authSecret: 'integration-test-secret-at-least-32-characters',
+ s3Endpoint: 'http://localhost:9000',
+ s3Region: 'us-east-1',
+ s3Bucket: 'openpencil',
+ s3AccessKeyId: 'openpencil',
+ s3SecretAccessKey: 'openpencil-secret'
+})
+
+const alice: CloudActor = {
+ userId: 'alice',
+ email: '[email protected]',
+ name: 'Alice'
+}
+const bob: CloudActor = {
+ userId: 'bob',
+ email: '[email protected]',
+ name: 'Bob'
+}
+
+async function testApp(actor: CloudActor | null) {
+ const runtime = await createCloudTestDatabase()
+ const auth = createBetterAuthAdapter(config, runtime.database)
+ const objects = createMemoryObjectStore()
+ return {
+ runtime,
+ app: createCloudApp({
+ config,
+ database: runtime.database,
+ auth,
+ objects: objects.store,
+ resolveSession: async () => actor
+ })
+ }
+}
+
+describe('Cloud workspace routes', () => {
+ test('gives an active account one workspace of its own, however often it asks', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const app = createCloudApp({
+ config,
+ database: runtime.database,
+ auth: createBetterAuthAdapter(config, runtime.database),
+ objects: createMemoryObjectStore().store,
+ resolveIdentity: async () => alice,
+ resolveSession: async () => alice
+ })
+ const statuses = await Promise.all([
+ app.request('/api/account/status'),
+ app.request('/api/account/status')
+ ])
+ expect(statuses.map((response) => response.status)).toEqual([200, 200])
+ await app.request('/api/account/status')
+
+ const listed = await responseJSON(
+ await app.request('/api/workspaces'),
+ v.object({ workspaces: v.array(v.object({ name: v.string(), role: v.string() })) })
+ )
+ expect(listed.workspaces).toEqual([
+ expect.objectContaining({ name: 'Alice’s workspace', role: 'admin' })
+ ])
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('requires authentication for Cloud APIs', async () => {
+ const { app, runtime } = await testApp(null)
+ try {
+ const response = await app.request('/api/workspaces')
+ expect(response.status).toBe(401)
+ expect(await response.json()).toEqual({ error: { code: 'unauthorized' } })
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('returns the resolved session actor', async () => {
+ const { app, runtime } = await testApp(alice)
+ try {
+ const response = await app.request('/api/session')
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({ user: alice })
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('creates, lists, and reads an owned workspace', async () => {
+ const { app, runtime } = await testApp(alice)
+ try {
+ const createResponse = await app.request('/api/workspaces', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'Design team', slug: 'design-team' })
+ })
+ expect(createResponse.status).toBe(201)
+ const created = await responseJSON(
+ createResponse,
+ v.object({
+ workspace: v.object({
+ id: v.string(),
+ name: v.string(),
+ slug: v.string(),
+ role: v.string()
+ })
+ })
+ )
+ expect(created.workspace).toMatchObject({
+ name: 'Design team',
+ slug: 'design-team',
+ role: 'admin'
+ })
+
+ const listResponse = await app.request('/api/workspaces')
+ expect(listResponse.status).toBe(200)
+ expect(await listResponse.json()).toMatchObject({
+ workspaces: [{ id: created.workspace.id, role: 'admin' }]
+ })
+
+ const getResponse = await app.request(`/api/workspaces/${created.workspace.id}`)
+ expect(getResponse.status).toBe(200)
+ expect(await getResponse.json()).toMatchObject({ workspace: created.workspace })
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('does not reveal another user workspace', async () => {
+ const { app, runtime } = await testApp(alice)
+ try {
+ const createResponse = await app.request('/api/workspaces', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'Private', slug: 'private-space' })
+ })
+ const created = await responseJSON(
+ createResponse,
+ v.object({ workspace: v.object({ id: v.string() }) })
+ )
+ const bobApp = createCloudApp({
+ config,
+ database: runtime.database,
+ auth: createBetterAuthAdapter(config, runtime.database),
+ objects: createMemoryObjectStore().store,
+ resolveSession: async () => bob
+ })
+
+ const response = await bobApp.request(`/api/workspaces/${created.workspace.id}`)
+ expect(response.status).toBe(404)
+ expect(await response.json()).toEqual({ error: { code: 'not_found' } })
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test('validates workspace input and reports duplicate slugs', async () => {
+ const { app, runtime } = await testApp(alice)
+ try {
+ const invalid = await app.request('/api/workspaces', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: '' })
+ })
+ expect(invalid.status).toBe(400)
+
+ const body = JSON.stringify({ name: 'Team', slug: 'shared-team' })
+ const first = await app.request('/api/workspaces', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body
+ })
+ expect(first.status).toBe(201)
+ const duplicate = await app.request('/api/workspaces', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body
+ })
+ expect(duplicate.status).toBe(409)
+ expect(await duplicate.json()).toEqual({ error: { code: 'slug_conflict' } })
+ } finally {
+ await runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/runtime/node/config.test.ts b/packages/cloud/tests/runtime/node/config.test.ts
new file mode 100644
index 000000000..045eb058a
--- /dev/null
+++ b/packages/cloud/tests/runtime/node/config.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, test } from 'bun:test'
+import { mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+import { loadNodeCloudServerConfig } from '#cloud/runtime/node'
+
+const source = `
+schema_version = 2
+[deployment]
+mode = "self-hosted"
+public_url = "https://toml.example.com"
+indexing = "deny"
+[authentication]
+[object_storage]
+endpoint = "https://objects.example.com"
+region = "us-east-1"
+bucket = "openpencil"
+`
+
+const secrets = {
+ DATABASE_URL: 'postgresql://user:password@database/openpencil',
+ BETTER_AUTH_SECRET: 'auth-secret-at-least-32-characters-long',
+ S3_ACCESS_KEY_ID: 'access-key',
+ S3_SECRET_ACCESS_KEY: 'secret-key'
+}
+
+describe('Node Cloud configuration', () => {
+ test('ignores flat environment variables that the TOML file owns', async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'openpencil-cloud-config-'))
+ const path = join(directory, 'cloud.toml')
+ try {
+ await writeFile(path, source)
+ const config = await loadNodeCloudServerConfig({
+ ...secrets,
+ OPENPENCIL_CLOUD_CONFIG: path,
+ OPENPENCIL_CLOUD_URL: 'https://ignored.example.com',
+ OPENPENCIL_CLOUD_INDEXING_POLICY: 'allow'
+ })
+ expect(config.publicURL).toBe('https://toml.example.com')
+ expect(config.indexingPolicy).toBe('deny')
+ } finally {
+ await rm(directory, { recursive: true })
+ }
+ })
+
+ test('requires a deployment TOML file', async () => {
+ await expect(loadNodeCloudServerConfig(secrets)).rejects.toThrow('OPENPENCIL_CLOUD_CONFIG')
+ })
+})
diff --git a/packages/cloud/tests/runtime/node/email.test.ts b/packages/cloud/tests/runtime/node/email.test.ts
new file mode 100644
index 000000000..a9a75dbfd
--- /dev/null
+++ b/packages/cloud/tests/runtime/node/email.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, test } from 'bun:test'
+
+import { renderTransactionalEmail } from '#cloud/email'
+import { createNodemailerTransactionalEmailTransport } from '#cloud/runtime/node'
+
+const payload = {
+ inviterName: 'Alice',
+ documentName: 'Homepage',
+ permission: 'edit' as const,
+ expiresAt: '2026-01-08T00:00:00.000Z',
+ acceptanceURL:
+ 'https://app.example.com/cloud/invitations/invitation-id?server=https%3A%2F%2Fcloud.example.com#secret-token'
+}
+
+describe('transactional email delivery', () => {
+ test('renders matching HTML and plain-text invitations', async () => {
+ const rendered = await renderTransactionalEmail({ kind: 'document-invitation', payload })
+ expect(rendered.subject).toContain('Alice invited you to edit Homepage')
+ expect(rendered.html).toContain('OpenPencil invitation')
+ expect(rendered.html).toContain(payload.acceptanceURL.replaceAll('&', '&amp;'))
+ expect(rendered.text).toContain(payload.acceptanceURL)
+ })
+
+ test('sends rendered messages through injected Nodemailer transports', async () => {
+ const sent: unknown[] = []
+ const transport = createNodemailerTransactionalEmailTransport({
+ transporter: {
+ async sendMail(mail) {
+ sent.push(mail)
+ return { messageId: 'message-id' }
+ }
+ }
+ })
+ expect(
+ await transport.send({
+ deliveryId: 'delivery-id',
+ from: 'OpenPencil <[email protected]>',
+ subject: 'Invitation',
+ html: '<p>Invitation</p>',
+ text: 'Invitation',
+ headers: { 'X-OpenPencil-Delivery-ID': 'delivery-id' }
+ })
+ ).toMatchObject({ transportMessageId: 'message-id' })
+ expect(sent).toHaveLength(1)
+ expect(sent[0]).toMatchObject({
+ from: 'OpenPencil <[email protected]>',
+ headers: { 'X-OpenPencil-Delivery-ID': 'delivery-id' }
+ })
+ })
+})
diff --git a/packages/cloud/tests/runtime/node/enrollment-email.test.ts b/packages/cloud/tests/runtime/node/enrollment-email.test.ts
new file mode 100644
index 000000000..f277365e0
--- /dev/null
+++ b/packages/cloud/tests/runtime/node/enrollment-email.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, test } from 'bun:test'
+
+import { renderTransactionalEmail } from '#cloud/email'
+
+const enrollmentKinds = [
+ 'enrollment-requested',
+ 'enrollment-approved',
+ 'enrollment-rejected',
+ 'enrollment-revoked'
+] as const
+
+describe('enrollment email rendering', () => {
+ for (const kind of enrollmentKinds) {
+ test(`renders HTML and text for ${kind}`, async () => {
+ const rendered = await renderTransactionalEmail({
+ kind,
+ payload: { name: 'Person', actionURL: 'https://cloud.example.com/auth/sign-in' }
+ })
+ expect(rendered.subject).toBeString()
+ expect(rendered.html).toContain('https://cloud.example.com/auth/sign-in')
+ expect(rendered.text).toContain('https://cloud.example.com/auth/sign-in')
+ expect(rendered.html).not.toContain('internal note')
+ })
+ }
+ test('renders administrator notification without an approval token', async () => {
+ const rendered = await renderTransactionalEmail({
+ kind: 'admin-enrollment-notification',
+ payload: {
+ requesterEmail: '[email protected]',
+ requesterName: 'Person',
+ reason: 'Design',
+ actionURL: 'https://cloud.example.com/admin/enrollment'
+ }
+ })
+ expect(rendered.html).toContain('[email protected]')
+ expect(rendered.html).toContain('/admin/enrollment')
+ expect(rendered.html).not.toContain('token=')
+ })
+})
diff --git a/packages/cloud/tests/runtime/node/entitlements-command.test.ts b/packages/cloud/tests/runtime/node/entitlements-command.test.ts
new file mode 100644
index 000000000..4c052f21e
--- /dev/null
+++ b/packages/cloud/tests/runtime/node/entitlements-command.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, test } from 'bun:test'
+
+import { entitlementWriteRefusal } from '#cloud/runtime/node/entitlements-command'
+
+const staticConfig = {
+ staticEntitlements: { documents: {}, sharing: {}, storage: {}, collaboration: {} }
+}
+
+describe('entitlements command', () => {
+ test('refuses to write rows the server does not read when entitlements are static', () => {
+ expect(entitlementWriteRefusal(staticConfig, 'set', false)).toContain('static [entitlements]')
+ expect(entitlementWriteRefusal(staticConfig, 'clear', false)).toContain('static [entitlements]')
+ })
+
+ test('reads, dry runs, and database entitlements stay available', () => {
+ expect(entitlementWriteRefusal(staticConfig, 'get', false)).toBeNull()
+ expect(entitlementWriteRefusal(staticConfig, 'set', true)).toBeNull()
+ expect(entitlementWriteRefusal({ staticEntitlements: undefined }, 'set', false)).toBeNull()
+ })
+})
diff --git a/packages/cloud/tests/runtime/node/workspace-invitation-email.test.ts b/packages/cloud/tests/runtime/node/workspace-invitation-email.test.ts
new file mode 100644
index 000000000..6a912a82e
--- /dev/null
+++ b/packages/cloud/tests/runtime/node/workspace-invitation-email.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, test } from 'bun:test'
+
+import { renderTransactionalEmail } from '#cloud/email'
+
+describe('workspace invitation email', () => {
+ test('names the workspace, the inviter, and what joining lets the person do', async () => {
+ const acceptanceURL = 'https://app.example.com/cloud/invitations/id?server=x#secret'
+ const rendered = await renderTransactionalEmail({
+ kind: 'workspace-invitation',
+ payload: {
+ inviterName: 'Ana',
+ workspaceName: 'Studio',
+ role: 'editor',
+ expiresAt: '2026-10-22T00:00:00.000Z',
+ acceptanceURL
+ }
+ })
+ expect(rendered.subject).toBe('Ana invited you to Studio')
+ expect(rendered.text).toContain('Ana invited you to edit in the workspace “Studio”')
+ expect(rendered.html).toContain(acceptanceURL)
+ expect(rendered.text).toContain('Join workspace')
+ })
+})
diff --git a/packages/cloud/tests/server/api/router.test.ts b/packages/cloud/tests/server/api/router.test.ts
new file mode 100644
index 000000000..c3dadb8ee
--- /dev/null
+++ b/packages/cloud/tests/server/api/router.test.ts
@@ -0,0 +1,133 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudAPIRouter, type CloudActor, type CloudAPIEnvironment } from '#cloud/server'
+import { Hono } from 'hono'
+
+const actor: CloudActor = {
+ userId: 'alice',
+ email: '[email protected]',
+ name: 'Alice'
+}
+
+async function notUsed(): Promise<never> {
+ throw new Error('not used')
+}
+
+function services() {
+ return {
+ collaboration: {
+ issueUserTicket: async () => {
+ throw new Error('not used')
+ },
+ issueShareTicket: async () => {
+ throw new Error('not used')
+ }
+ },
+ documents: {
+ cleanupExpiredUploads: async () => 0,
+ list: async () => [],
+ listShared: async () => [],
+ usage: async () => ({ bytesUsed: 0, objectCount: 0, documentCount: 0 }),
+ access: async () => ({
+ permission: 'edit' as const,
+ canManageSharing: true,
+ sources: ['owner' as const]
+ }),
+ downloadShared: async () => {
+ throw new Error('not used')
+ },
+ download: async () => {
+ throw new Error('not used')
+ },
+ remove: async () => undefined,
+ create: async () => {
+ throw new Error('not used')
+ },
+ createUpload: async () => {
+ throw new Error('not used')
+ },
+ commitUpload: async () => {
+ throw new Error('not used')
+ }
+ },
+ sharing: {
+ lookupUser: async () => null,
+ userProfile: async () => null,
+ listShares: async () => [],
+ createShare: async () => {
+ throw new Error('not used')
+ },
+ updateShare: async () => {
+ throw new Error('not used')
+ },
+ rotateShare: async () => {
+ throw new Error('not used')
+ },
+ revokeShare: async () => undefined,
+ resolveShare: async () => {
+ throw new Error('not used')
+ },
+ listGrants: async () => [],
+ putGrant: async () => {
+ throw new Error('not used')
+ },
+ revokeGrant: async () => undefined,
+ listInvitations: async () => [],
+ createInvitation: async () => {
+ throw new Error('not used')
+ },
+ createInvitationContinuation: async () => {
+ throw new Error('not used')
+ },
+ consumeInvitationContinuation: async () => {
+ throw new Error('not used')
+ },
+ previewInvitation: async () => {
+ throw new Error('not used')
+ },
+ acceptInvitation: async () => {
+ throw new Error('not used')
+ },
+ revokeInvitation: async () => undefined
+ },
+ workspaces: {
+ list: async () => [],
+ get: async () => undefined,
+ create: async () => {
+ throw new Error('not used')
+ },
+ ensurePersonal: async () => undefined
+ },
+ workspaceMembers: {
+ rename: notUsed,
+ list: notUsed,
+ invite: notUsed,
+ revokeInvitation: notUsed,
+ updateRole: notUsed,
+ remove: notUsed,
+ delete: notUsed,
+ preview: async () => null,
+ accept: async () => null
+ }
+ }
+}
+
+describe('createCloudAPIRouter', () => {
+ test('exposes API-relative routes independently from deployment assembly', async () => {
+ const router = createCloudAPIRouter(services())
+ const app = new Hono<CloudAPIEnvironment>()
+ .use('*', async (context, next) => {
+ context.set('actor', actor)
+ await next()
+ })
+ .route('/', router)
+
+ const session = await app.request('/session')
+ expect(session.status).toBe(200)
+ expect(await session.json()).toEqual({ user: actor })
+
+ const workspaces = await app.request('/workspaces')
+ expect(workspaces.status).toBe(200)
+ expect(await workspaces.json()).toEqual({ workspaces: [] })
+ })
+})
diff --git a/packages/cloud/tests/server/auth/index.test.ts b/packages/cloud/tests/server/auth/index.test.ts
new file mode 100644
index 000000000..4f33a3fef
--- /dev/null
+++ b/packages/cloud/tests/server/auth/index.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ configuredSocialProviders,
+ createBetterAuthAdapter,
+ parseCloudServerConfig
+} from '#cloud/server'
+import type { CloudDatabase } from '#cloud/server'
+import type { BetterAuthOptions } from 'better-auth'
+import {
+ DummyDriver,
+ Kysely,
+ PostgresAdapter,
+ PostgresIntrospector,
+ PostgresQueryCompiler,
+ type Dialect
+} from 'kysely'
+
+function dummyPostgresDialect(): Dialect {
+ return {
+ createAdapter: () => new PostgresAdapter(),
+ createDriver: () => new DummyDriver(),
+ createIntrospector: (database) => new PostgresIntrospector(database),
+ createQueryCompiler: () => new PostgresQueryCompiler()
+ }
+}
+
+const baseConfig = {
+ deployment: 'self-hosted',
+ publicURL: 'https://pencil.example.com',
+ databaseURL: 'postgresql://openpencil:secret@database/openpencil',
+ authSecret: 'a-secure-auth-secret-with-at-least-32-characters',
+ s3Endpoint: 'https://objects.example.com',
+ s3Region: 'us-east-1',
+ s3Bucket: 'openpencil',
+ s3AccessKeyId: 'access-key',
+ s3SecretAccessKey: 'secret-key'
+}
+
+function database(): Kysely<CloudDatabase> {
+ return new Kysely<CloudDatabase>({ dialect: dummyPostgresDialect() })
+}
+
+describe('Cloud authentication', () => {
+ test('keeps social providers optional for self-hosting', () => {
+ const config = parseCloudServerConfig(baseConfig)
+ expect(configuredSocialProviders(config)).toEqual([])
+ expect(createBetterAuthAdapter(config, database()).handler).toBeFunction()
+ })
+
+ test('advertises only fully configured providers', () => {
+ const config = parseCloudServerConfig({
+ ...baseConfig,
+ googleClientId: 'google-client',
+ googleClientSecret: 'google-secret',
+ appleClientId: 'apple-client',
+ appleTeamId: 'apple-team',
+ appleKeyId: 'apple-key',
+ applePrivateKey: 'private-key-loaded-lazily'
+ })
+ expect(configuredSocialProviders(config)).toEqual(['apple', 'google'])
+ })
+
+ test('retains explicit trusted client IP configuration', () => {
+ const config = parseCloudServerConfig({
+ ...baseConfig,
+ authTrustedIPHeaders: ['cf-connecting-ip'],
+ authTrustedProxies: ['192.0.2.10', '10.0.0.0/24']
+ })
+ expect(config.authTrustedIPHeaders).toEqual(['cf-connecting-ip'])
+ expect(config.authTrustedProxies).toEqual(['192.0.2.10', '10.0.0.0/24'])
+ })
+
+ test('uses Better Auth PostgreSQL configuration without exposing it in contracts', () => {
+ const options = {
+ database: { db: database(), type: 'postgres' }
+ } satisfies Pick<BetterAuthOptions, 'database'>
+ expect(options.database.type).toBe('postgres')
+ })
+})
diff --git a/packages/cloud/tests/server/auth/workspace-access.test.ts b/packages/cloud/tests/server/auth/workspace-access.test.ts
new file mode 100644
index 000000000..cdbe30dbc
--- /dev/null
+++ b/packages/cloud/tests/server/auth/workspace-access.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, test } from 'bun:test'
+
+import { workspaceRoles } from '#cloud/server'
+
+describe('Better Auth workspace access prototype', () => {
+ test('models current admin, editor, and viewer permissions', () => {
+ expect(
+ workspaceRoles.admin.authorize({ workspace: ['delete'], document: ['share'] }).success
+ ).toBe(true)
+ expect(workspaceRoles.editor.authorize({ document: ['edit', 'share'] }).success).toBe(true)
+ expect(workspaceRoles.editor.authorize({ workspace: ['manage-members'] }).success).toBe(false)
+ expect(workspaceRoles.viewer.authorize({ document: ['read'] }).success).toBe(true)
+ expect(workspaceRoles.viewer.authorize({ document: ['edit'] }).success).toBe(false)
+ })
+})
diff --git a/packages/cloud/tests/server/config/deployment.test.ts b/packages/cloud/tests/server/config/deployment.test.ts
new file mode 100644
index 000000000..b0b948367
--- /dev/null
+++ b/packages/cloud/tests/server/config/deployment.test.ts
@@ -0,0 +1,224 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ cloudDeploymentConfigSchema,
+ cloudDiscoveryFromConfig,
+ parseCloudDeploymentConfig,
+ parseCloudDeploymentTOML
+} from '#cloud/server'
+import { parse as parseTOML } from 'smol-toml'
+import * as v from 'valibot'
+
+const minimalSource = `
+schema_version = 2
+
+[deployment]
+mode = "self-hosted"
+public_url = "https://cloud.example.com"
+app_url = "https://app.example.com"
+trusted_origins = ["https://app.example.com"]
+
+[authentication]
+enrollment_mode = "approval"
+
+[authentication.mfa]
+deployment_admin_required = true
+totp_enabled = true
+passkeys_enabled = true
+recovery_codes_enabled = true
+trusted_device_days = 7
+
+[authentication.passkeys]
+rp_id = "cloud.example.com"
+rp_name = "OpenPencil Cloud"
+origin = "https://cloud.example.com"
+
+[authentication.email_password]
+enabled = true
+sign_up = false
+minimum_password_length = 16
+maximum_password_length = 120
+verification_link_expires_minutes = 30
+password_reset_link_expires_minutes = 45
+compromised_password_check = true
+
+[authentication.captcha]
+provider = "cloudflare-turnstile"
+site_key = "public-turnstile-site-key"
+allowed_hostnames = ["cloud.example.com"]
+
+[authentication.providers.google]
+
+[email]
+transport = "smtp"
+
+[email.smtp]
+host = "smtp.example.com"
+port = 465
+secure = true
+
+[object_storage]
+endpoint = "https://objects.example.com"
+region = "us-east-1"
+bucket = "openpencil"
+`
+
+const environment = {
+ DATABASE_URL: 'postgresql://user:password@database/openpencil',
+ BETTER_AUTH_SECRET: 'auth-secret-at-least-32-characters-long',
+ TURNSTILE_SECRET_KEY: 'turnstile-secret',
+ GOOGLE_CLIENT_ID: 'google-public-client-id',
+ GOOGLE_CLIENT_SECRET: 'google-secret',
+ OPENPENCIL_CLOUD_SMTP_USER: 'smtp-user',
+ OPENPENCIL_CLOUD_SMTP_PASSWORD: 'smtp-password',
+ S3_ACCESS_KEY_ID: 'access-key',
+ S3_SECRET_ACCESS_KEY: 'secret-key'
+}
+
+const completeSource = `${minimalSource.replace(
+ 'trusted_origins = ["https://app.example.com"]',
+ 'trusted_origins = ["https://app.example.com"]\nindexing = "allow"'
+)}
+
+[authentication.trusted_proxies]
+headers = ["cf-connecting-ip"]
+addresses = ["192.0.2.10"]
+
+[object_storage.credentials.session_token]
+from_env = "CUSTOM_SESSION_TOKEN"
+
+[workers.email]
+batch_size = 20
+interval_ms = 15000
+lease_ms = 120000
+maximum_attempts = 3
+
+[workers.cleanup]
+enabled = false
+batch_size = 40
+interval_ms = 45000
+lease_ms = 180000
+document_retention_days = 14
+
+[technical_limits]
+maximum_upload_bytes = 104857600
+maximum_collaboration_message_bytes = 524288
+maximum_connections_per_room = 250
+`
+
+describe('Cloud TOML deployment configuration', () => {
+ test('uses conventional secret references without TOML boilerplate', () => {
+ expect(parseCloudDeploymentTOML(minimalSource, environment)).toMatchObject({
+ deployment: 'self-hosted',
+ databaseURL: environment.DATABASE_URL,
+ authSecret: environment.BETTER_AUTH_SECRET,
+ enrollmentMode: 'approval',
+ emailPasswordEnabled: true,
+ emailPasswordSignUpEnabled: false,
+ emailPasswordMinimumLength: 16,
+ emailPasswordMaximumLength: 120,
+ emailVerificationExpiresIn: 1800,
+ passwordResetExpiresIn: 2700,
+ compromisedPasswordCheck: true,
+ deploymentAdminMFARequired: true,
+ totpEnabled: true,
+ passkeysEnabled: true,
+ recoveryCodesEnabled: true,
+ mfaTrustedDeviceDays: 7,
+ passkeyRPID: 'cloud.example.com',
+ passkeyRPName: 'OpenPencil Cloud',
+ passkeyOrigin: 'https://cloud.example.com',
+ captchaProvider: 'cloudflare-turnstile',
+ captchaSiteKey: 'public-turnstile-site-key',
+ captchaSecretKey: 'turnstile-secret',
+ captchaAllowedHostnames: ['cloud.example.com'],
+ googleClientId: 'google-public-client-id',
+ googleClientSecret: environment.GOOGLE_CLIENT_SECRET,
+ s3AccessKeyId: environment.S3_ACCESS_KEY_ID,
+ s3SecretAccessKey: environment.S3_SECRET_ACCESS_KEY
+ })
+ })
+
+ test('normalizes complete operational and storage policy', () => {
+ const config = parseCloudDeploymentTOML(completeSource, {
+ ...environment,
+ CUSTOM_SESSION_TOKEN: 'session-token'
+ })
+ expect(config).toMatchObject({
+ indexingPolicy: 'allow',
+ authTrustedIPHeaders: ['cf-connecting-ip'],
+ authTrustedProxies: ['192.0.2.10'],
+ s3SessionToken: 'session-token',
+ emailBatchSize: 20,
+ emailIntervalMs: 15_000,
+ emailLeaseDurationMs: 120_000,
+ emailMaximumAttempts: 3,
+ cleanupEnabled: false,
+ cleanupBatchSize: 40,
+ cleanupIntervalMs: 45_000,
+ cleanupLeaseDurationMs: 180_000,
+ documentRetentionMs: 14 * 86_400_000,
+ technicalLimits: {
+ maximumUploadBytes: 104857600,
+ maximumCollaborationMessageBytes: 524288,
+ maximumConnectionsPerRoom: 250
+ }
+ })
+ })
+
+ test('lists the server for editors from a minimum version, and only when configured', () => {
+ const unlisted = cloudDiscoveryFromConfig(parseCloudDeploymentTOML(minimalSource, environment))
+ expect(unlisted.listing).toBeUndefined()
+
+ const listedSource = minimalSource.replace(
+ 'trusted_origins = ["https://app.example.com"]',
+ 'trusted_origins = ["https://app.example.com"]\nlisting = { minimum_editor_version = "0.14.0" }'
+ )
+ const listed = cloudDiscoveryFromConfig(parseCloudDeploymentTOML(listedSource, environment))
+ expect(listed.listing).toEqual({ minimumEditorVersion: '0.14.0' })
+
+ expect(() =>
+ parseCloudDeploymentTOML(listedSource.replace('"0.14.0"', '"soon"'), environment)
+ ).toThrow()
+ })
+
+ test('supports explicit secret-reference names', () => {
+ const input = parseTOML(minimalSource)
+ const parsed = v.parse(cloudDeploymentConfigSchema, input)
+ const custom = {
+ ...parsed,
+ authentication: {
+ ...parsed.authentication,
+ secret: { from_env: 'CUSTOM_AUTH_SECRET' }
+ }
+ }
+ expect(
+ parseCloudDeploymentConfig(custom, {
+ ...environment,
+ CUSTOM_AUTH_SECRET: 'custom-auth-secret-at-least-32-characters'
+ }).authSecret
+ ).toBe('custom-auth-secret-at-least-32-characters')
+ })
+
+ test('reports missing reference names without exposing values', () => {
+ expect(() => parseCloudDeploymentTOML(minimalSource, {})).toThrow(
+ 'Required secret binding is unavailable: DATABASE_URL'
+ )
+ })
+
+ test('rejects unsupported schema versions', () => {
+ expect(() =>
+ parseCloudDeploymentTOML(
+ minimalSource.replace('schema_version = 2', 'schema_version = 1'),
+ environment
+ )
+ ).toThrow()
+ expect(() =>
+ parseCloudDeploymentTOML(
+ minimalSource.replace('schema_version = 2', 'schema_version = 3'),
+ environment
+ )
+ ).toThrow()
+ })
+})
diff --git a/packages/cloud/tests/server/config/schema.test.ts b/packages/cloud/tests/server/config/schema.test.ts
new file mode 100644
index 000000000..8c967003a
--- /dev/null
+++ b/packages/cloud/tests/server/config/schema.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, test } from 'bun:test'
+
+import { CloudConfigError, parseCloudServerConfig } from '#cloud/server'
+
+const baseConfig = {
+ deployment: 'self-hosted',
+ publicURL: 'https://pencil.example.com',
+ databaseURL: 'postgresql://openpencil:secret@database/openpencil',
+ authSecret: 'a-secure-auth-secret-with-at-least-32-characters',
+ s3Endpoint: 'https://objects.example.com',
+ s3Region: 'us-east-1',
+ s3Bucket: 'openpencil',
+ s3AccessKeyId: 'access-key',
+ s3SecretAccessKey: 'secret-key'
+}
+
+describe('Cloud server configuration', () => {
+ test('accepts a self-hosted configuration without social providers', () => {
+ expect(parseCloudServerConfig(baseConfig)).toMatchObject({
+ deployment: 'self-hosted',
+ indexingPolicy: 'deny',
+ trustedOrigins: []
+ })
+ })
+
+ test('requires an MFA method when enforcing deployment administrator MFA', () => {
+ expect(() =>
+ parseCloudServerConfig({ ...baseConfig, deploymentAdminMFARequired: true })
+ ).toThrow('requires TOTP or passkeys')
+ })
+
+ test('requires passkey identity to match the Cloud origin', () => {
+ expect(() =>
+ parseCloudServerConfig({
+ ...baseConfig,
+ passkeysEnabled: true,
+ passkeyRPID: 'other.example.com',
+ passkeyOrigin: 'https://other.example.com'
+ })
+ ).toThrow('Passkey origin must match')
+ })
+
+ test('requires email delivery when enabling email and password', () => {
+ expect(() => parseCloudServerConfig({ ...baseConfig, emailPasswordEnabled: true })).toThrow(
+ 'requires transactional email delivery'
+ )
+ })
+
+ test('requires strong abuse controls for official public credential sign-up', () => {
+ expect(() =>
+ parseCloudServerConfig({
+ ...baseConfig,
+ deployment: 'official',
+ emailPasswordEnabled: true,
+ emailTransport: 'cloudflare',
+ emailFrom: '[email protected]'
+ })
+ ).toThrow('requires compromised-password checks and CAPTCHA')
+ })
+
+ test('requires CAPTCHA public and secret configuration together', () => {
+ expect(() =>
+ parseCloudServerConfig({
+ ...baseConfig,
+ captchaProvider: 'cloudflare-turnstile',
+ captchaSiteKey: 'public-site-key'
+ })
+ ).toThrow('CAPTCHA configuration must provide')
+ })
+
+ test('requires Google credentials together', () => {
+ expect(() =>
+ parseCloudServerConfig({ ...baseConfig, googleClientId: 'google-client' })
+ ).toThrow(CloudConfigError)
+ })
+
+ test('requires all Apple signing fields together', () => {
+ expect(() => parseCloudServerConfig({ ...baseConfig, appleClientId: 'apple-client' })).toThrow(
+ CloudConfigError
+ )
+ })
+
+ test('requires transport-specific transactional email configuration', () => {
+ expect(() =>
+ parseCloudServerConfig({
+ ...baseConfig,
+ emailTransport: 'cloudflare'
+ })
+ ).toThrow('requires an email from address')
+ expect(() =>
+ parseCloudServerConfig({
+ ...baseConfig,
+ emailTransport: 'smtp',
+ emailFrom: '[email protected]'
+ })
+ ).toThrow('SMTP configuration')
+ expect(
+ parseCloudServerConfig({
+ ...baseConfig,
+ emailTransport: 'cloudflare',
+ emailFrom: '[email protected]'
+ }).emailTransport
+ ).toBe('cloudflare')
+ })
+
+ test('requires Cloudflare R2 S3 compatibility settings', () => {
+ const r2 = {
+ ...baseConfig,
+ s3Endpoint: 'https://account-id.r2.cloudflarestorage.com',
+ s3Region: 'auto',
+ s3ForcePathStyle: false,
+ s3ChecksumVerification: 'metadata' as const
+ }
+ expect(parseCloudServerConfig(r2)).toMatchObject(r2)
+ expect(() => parseCloudServerConfig({ ...r2, s3Region: 'us-east-1' })).toThrow(
+ 'Cloudflare R2 S3 region must be auto'
+ )
+ expect(() => parseCloudServerConfig({ ...r2, s3ForcePathStyle: true })).toThrow(
+ 'Cloudflare R2 S3 endpoint must disable path-style requests'
+ )
+ expect(() => parseCloudServerConfig({ ...r2, s3ChecksumVerification: 'native' })).toThrow(
+ 'Cloudflare R2 checksum verification must use metadata'
+ )
+ })
+
+ test('rejects short auth secrets', () => {
+ expect(() => parseCloudServerConfig({ ...baseConfig, authSecret: 'short' })).toThrow()
+ })
+})
diff --git a/packages/cloud/tests/server/email/worker.test.ts b/packages/cloud/tests/server/email/worker.test.ts
new file mode 100644
index 000000000..18820bbb9
--- /dev/null
+++ b/packages/cloud/tests/server/email/worker.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, test } from 'bun:test'
+
+import { startTransactionalEmailWorker } from '#cloud/server'
+
+describe('transactional email worker lifecycle', () => {
+ test('runs sequentially and awaits an in-flight drain during shutdown', async () => {
+ let calls = 0
+ let concurrent = 0
+ let maximumConcurrent = 0
+ let releaseFirst: (() => void) | undefined
+ const firstRun = new Promise<void>((resolve) => {
+ releaseFirst = resolve
+ })
+ const worker = startTransactionalEmailWorker(
+ {
+ async enqueue() {
+ return 'unused'
+ },
+ async deliverPending() {
+ calls++
+ concurrent++
+ maximumConcurrent = Math.max(maximumConcurrent, concurrent)
+ if (calls === 1) await firstRun
+ concurrent--
+ return { claimed: 0, accepted: 0, retrying: 0, failed: 0, suppressed: 0 }
+ }
+ },
+ {
+ batchSize: 1,
+ intervalMs: 1000,
+ leaseDurationMs: 1000,
+ maximumAttempts: 1
+ }
+ )
+ expect(calls).toBe(1)
+ const stopped = worker.stop()
+ await Promise.resolve()
+ expect(concurrent).toBe(1)
+ releaseFirst?.()
+ await stopped
+ expect(calls).toBe(1)
+ expect(maximumConcurrent).toBe(1)
+ })
+})
diff --git a/packages/cloud/tests/server/policy/entitlements.test.ts b/packages/cloud/tests/server/policy/entitlements.test.ts
new file mode 100644
index 000000000..07a24ddf3
--- /dev/null
+++ b/packages/cloud/tests/server/policy/entitlements.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, test } from 'bun:test'
+
+import { StaticEntitlementSource } from '#cloud/server'
+
+const workspace = { type: 'workspace' as const, id: 'workspace-1' }
+
+describe('entitlement source', () => {
+ test('returns typed values and null for unavailable entitlements', async () => {
+ const source = new StaticEntitlementSource({
+ anonymous: true,
+ maximumFileBytes: 1024,
+ tier: 'self-hosted'
+ })
+ expect(await source.boolean(workspace, 'anonymous')).toBe(true)
+ expect(await source.number(workspace, 'maximumFileBytes')).toBe(1024)
+ expect(await source.string(workspace, 'tier')).toBe('self-hosted')
+ expect(await source.number(workspace, 'unknown')).toBeNull()
+ })
+})
diff --git a/packages/cloud/tests/server/policy/policy.test.ts b/packages/cloud/tests/server/policy/policy.test.ts
new file mode 100644
index 000000000..c8038abd4
--- /dev/null
+++ b/packages/cloud/tests/server/policy/policy.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, test } from 'bun:test'
+
+import { CLOUD_FEATURE_KEYS, createDefaultCloudPolicy } from '#cloud/server'
+
+const context = {
+ targetingKey: 'workspace-1',
+ workspaceId: 'workspace-1',
+ deploymentMode: 'self-hosted' as const
+}
+
+describe('Cloud OpenFeature policy', () => {
+ test('evaluates typed safe defaults through OpenFeature', async () => {
+ const policy = await createDefaultCloudPolicy()
+ expect(await policy.boolean(CLOUD_FEATURE_KEYS.capabilityLinks, false, context)).toBe(true)
+ expect(await policy.boolean(CLOUD_FEATURE_KEYS.serverEnforcedWrites, true, context)).toBe(false)
+ expect(await policy.number(CLOUD_FEATURE_KEYS.maximumFileBytes, 1, context)).toBe(
+ 1024 * 1024 * 1024
+ )
+ })
+})
diff --git a/packages/cloud/tests/server/policy/static.test.ts b/packages/cloud/tests/server/policy/static.test.ts
new file mode 100644
index 000000000..419982828
--- /dev/null
+++ b/packages/cloud/tests/server/policy/static.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, test } from 'bun:test'
+
+import { staticEntitlementValues } from '#cloud/server'
+
+describe('structured static entitlements', () => {
+ test('maps product-domain configuration to internal feature keys', () => {
+ expect(
+ staticEntitlementValues({
+ documents: { maximumFileBytes: 100, revisionHistory: true },
+ storage: { maximumBytes: 1000 },
+ sharing: { capabilityLinks: true, anonymousView: true, anonymousEdit: false },
+ collaboration: { enabled: true, maximumParticipants: 5 }
+ })
+ ).toEqual({
+ 'cloud.documents.maximum-file-bytes': 100,
+ 'cloud.documents.revision-history': true,
+ 'cloud.storage.maximum-bytes': 1000,
+ 'cloud.sharing.capability-links': true,
+ 'cloud.sharing.anonymous-view': true,
+ 'cloud.sharing.anonymous-edit': false,
+ 'cloud.collaboration.enabled': true,
+ 'cloud.collaboration.maximum-participants': 5
+ })
+ })
+})
diff --git a/packages/cloud/tests/server/rate-limit/keys.test.ts b/packages/cloud/tests/server/rate-limit/keys.test.ts
new file mode 100644
index 000000000..5c1bfc1ed
--- /dev/null
+++ b/packages/cloud/tests/server/rate-limit/keys.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test } from 'bun:test'
+
+import { trustedClientIP } from '#cloud/server/rate-limit/keys'
+import { Hono } from 'hono'
+
+async function clientIP(headers: Record<string, string>, trustedHeaders: string[]) {
+ const app = new Hono().get('/', (context) =>
+ context.text(trustedClientIP(context, { trustedHeaders }) ?? 'none')
+ )
+ return (await app.request('/', { headers })).text()
+}
+
+describe('trusted client address', () => {
+ test('takes the entry the trusted proxy appended, not what the client sent', async () => {
+ expect(
+ await clientIP({ 'x-forwarded-for': 'spoofed-1, 203.0.113.7' }, ['x-forwarded-for'])
+ ).toBe('203.0.113.7')
+ expect(await clientIP({ 'x-forwarded-for': '203.0.113.7' }, ['x-forwarded-for'])).toBe(
+ '203.0.113.7'
+ )
+ })
+
+ test('skips empty entries and headers that are not trusted', async () => {
+ expect(await clientIP({ 'x-forwarded-for': '203.0.113.7, ' }, ['x-forwarded-for'])).toBe(
+ '203.0.113.7'
+ )
+ expect(await clientIP({ 'x-forwarded-for': '203.0.113.7' }, ['x-real-ip'])).toBe('none')
+ expect(
+ await clientIP({ 'x-real-ip': '198.51.100.2', 'x-forwarded-for': 'a, b' }, [
+ 'x-real-ip',
+ 'x-forwarded-for'
+ ])
+ ).toBe('198.51.100.2')
+ })
+})
diff --git a/packages/cloud/tests/server/sharing/crypto.test.ts b/packages/cloud/tests/server/sharing/crypto.test.ts
new file mode 100644
index 000000000..d41db4fee
--- /dev/null
+++ b/packages/cloud/tests/server/sharing/crypto.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ capabilityHashMatches,
+ decryptContinuationToken,
+ encryptContinuationToken,
+ hashCapability
+} from '#cloud/server'
+
+const secret = 'continuation-test-secret-at-least-32-characters'
+
+describe('sharing crypto', () => {
+ test('hashes capability values and compares malformed values safely', () => {
+ const digest = hashCapability('secret-value')
+ expect(digest).toHaveLength(64)
+ expect(capabilityHashMatches(digest, 'secret-value')).toBe(true)
+ expect(capabilityHashMatches(digest, 'other-value')).toBe(false)
+ expect(capabilityHashMatches('invalid-hex', 'secret-value')).toBe(false)
+ })
+
+ test('uses standard compact JWE and rejects tampered envelopes', async () => {
+ const encrypted = await encryptContinuationToken(secret, 'invitation-token')
+ expect(encrypted.split('.')).toHaveLength(5)
+ expect(await decryptContinuationToken(secret, encrypted)).toBe('invitation-token')
+ const parts = encrypted.split('.')
+ const tag = parts[4] ?? ''
+ const replacement = tag.startsWith('A') ? 'B' : 'A'
+ parts[4] = `${replacement}${tag.slice(1)}`
+ await expect(decryptContinuationToken(secret, parts.join('.'))).rejects.toThrow()
+ })
+})
diff --git a/packages/cloud/tests/server/worker/interval.test.ts b/packages/cloud/tests/server/worker/interval.test.ts
new file mode 100644
index 000000000..414877059
--- /dev/null
+++ b/packages/cloud/tests/server/worker/interval.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, test } from 'bun:test'
+
+import { waitForWorkerInterval } from '#cloud/server/worker/interval'
+
+describe('worker interval', () => {
+ test('waits for the interval', async () => {
+ const started = performance.now()
+ await waitForWorkerInterval(20, new AbortController().signal)
+ expect(performance.now() - started).toBeGreaterThanOrEqual(15)
+ })
+
+ test('ends as soon as the worker stops', async () => {
+ const controller = new AbortController()
+ const waiting = waitForWorkerInterval(60_000, controller.signal)
+ controller.abort()
+ await waiting
+ await waitForWorkerInterval(60_000, controller.signal)
+ })
+})
diff --git a/packages/cloud/tsconfig.json b/packages/cloud/tsconfig.json
new file mode 100644
index 000000000..aa0446d65
--- /dev/null
+++ b/packages/cloud/tsconfig.json
@@ -0,0 +1,30 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "noUncheckedIndexedAccess": true,
+ "noImplicitOverride": true,
+ "useUnknownInCatchVariables": true,
+ "noFallthroughCasesInSwitch": true,
+ "lib": ["ES2023", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "declaration": true,
+ "declarationMap": true,
+ "outDir": "./dist",
+ "rootDir": ".",
+ "skipLibCheck": true,
+ "types": ["bun"],
+ "paths": {
+ "#cloud/*": ["./src/*"],
+ "#cloud-tests/*": ["./tests/*"],
+ "@open-pencil/cloud/contract": ["./src/contract/index.ts"],
+ "@open-pencil/cloud/client": ["./src/client/index.ts"],
+ "@open-pencil/cloud/email": ["./src/email/index.ts"],
+ "@open-pencil/cloud/runtime/node": ["./src/runtime/node/index.ts"],
+ "@open-pencil/cloud/server": ["./src/server/index.ts"]
+ }
+ },
+ "include": ["src/**/*.ts", "tests/**/*.ts", "deploy/**/*.ts"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/packages/cloud/tsdown.config.ts b/packages/cloud/tsdown.config.ts
new file mode 100644
index 000000000..75aa8d696
--- /dev/null
+++ b/packages/cloud/tsdown.config.ts
@@ -0,0 +1,50 @@
+import { defineConfig } from 'tsdown'
+
+const shared = {
+ format: ['esm'] as const,
+ dts: true,
+ sourcemap: true,
+ hash: false,
+ outDir: './dist',
+ treeshake: { moduleSideEffects: false },
+ outputOptions: { minifyInternalExports: false },
+ deps: {
+ neverBundle: [/^node:/],
+ // Dependencies stay imports, except the shared email layout, which ships as source.
+ alwaysBundle: [/^@open-pencil\/feedback\//]
+ }
+}
+
+export default defineConfig([
+ {
+ ...shared,
+ name: 'neutral',
+ entry: {
+ contract: './src/contract/index.ts',
+ server: './src/server/index.ts'
+ },
+ platform: 'neutral',
+ clean: true
+ },
+ {
+ ...shared,
+ name: 'browser',
+ entry: { client: './src/client/index.ts' },
+ platform: 'browser',
+ clean: false
+ },
+ {
+ ...shared,
+ name: 'email',
+ entry: { email: './src/email/index.ts' },
+ platform: 'neutral',
+ clean: false
+ },
+ {
+ ...shared,
+ name: 'node',
+ entry: { 'runtime-node': './src/runtime/node/index.ts' },
+ platform: 'node',
+ clean: false
+ }
+])
diff --git a/packages/cloud/tsdown.standalone.config.ts b/packages/cloud/tsdown.standalone.config.ts
new file mode 100644
index 000000000..89edb5029
--- /dev/null
+++ b/packages/cloud/tsdown.standalone.config.ts
@@ -0,0 +1,22 @@
+import { fileURLToPath } from 'node:url'
+
+import { defineConfig } from 'tsdown'
+
+export default defineConfig({
+ entry: { server: './src/runtime/node/main.ts' },
+ platform: 'node',
+ format: ['esm'],
+ dts: false,
+ sourcemap: true,
+ clean: true,
+ outDir: './dist-standalone',
+ target: 'node22',
+ deps: { alwaysBundle: [/.*/], neverBundle: [/^node:/] },
+ inputOptions: {
+ resolve: {
+ alias: {
+ '#cloud': fileURLToPath(new URL('./src', import.meta.url))
+ }
+ }
+ }
+})
diff --git a/packages/docs/.vitepress/sidebars.ts b/packages/docs/.vitepress/sidebars.ts
index 2180c6dc8..0e50366ec 100644
--- a/packages/docs/.vitepress/sidebars.ts
+++ b/packages/docs/.vitepress/sidebars.ts
@@ -129,6 +129,7 @@ export const developmentSidebar = (
{ text: 'Roadmap', link: '/development/roadmap' },
{ text: 'AI Chat Replies', link: '/development/ai-chat' },
{ text: 'Behaviours and Preview', link: '/development/behaviours-and-preview' },
+ { text: 'Cloud Architecture', link: '/development/cloud' },
{ text: 'Navigation Performance', link: '/development/navigation-performance' },
{ text: 'Renderer Lifecycle', link: '/development/renderer-lifecycle' },
{ text: 'Renderer Profiler', link: '/development/renderer-profiler' },
diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.md
new file mode 100644
index 000000000..80ac52a8c
--- /dev/null
+++ b/packages/docs/development/cloud.md
@@ -0,0 +1,123 @@
+# Cloud Architecture
+
+OpenPencil Cloud is an optional, self-hostable backend for storing, sharing, and collaborating on
+documents. The editor stays local-first: opening, editing, and saving local files never needs this
+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.
+
+```mermaid
+flowchart LR
+ Editor[Editor and desktop app] -->|typed client| API[Hono server]
+ API --> Auth[Better Auth sessions]
+ API --> Policy[OpenFeature policy]
+ API --> PG[(PostgreSQL metadata)]
+ API -->|presigned URLs| S3[(S3-compatible objects)]
+ Editor -->|presigned PUT and GET| S3
+ Workers[Cleanup and email workers] --> PG
+ Workers --> S3
+ Workers --> SMTP[SMTP]
+```
+
+## Package boundaries
+
+| Subpath | Contents |
+| --------------------------------- | -------------------------------------------------------------------------- |
+| `@open-pencil/cloud/contract` | Valibot schemas and types shared by every side of the network |
+| `@open-pencil/cloud/client` | Discovery, authentication, device authorization, and the typed Hono client |
+| `@open-pencil/cloud/email` | Vue Email rendering for transactional mail |
+| `@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 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.
+
+## Documents and revisions
+
+PostgreSQL stores workspaces, membership, documents, revisions, uploads, sharing, and quota state.
+Object storage stores immutable `.fig` revisions; a document points at its current revision, and every
+revision has its own object key.
+
+- Uploads go straight from the client to object storage through presigned single or multipart PUTs.
+ The server verifies a SHA-256 digest before committing; ETags only complete multipart uploads.
+- Each upload names the revision it was based on, so a stale base is rejected instead of silently
+ overwriting a newer revision. The client then chooses: take the Cloud revision, keep both, or
+ replace it.
+- Deleting a document is immediate for users; the cleanup worker removes revisions and objects once
+ the retention period passes.
+
+## Authentication and authorization
+
+Better Auth owns users, sessions, social sign-in, email and password, passkeys, TOTP, and recovery
+codes. OpenPencil owns workspace and document authorization. For clients that cannot host a browser
+redirect, such as the desktop app, the server supports the OAuth device authorization flow and
+accepts the resulting bearer token.
+
+Access to a document comes from ownership, workspace membership, a direct grant, or a capability
+link, and the strongest source wins. Revoking one source leaves access inherited from another.
+Documents granted to someone outside their own workspaces are listed for them separately, so a
+client can show what was shared with them.
+
+Database rows use UUIDs. Capability secrets and invitation tokens are random hex; only their SHA-256
+digests are stored, and they travel in URL fragments so they never reach access logs or `Referer`
+headers. Invitation continuations through OAuth are single-use compact JWE.
+
+Collaboration tickets are signed, epoch-scoped JWTs naming the principal and permission. Rotating a
+capability secret keeps the current epoch; revoking access advances it so old tickets stop working.
+
+## Enrollment and administration
+
+Enrollment is `open`, `approval`, or `closed`. In approval mode a verified identity creates a
+pending request that a deployment administrator approves or rejects; approval can be revoked later.
+Deployment administrators are separate from workspace administrators, and startup never grants
+either role: the first operator is approved and promoted through the `admin` command.
+
+## Configuration
+
+Operators author one schema-versioned TOML file. It owns URLs, trusted origins and proxies,
+authentication providers, enrollment, object storage, email, worker schedules, retention,
+entitlements, and technical limits. Environment variables only supply secrets, through references
+such as `{ from_env = "DATABASE_URL" }`, and never override a value the file sets. TOML is parsed
+with `smol-toml` and then validated and normalised by Valibot.
+
+Technical limits are safety ceilings, not entitlements: runtime policy can be stricter but never
+looser.
+
+## Policy, entitlements, and quotas
+
+OpenFeature answers concrete questions such as whether capability links, anonymous viewing, or
+revision history are available, and what a numeric limit is. Its provider reads one entitlement
+source, chosen by `[entitlements] source`: the static table in the deployment TOML, which applies to
+every workspace, or per-workspace rows in the database that the `entitlements` command sets. The two
+are alternatives, not layers. Technical limits cap the file size and participant limits the source
+reports.
+
+Storage quota uses reservations: the upload locks the workspace's quota row, counts committed usage
+plus active reservations, reserves the requested bytes, and commits the verified size when the
+upload finishes. Cleanup releases reservations from abandoned uploads.
+
+## Rate limiting
+
+OpenPencil routes use `hono-rate-limiter` with one PostgreSQL store that atomically increments
+hashed, namespaced keys, so limits hold across instances. Better Auth keeps its own limiter for
+`/api/auth/**`; those routes mount before OpenPencil middleware and are never counted twice.
+
+## Transactional email
+
+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.
+
+## Tests
+
+| Level | Location | Needs |
+| ----------- | ------------------------------------------------------- | ----------------------- |
+| Unit | `packages/cloud/tests/{client,contract,runtime,server}` | nothing |
+| Integration | `packages/cloud/tests/integration`, mirroring `src` | PGlite, in process |
+| End-to-end | `packages/cloud/tests/e2e` | Docker Compose services |
+
+`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.
diff --git a/packages/feedback/package.json b/packages/feedback/package.json
index a7d2305ca..66291aec0 100644
--- a/packages/feedback/package.json
+++ b/packages/feedback/package.json
@@ -11,7 +11,8 @@
},
"exports": {
"./contract": "./src/contract/index.ts",
- "./client": "./src/client.ts"
+ "./client": "./src/client.ts",
+ "./email": "./src/waitlist/email/layout.ts"
},
"scripts": {
"dev": "wrangler dev",
diff --git a/packages/feedback/src/waitlist/email/confirmation.ts b/packages/feedback/src/waitlist/email/confirmation.ts
index c35d670ae..da7e31742 100644
--- a/packages/feedback/src/waitlist/email/confirmation.ts
+++ b/packages/feedback/src/waitlist/email/confirmation.ts
@@ -19,8 +19,7 @@ const ConfirmationEmail = defineComponent({
actionURL: props.confirmURL,
note: {
text: 'Did not sign up? Ignore this email and the address is deleted in seven days, or',
- linkLabel: 'remove it now',
- linkURL: props.leaveURL
+ link: { label: 'remove it now', url: props.leaveURL }
}
})
}
diff --git a/packages/feedback/src/waitlist/email/layout.ts b/packages/feedback/src/waitlist/email/layout.ts
index 695e2a3d9..9b8e09f17 100644
--- a/packages/feedback/src/waitlist/email/layout.ts
+++ b/packages/feedback/src/waitlist/email/layout.ts
@@ -71,10 +71,18 @@ export type EmailLayoutProps = {
actionLabel: string
actionURL: string
/** Small print under the button, with an optional link at its end. */
- note: { text: string; linkLabel: string; linkURL: string }
+ note?: { text: string; link?: { label: string; url: string } }
}
+function noteContent(note: NonNullable<EmailLayoutProps['note']>) {
+ if (!note.link) return note.text
+ const { label, url } = note.link
+ return [`${note.text} `, h(Link, { href: url, style: styles.link }, () => label), '.']
+}
+
+/** The branded email every OpenPencil service sends: the waitlist and Cloud alike. */
export function emailLayout(props: EmailLayoutProps): VNode {
+ const { note } = props
return h(HTML, { lang: 'en' }, () => [
h(Head),
h(Preview, () => props.preview),
@@ -86,11 +94,7 @@ export function emailLayout(props: EmailLayoutProps): VNode {
h(Section, () =>
h(Button, { href: props.actionURL, style: styles.button }, () => props.actionLabel)
),
- h(Text, { style: styles.note }, () => [
- `${props.note.text} `,
- h(Link, { href: props.note.linkURL, style: styles.link }, () => props.note.linkLabel),
- '.'
- ])
+ note ? h(Text, { style: styles.note }, () => noteContent(note)) : null
]),
h(Text, { style: styles.footer }, () => [
'OpenPencil, the open-source design editor · ',
diff --git a/tests/app/shell/support/baseline.test.ts b/tests/app/shell/support/baseline.test.ts
index be1c48d4e..ad63ec5cd 100644
--- a/tests/app/shell/support/baseline.test.ts
+++ b/tests/app/shell/support/baseline.test.ts
@@ -34,7 +34,8 @@ const BROWSER_TSCONFIGS = [
'packages/vue/tsconfig.json',
'packages/dom-css/tsconfig.json',
'packages/fig/tsconfig.json',
- 'packages/pen/tsconfig.json'
+ 'packages/pen/tsconfig.json',
+ 'packages/cloud/tsconfig.json'
]
async function readJSON<T>(schema: v.GenericSchema<unknown, T>, path: string): Promise<T> {
diff --git a/tools/AGENTS.md b/tools/AGENTS.md
index 4299163b2..ff9cdcacd 100644
--- a/tools/AGENTS.md
+++ b/tools/AGENTS.md
@@ -8,7 +8,7 @@ Private tooling lives under `tools/<role>/<domain>/{src,tests}`; Steiger enforce
| `generate/` | Write generated files or artifacts, idempotently | `brand`, `demo`, `tauri-menu`, `authoring-reference`, `visual-oracles`, `landing-posters` |
| `release/` | Build, verify, and publish packages and native artifacts | `package-artifacts`, `release-packages` |
| `ci/` | Consumed by workflows: path classification and gate policy, container images, the review-guidance bot | `policy`, `images`, `pr-review-guidance` |
-| `dev/` | Test running and benchmarks for humans | `unit-tests`, `navigation-benchmark`, `dev-server` |
+| `dev/` | Test running, benchmarks, and local services for humans | `unit-tests`, `navigation-benchmark`, `dev-server`, `cloud` |
- Nothing under `generate/` or `release/` runs from `bun run check` except through a check entrypoint; `generate/authoring-reference` keeps its `check.ts` beside `generate.ts` until it splits.
- Resolve the workspace with `resolveWorkspaceRoot` from `@open-pencil/package-artifacts-tools`, not parent-directory traversal. Keep sibling imports relative.
diff --git a/tools/checks/architecture/src/steiger-rules/support.ts b/tools/checks/architecture/src/steiger-rules/support.ts
index 5e3ee9e41..a021638c2 100644
--- a/tools/checks/architecture/src/steiger-rules/support.ts
+++ b/tools/checks/architecture/src/steiger-rules/support.ts
@@ -51,7 +51,9 @@ export const PACKAGE_ALIASES: Record<string, string> = {
'#cli/': 'packages/cli/src/',
'#mcp/': 'packages/mcp/src/',
'#feedback/': 'packages/feedback/src/',
- '#feedback-tests/': 'packages/feedback/tests/'
+ '#feedback-tests/': 'packages/feedback/tests/',
+ '#cloud/': 'packages/cloud/src/',
+ '#cloud-tests/': 'packages/cloud/tests/'
}
export const PACKAGE_ALIAS_OWNERS: Record<string, string> = {
@@ -66,7 +68,9 @@ export const PACKAGE_ALIAS_OWNERS: Record<string, string> = {
'#cli/': 'packages/cli/',
'#mcp/': 'packages/mcp/src/',
'#feedback/': 'packages/feedback/',
- '#feedback-tests/': 'packages/feedback/tests/'
+ '#feedback-tests/': 'packages/feedback/tests/',
+ '#cloud/': 'packages/cloud/',
+ '#cloud-tests/': 'packages/cloud/tests/'
}
function normalizePath(filePath: string) {
diff --git a/tools/ci/policy/src/policy.ts b/tools/ci/policy/src/policy.ts
index c08f9f65c..367e08262 100644
--- a/tools/ci/policy/src/policy.ts
+++ b/tools/ci/policy/src/policy.ts
@@ -27,7 +27,8 @@ export const CODE_JOBS = [
'storybook',
'native-test-contracts',
'unit-tests',
- 'feedback-tests'
+ 'feedback-tests',
+ 'cloud-tests'
] as const
export const DOCS_JOB = 'documentation'
export const ALWAYS_JOBS = ['commit-messages'] as const
diff --git a/tools/dev/cloud/package.json b/tools/dev/cloud/package.json
new file mode 100644
index 000000000..ddc16e6a7
--- /dev/null
+++ b/tools/dev/cloud/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "@open-pencil/cloud-tools",
+ "private": true,
+ "type": "module",
+ "imports": {
+ "#cloud-dev/*": "./src/*.ts"
+ },
+ "scripts": {
+ "test": "bun test tests"
+ },
+ "dependencies": {
+ "@open-pencil/cloud": "workspace:*",
+ "@open-pencil/package-artifacts-tools": "workspace:*",
+ "@open-pencil/scene-graph": "workspace:*",
+ "smol-toml": "^1.8.0"
+ }
+}
diff --git a/tools/dev/cloud/src/config.ts b/tools/dev/cloud/src/config.ts
new file mode 100644
index 000000000..5432d33ef
--- /dev/null
+++ b/tools/dev/cloud/src/config.ts
@@ -0,0 +1,102 @@
+import { stringify } from 'smol-toml'
+
+import type { CloudDeploymentInput } from '@open-pencil/cloud/server'
+
+export type LocalCloudEndpoints = {
+ cloudURL: string
+ editorURL: string
+ objectStorageURL: string
+ smtpPort: number
+}
+
+/** Deployment settings for one worktree's local Cloud, with open sign-up and captured mail. */
+export function localCloudDeployment(endpoints: LocalCloudEndpoints): CloudDeploymentInput {
+ return {
+ schema_version: 2,
+ deployment: {
+ mode: 'self-hosted',
+ public_url: endpoints.cloudURL,
+ app_url: endpoints.editorURL,
+ indexing: 'deny',
+ trusted_origins: [endpoints.editorURL, endpoints.cloudURL]
+ },
+ database: {},
+ authentication: {
+ enrollment_mode: 'open',
+ admin_notification_emails: [],
+ email_password: {
+ enabled: true,
+ sign_up: true,
+ minimum_password_length: 8,
+ maximum_password_length: 128,
+ verification_link_expires_minutes: 60,
+ password_reset_link_expires_minutes: 60,
+ compromised_password_check: false
+ },
+ mfa: {
+ deployment_admin_required: false,
+ totp_enabled: true,
+ passkeys_enabled: true,
+ recovery_codes_enabled: true,
+ trusted_device_days: 14
+ },
+ passkeys: {
+ rp_id: new URL(endpoints.cloudURL).hostname,
+ rp_name: 'OpenPencil Cloud',
+ origin: endpoints.cloudURL
+ },
+ trusted_proxies: { headers: [], addresses: [] }
+ },
+ object_storage: {
+ endpoint: endpoints.objectStorageURL,
+ region: 'us-east-1',
+ bucket: 'openpencil',
+ force_path_style: true,
+ checksum_verification: 'metadata'
+ },
+ email: {
+ transport: 'smtp',
+ from: 'OpenPencil Cloud <[email protected]>',
+ smtp: { host: '127.0.0.1', port: endpoints.smtpPort, secure: false }
+ },
+ workers: {
+ email: { batch_size: 50, interval_ms: 1000, lease_ms: 300_000, maximum_attempts: 5 },
+ cleanup: {
+ enabled: true,
+ batch_size: 100,
+ interval_ms: 60_000,
+ lease_ms: 300_000,
+ document_retention_days: 30
+ }
+ },
+ entitlements: {
+ source: 'static',
+ documents: { maximum_file_bytes: 1_073_741_824, revision_history: true },
+ storage: { maximum_bytes: 1_099_511_627_776 },
+ sharing: {
+ capability_links: true,
+ anonymous_view: true,
+ anonymous_edit: true,
+ guest_presence: true
+ },
+ collaboration: { enabled: true, maximum_participants: 100 }
+ },
+ technical_limits: {
+ maximum_upload_bytes: 1_073_741_824,
+ maximum_collaboration_message_bytes: 1_048_576,
+ maximum_connections_per_room: 1000
+ }
+ }
+}
+
+export function localCloudDeploymentTOML(endpoints: LocalCloudEndpoints): string {
+ return `${stringify(localCloudDeployment(endpoints))}\n`
+}
+
+export function composeProjectName(branch: string): string {
+ const normalized = branch
+ .toLowerCase()
+ .replaceAll(/[^a-z0-9_-]+/g, '-')
+ .replaceAll(/^-+|-+$/g, '')
+ return `openpencil-cloud-${normalized || 'development'}`
+}
diff --git a/tools/dev/cloud/src/index.ts b/tools/dev/cloud/src/index.ts
new file mode 100644
index 000000000..b8a7f0217
--- /dev/null
+++ b/tools/dev/cloud/src/index.ts
@@ -0,0 +1,162 @@
+import { existsSync } from 'node:fs'
+import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+
+import { resolveWorkspaceRoot } from '@open-pencil/package-artifacts-tools'
+import { randomHex } from '@open-pencil/scene-graph/random'
+
+import { composeProjectName, localCloudDeploymentTOML } from './config'
+
+const root = await resolveWorkspaceRoot(import.meta.dir)
+const composeFile = join(root, 'packages/cloud/deploy/compose.yml')
+const generatedDirectory = join(root, 'packages/cloud/deploy/generated')
+const generatedConfig = join(generatedDirectory, 'openpencil-cloud.local.toml')
+const generatedSecret = join(generatedDirectory, 'auth-secret')
+
+// Development-only credentials shared with compose.yml defaults.
+const POSTGRES_PASSWORD = 'openpencil-development-password'
+const S3_ACCESS_KEY_ID = 'openpencil'
+const S3_SECRET_ACCESS_KEY = 'openpencil-development-secret'
+
+async function output(command: string[]): Promise<string> {
+ const child = Bun.spawn(command, { cwd: root, stdout: 'pipe', stderr: 'pipe' })
+ const [stdout, stderr, exitCode] = await Promise.all([
+ new Response(child.stdout).text(),
+ new Response(child.stderr).text(),
+ child.exited
+ ])
+ if (exitCode !== 0) throw new Error(stderr.trim() || `${command[0]} exited with ${exitCode}`)
+ return stdout.trim()
+}
+
+async function execute(
+ command: string[],
+ options: { allowFailure?: boolean; environment?: Record<string, string | undefined> } = {}
+): Promise<number> {
+ const child = Bun.spawn(command, {
+ cwd: root,
+ env: options.environment,
+ stdout: 'inherit',
+ stderr: 'inherit'
+ })
+ const exitCode = await child.exited
+ if (exitCode !== 0 && !options.allowFailure) {
+ throw new Error(`${command.join(' ')} exited with ${exitCode}`)
+ }
+ return exitCode
+}
+
+function compose(project: string, ...args: string[]): string[] {
+ return ['docker', 'compose', '--project-name', project, '--file', composeFile, ...args]
+}
+
+async function publishedPort(project: string, service: string, port: number): Promise<number> {
+ const address = await output(compose(project, 'port', service, String(port)))
+ const value = Number(address.slice(address.lastIndexOf(':') + 1))
+ if (!Number.isSafeInteger(value) || value < 1) {
+ throw new Error(`Could not resolve the published ${service} port ${port}`)
+ }
+ return value
+}
+
+const portlessURL = (name: string) => output(['bunx', 'portless', 'get', name])
+
+function aliasName(url: string): string {
+ const hostname = new URL(url).hostname
+ if (!hostname.endsWith('.localhost'))
+ throw new Error(`Portless returned an unexpected URL: ${url}`)
+ return hostname.slice(0, -'.localhost'.length)
+}
+
+async function authSecret(): Promise<string> {
+ if (existsSync(generatedSecret)) return (await readFile(generatedSecret, 'utf8')).trim()
+ const secret = randomHex(32)
+ await writeFile(generatedSecret, `${secret}\n`, { mode: 0o600 })
+ return secret
+}
+
+async function start(project: string): Promise<void> {
+ const [cloudURL, mailURL, editorURL] = await Promise.all([
+ portlessURL('cloud.open-pencil'),
+ portlessURL('mail.open-pencil'),
+ portlessURL('open-pencil')
+ ])
+
+ // Port 0 lets Docker pick free loopback ports, so worktrees never collide.
+ const services = {
+ ...process.env,
+ POSTGRES_PORT: '0',
+ SEAWEEDFS_S3_PORT: '0',
+ SEAWEEDFS_MASTER_PORT: '0',
+ MAILPIT_UI_PORT: '0',
+ MAILPIT_SMTP_PORT: '0'
+ }
+ await execute(compose(project, 'up', '--detach', '--wait', 'postgres', 'seaweedfs', 'mailpit'), {
+ environment: services
+ })
+ await execute(compose(project, 'run', '--rm', 'seaweedfs-init'), { environment: services })
+ const [postgresPort, s3Port, mailpitUIPort, smtpPort] = await Promise.all([
+ publishedPort(project, 'postgres', 5432),
+ publishedPort(project, 'seaweedfs', 8333),
+ publishedPort(project, 'mailpit', 8025),
+ publishedPort(project, 'mailpit', 1025)
+ ])
+
+ await mkdir(generatedDirectory, { recursive: true })
+ await writeFile(
+ generatedConfig,
+ localCloudDeploymentTOML({
+ cloudURL,
+ editorURL,
+ objectStorageURL: `http://127.0.0.1:${s3Port}`,
+ smtpPort
+ }),
+ { mode: 0o600 }
+ )
+ await execute(['bunx', 'portless', 'alias', aliasName(mailURL), String(mailpitUIPort), '--force'])
+
+ console.warn(`OpenPencil Cloud: ${cloudURL}`)
+ console.warn(`Captured email: ${mailURL}`)
+ console.warn('Stop the services with `bun run cloud:dev:down`; their data is kept.')
+
+ const exitCode = await execute(
+ [
+ 'bunx',
+ 'portless',
+ 'run',
+ '--name',
+ 'cloud.open-pencil',
+ 'bun',
+ '--watch',
+ 'packages/cloud/src/runtime/node/main.ts'
+ ],
+ {
+ allowFailure: true,
+ environment: {
+ ...process.env,
+ HOST: '127.0.0.1',
+ OPENPENCIL_CLOUD_CONFIG: generatedConfig,
+ DATABASE_URL: `postgresql://openpencil:${POSTGRES_PASSWORD}@127.0.0.1:${postgresPort}/openpencil`,
+ BETTER_AUTH_SECRET: await authSecret(),
+ S3_ACCESS_KEY_ID,
+ S3_SECRET_ACCESS_KEY
+ }
+ }
+ )
+ process.exitCode = exitCode
+}
+
+async function stop(project: string): Promise<void> {
+ await execute(compose(project, 'down'), { allowFailure: true })
+ const mailURL = await portlessURL('mail.open-pencil')
+ await execute(['bunx', 'portless', 'alias', '--remove', aliasName(mailURL)], {
+ allowFailure: true
+ })
+ await rm(generatedConfig, { force: true })
+}
+
+const project = composeProjectName(await output(['git', 'branch', '--show-current']))
+const command = process.argv[2] ?? 'up'
+if (command === 'up') await start(project)
+else if (command === 'down') await stop(project)
+else throw new Error('Usage: bun tools/dev/cloud/src/index.ts [up|down]')
diff --git a/tools/dev/cloud/tests/config.test.ts b/tools/dev/cloud/tests/config.test.ts
new file mode 100644
index 000000000..8cd7d3192
--- /dev/null
+++ b/tools/dev/cloud/tests/config.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, test } from 'bun:test'
+
+import { composeProjectName, localCloudDeploymentTOML } from '#cloud-dev/config'
+
+import { parseCloudDeploymentTOML } from '@open-pencil/cloud/server'
+
+const secrets = {
+ DATABASE_URL: 'postgresql://openpencil:[email protected]:54329/openpencil',
+ BETTER_AUTH_SECRET: 'local-development-secret-at-least-32-characters',
+ S3_ACCESS_KEY_ID: 'openpencil',
+ S3_SECRET_ACCESS_KEY: 'openpencil-development-secret'
+}
+
+describe('local Cloud development configuration', () => {
+ test('points branch URLs at the Compose services published on loopback', () => {
+ const config = parseCloudDeploymentTOML(
+ localCloudDeploymentTOML({
+ cloudURL: 'https://feature.cloud.open-pencil.localhost',
+ editorURL: 'https://feature.open-pencil.localhost',
+ objectStorageURL: 'http://127.0.0.1:41000',
+ smtpPort: 41025
+ }),
+ secrets
+ )
+
+ expect(config).toMatchObject({
+ deployment: 'self-hosted',
+ publicURL: 'https://feature.cloud.open-pencil.localhost',
+ appURL: 'https://feature.open-pencil.localhost',
+ trustedOrigins: [
+ 'https://feature.open-pencil.localhost',
+ 'https://feature.cloud.open-pencil.localhost'
+ ],
+ emailPasswordEnabled: true,
+ emailPasswordSignUpEnabled: true,
+ passkeyRPID: 'feature.cloud.open-pencil.localhost',
+ passkeyOrigin: 'https://feature.cloud.open-pencil.localhost',
+ s3Endpoint: 'http://127.0.0.1:41000',
+ emailTransport: 'smtp',
+ smtpHost: '127.0.0.1',
+ smtpPort: 41025,
+ smtpSecure: false
+ })
+ })
+
+ test('derives a Compose project name from the branch', () => {
+ expect(composeProjectName('feature/cloud auth')).toBe('openpencil-cloud-feature-cloud-auth')
+ expect(composeProjectName('')).toBe('openpencil-cloud-development')
+ })
+})
diff --git a/tools/dev/unit-tests/tests/shards.test.ts b/tools/dev/unit-tests/tests/shards.test.ts
index 57f2800fd..d5db1732d 100644
--- a/tools/dev/unit-tests/tests/shards.test.ts
+++ b/tools/dev/unit-tests/tests/shards.test.ts
@@ -13,7 +13,7 @@ import {
const REPO_ROOT = await resolveWorkspaceRoot(import.meta.dir)
// Packages whose tests run in their own CI job instead of the unit shards.
-const OWN_SUITES = ['packages/harness/', 'packages/feedback/']
+const OWN_SUITES = ['packages/harness/', 'packages/feedback/', 'packages/cloud/']
async function discover(pattern: string): Promise<string[]> {
return Array.fromAsync(new Bun.Glob(pattern).scan({ cwd: REPO_ROOT }))
diff --git a/tsconfig.json b/tsconfig.json
index bf6745826..c0fffade7 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -49,6 +49,12 @@
"#feedback/*": [
"./packages/feedback/src/*"
],
+ "@open-pencil/cloud/*": [
+ "./packages/cloud/src/*"
+ ],
+ "#cloud/*": [
+ "./packages/cloud/src/*"
+ ],
"#dom-css/*": [
"./packages/dom-css/src/*"
],
diff --git a/tsconfig.tests.json b/tsconfig.tests.json
index 9f5311674..c4dbdad55 100644
--- a/tsconfig.tests.json
+++ b/tsconfig.tests.json
@@ -49,6 +49,9 @@
"#feedback/*": [
"./packages/feedback/src/*"
],
+ "@open-pencil/cloud/*": [
+ "./packages/cloud/src/*"
+ ],
"#dom-css/*": [
"./packages/dom-css/src/*"
],
@@ -108,6 +111,12 @@
],
"#cli-tests/*": [
"./packages/cli/tests/*"
+ ],
+ "#cloud/*": [
+ "./packages/cloud/src/*"
+ ],
+ "#cloud-tests/*": [
+ "./packages/cloud/tests/*"
]
},
"types": [