Skip to content

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

feat(cloud): serve the editor from the Cloud server, and let it require signing in (#1385)

Danila Poyarkovad740433e385
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e8fe8332f..9503eabac 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -340,13 +340,19 @@ jobs:
- name: Generate package declarations
run: bun run build:packages
- # The Worker serves the portal as static assets, and every official deployment bundles it.
- - name: Build the Cloud portal and bundle the official Workers
+ # The editor's demo document draws its shader fills at build time in a headless Chromium.
+ - name: Install Chromium for the demo document
+ if: matrix.worker
+ run: bunx playwright install --with-deps chromium
+
+ # The Worker serves the editor and the portal as static assets, and every official
+ # deployment bundles them.
+ - name: Build the Cloud site and bundle the official Workers
if: matrix.worker
run: |
- bun run build:cloud-portal
+ bun run build:cloud
for deployment in packages/cloud/deploy/openpencil/*/; do
- (cd "$deployment" && bunx wrangler deploy --dry-run)
+ (cd "$deployment" && bunx wrangler deploy --dry-run --assets "$GITHUB_WORKSPACE/dist-cloud")
done
- name: Run Cloud end-to-end tests against ${{ matrix.store }}
diff --git a/.github/workflows/cloud.yml b/.github/workflows/cloud.yml
index 600616752..a4ee5f76a 100644
--- a/.github/workflows/cloud.yml
+++ b/.github/workflows/cloud.yml
@@ -33,9 +33,16 @@ jobs:
- uses: ./.github/actions/setup-bun
- # The Worker serves the portal as static assets.
- - name: Build the Cloud portal
- run: bun run build:packages && bun run build:cloud-portal
+ # The editor's demo document draws its shader fills at build time in a headless Chromium.
+ - run: bunx playwright install --with-deps chromium
+
+ # The Worker serves the editor and the portal as static assets. The editor names this
+ # deployment as the official server and, like app.openpencil.dev, sends the daily ping.
+ - name: Build the Cloud site
+ env:
+ VITE_OPENPENCIL_OFFICIAL_CLOUD_URL: ${{ vars.CLOUD_URL }}
+ VITE_OPENPENCIL_FEEDBACK: "on"
+ run: bun run build:packages && bun run build:cloud
# Migrations run before the new code, over the direct connection rather than Hyperdrive. The
# config reads every secret it names, so only this step and the next one see them.
@@ -69,15 +76,22 @@ jobs:
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
workingDirectory: ${{ env.DEPLOYMENT }}
packageManager: bun
- command: deploy --secrets-file ${{ runner.temp }}/cloud-secrets.json
+ command: >-
+ deploy --assets ${{ github.workspace }}/dist-cloud
+ --secrets-file ${{ runner.temp }}/cloud-secrets.json
- name: Check the deployment
env:
CLOUD_URL: ${{ vars.CLOUD_URL }}
# Only a 200 counts: a redirect to a sign-in or access page would mean the Worker isn't there.
+ # Pages are asked for as a browser does; the API is not, so a missing route can't turn into
+ # the editor's page.
run: |
- for path in /health /ready /.well-known/openpencil /auth/sign-in; do
+ for path in /health /ready /.well-known/openpencil / /welcome /auth/sign-in; do
+ accept='application/json'
+ case "$path" in /|/welcome|/auth/*) accept='text/html' ;; esac
status=$(curl --silent --show-error --retry 10 --retry-all-errors --retry-delay 3 \
+ --header "Accept: $accept" \
--output /dev/null --write-out '%{http_code}' "$CLOUD_URL$path")
if [ "$status" != 200 ]; then
echo "::error::$path answered HTTP $status"
diff --git a/.gitignore b/.gitignore
index 9316a0bba..4b3d2e409 100644
--- a/.gitignore
+++ b/.gitignore
@@ -97,5 +97,5 @@ packages/feedback/.dev.vars
# OpenPencil Cloud local and build outputs
packages/cloud/deploy/generated/
packages/cloud/dist-standalone/
-dist-cloud-portal/
+dist-cloud/
dist-metrics/
diff --git a/REUSE.toml b/REUSE.toml
index 6470bc63a..b9986b62e 100644
--- a/REUSE.toml
+++ b/REUSE.toml
@@ -21,7 +21,8 @@ path = [
"src/theme/cloud-portal/**",
"src/views/cloud/**",
"tests/app/cloud-portal/**",
- "vite/cloud-portal.ts",
+ "vite/cloud-site.ts",
+ "vite/metrics.ts",
]
precedence = "override"
SPDX-FileCopyrightText = "2026 Danila Poyarkov and OpenPencil contributors"
diff --git a/bun.lock b/bun.lock
index 428f31314..9995e070e 100644
--- a/bun.lock
+++ b/bun.lock
@@ -116,6 +116,7 @@
"@open-pencil/brand-tools": "workspace:*",
"@open-pencil/demo-tools": "workspace:*",
"@open-pencil/mcp": "workspace:*",
+ "@open-pencil/vite-config": "workspace:*",
"@oxlint/plugins": "1.57.0",
"@playwright/test": "^1.63.0",
"@storybook/addon-a11y": "^10.6.2",
diff --git a/package.json b/package.json
index 1ecc53044..458cfcfe8 100644
--- a/package.json
+++ b/package.json
@@ -54,7 +54,7 @@
"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",
- "build:cloud-portal": "vite build --mode cloud-portal",
+ "build:cloud": "vite build --mode cloud",
"build:metrics": "vite build --mode metrics",
"preview": "vite preview",
"storybook": "storybook dev -p 6006",
@@ -230,6 +230,7 @@
"@open-pencil/brand-tools": "workspace:*",
"@open-pencil/demo-tools": "workspace:*",
"@open-pencil/mcp": "workspace:*",
+ "@open-pencil/vite-config": "workspace:*",
"@oxlint/plugins": "1.57.0",
"@playwright/test": "^1.63.0",
"@storybook/addon-a11y": "^10.6.2",
diff --git a/packages/cloud/AGENTS.md b/packages/cloud/AGENTS.md
index c33c54aec..b6cdd0ddd 100644
--- a/packages/cloud/AGENTS.md
+++ b/packages/cloud/AGENTS.md
@@ -26,7 +26,7 @@ Optional, self-hostable backend; the design is in `packages/docs/development/clo
## Portal
-- The portal's pages live in the app (`cloud.html`, `src/views/cloud/`, `src/components/cloud-portal/`); this package owns only their paths (`src/contract/portal.ts`) and serving them (`src/runtime/node/portal.ts`). Links the server sends to people point at portal paths on `publicURL`; only the editor itself is on `appURL` (`src/admin/enrollment/email.ts`).
+- The portal's pages live in the app (`cloud.html`, `src/views/cloud/`, `src/components/cloud-portal/`); this package owns only their paths (`src/contract/portal.ts`) and serving them beside the editor (`src/runtime/site/server.ts`). Links the server sends to people point at portal paths on `publicURL`; only the editor itself is on `appURL`, which defaults to `publicURL` (`src/admin/enrollment/email.ts`).
## Configuration
diff --git a/packages/cloud/deploy/.env.example b/packages/cloud/deploy/.env.example
index e342b6bca..d4364a0b4 100644
--- a/packages/cloud/deploy/.env.example
+++ b/packages/cloud/deploy/.env.example
@@ -1,7 +1,7 @@
# The Node runtime reads durable settings from this TOML file.
OPENPENCIL_CLOUD_CONFIG=./openpencil-cloud.toml
-# The portal build (`bun run build:cloud-portal`): sign-in, account, and administration pages.
-OPENPENCIL_CLOUD_PORTAL_DIR=./dist-cloud-portal
+# The site build (`bun run build:cloud`): the editor, sign-in, account, and administration pages.
+OPENPENCIL_CLOUD_SITE_DIR=./dist-cloud
PORT=8787
# Required secrets. The conventional names below are the TOML defaults.
diff --git a/packages/cloud/deploy/README.md b/packages/cloud/deploy/README.md
index 6238b469d..6207caf11 100644
--- a/packages/cloud/deploy/README.md
+++ b/packages/cloud/deploy/README.md
@@ -42,7 +42,7 @@ bun --filter @open-pencil/cloud test:e2e:garage # Garage S3 compatibility
bun --filter @open-pencil/cloud test:e2e:cloudflare # the Worker under wrangler dev
```
-The Cloudflare run needs `dist-cloud-portal/` (`bun run build:cloud-portal`), which the Worker serves.
+The Cloudflare run needs `dist-cloud/` (`bun run build:cloud`), which the Worker serves.
Each runner starts an isolated Compose project and removes it with its volumes afterwards. The main
suite checks object-store readiness, a presigned single PUT and a 33 MiB three-part multipart upload
diff --git a/packages/cloud/deploy/cloudflare/wrangler.jsonc b/packages/cloud/deploy/cloudflare/wrangler.jsonc
index 95698c265..d3ef7337d 100644
--- a/packages/cloud/deploy/cloudflare/wrangler.jsonc
+++ b/packages/cloud/deploy/cloudflare/wrangler.jsonc
@@ -1,20 +1,19 @@
// OpenPencil Cloud on Cloudflare Workers. To deploy, copy this folder next to it (for example to
// deploy/mine), add your deployment TOML as openpencil-cloud.toml, replace the values marked below,
-// and run `wrangler deploy` there. The self-hosting guide walks through it.
+// and run `wrangler deploy --assets "$(git rev-parse --show-toplevel)/dist-cloud"` there. The
+// self-hosting guide walks through it.
{
- "$schema": "../../node_modules/wrangler/config-schema.json",
"name": "openpencil-cloud",
"main": "worker.ts",
"compatibility_date": "2026-10-01",
"compatibility_flags": ["nodejs_compat"],
- "tsconfig": "../../src/runtime/cloudflare/tsconfig.json",
// The deployment TOML is bundled as text and parsed when the Worker starts.
"rules": [{ "type": "Text", "globs": ["**/*.toml"], "fallthrough": false }],
"observability": { "enabled": true },
- // The Cloud portal from `bun run build:cloud-portal` at the repository root. The Worker always
- // answers first: API routes win, portal pages get `cloud.html`, and only then files.
+ // The editor and the portal from `bun run build:cloud`, which `--assets` names. The Worker always
+ // answers first: API routes win, portal pages get `cloud.html`, then files, and any other page
+ // the editor's `index.html`.
"assets": {
- "directory": "../../../../dist-cloud-portal",
"binding": "ASSETS",
"html_handling": "none",
"run_worker_first": true
diff --git a/packages/cloud/deploy/openpencil-cloud.example.toml b/packages/cloud/deploy/openpencil-cloud.example.toml
index 33e42a5ef..7b11d1d0d 100644
--- a/packages/cloud/deploy/openpencil-cloud.example.toml
+++ b/packages/cloud/deploy/openpencil-cloud.example.toml
@@ -3,9 +3,13 @@ schema_version = 2
[deployment]
mode = "self-hosted"
public_url = "http://localhost:8787"
-app_url = "http://localhost:5173"
indexing = "deny"
-trusted_origins = ["http://localhost:5173"]
+# The server serves the editor itself. Name another editor only when people use one elsewhere,
+# and trust every editor origin besides public_url.
+# app_url = "https://editor.example.com"
+# trusted_origins = ["https://editor.example.com"]
+# The editor works with files on the device without signing in; false asks everyone to sign in.
+local_editor = true
# 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" }
@@ -13,31 +17,32 @@ trusted_origins = ["http://localhost:5173"]
# Defaults to DATABASE_URL.
[database]
-[authentication]
-enrollment_mode = "open"
-admin_notification_emails = []
# The signing secret defaults to BETTER_AUTH_SECRET.
+[authentication]
+
+# "open", "approval" (an administrator reviews each new account), or "closed".
+[authentication.enrollment]
+mode = "open"
+notification_emails = []
[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"
+required_for_admins = false
+totp = false
+recovery_codes = false
+trusted_device_lifetime_days = 14
+
+# Passkeys belong to public_url's host.
+[authentication.passkeys]
+enabled = false
+rp_name = "OpenPencil Cloud"
[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
+verification_link_lifetime_minutes = 60
+password_reset_link_lifetime_minutes = 60
compromised_password_check = false
# Recommended when enabling public sign-up. TURNSTILE_SECRET_KEY remains external.
@@ -70,12 +75,20 @@ bucket = "openpencil"
force_path_style = true
checksum_verification = "metadata"
# Credentials default to S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY.
+maximum_upload_bytes = 1073741824
-# The collaboration relay is served on the API origin. Set this only when clients reach it
-# through a different URL, such as a separate proxy.
-# [collaboration]
+[collaboration]
+# One WebSocket message on the relay, at least 262160. Larger edits arrive as 256 KiB fragments.
+maximum_message_bytes = 1048576
+maximum_connections_per_room = 1000
+# The relay is served on the API origin. Set this only when clients reach it through a different
+# URL, such as a separate proxy.
# relay_url = "wss://relay.example.com/api/collaboration/relay"
+# How long deleted documents stay restorable.
+[documents]
+retention_days = 30
+
[email]
transport = "none"
@@ -107,7 +120,6 @@ enabled = true
batch_size = 100
interval_ms = 60000
lease_ms = 300000
-document_retention_days = 30
[entitlements]
source = "static"
@@ -120,10 +132,11 @@ revision_history = true
[entitlements.storage]
maximum_bytes = 1_099_511_627_776
+# Links work for people signed in to the server; guests are people who follow them without.
[entitlements.sharing]
-capability_links = true
-anonymous_view = true
-anonymous_edit = true
+links = true
+guest_view = true
+guest_edit = true
guest_presence = true
[entitlements.collaboration]
@@ -135,9 +148,3 @@ maximum_participants = 100
[entitlements.ai]
enabled = false
# monthly_credit_allowance = 10000
-
-[technical_limits]
-maximum_upload_bytes = 1073741824
-# One WebSocket message on the relay, at least 262160. Larger edits arrive as 256 KiB fragments.
-maximum_collaboration_message_bytes = 1048576
-maximum_connections_per_room = 1000
diff --git a/packages/cloud/deploy/openpencil/staging/openpencil-cloud.toml b/packages/cloud/deploy/openpencil/staging/openpencil-cloud.toml
index 18fe23892..fbba81cab 100644
--- a/packages/cloud/deploy/openpencil/staging/openpencil-cloud.toml
+++ b/packages/cloud/deploy/openpencil/staging/openpencil-cloud.toml
@@ -3,25 +3,18 @@
# S3_SECRET_ACCESS_KEY; DATABASE_URL is Hyperdrive's.
schema_version = 2
+# Staging is only for people the team approved: no editor or shared files without signing in.
[deployment]
mode = "official"
public_url = "https://cloud-staging.openpencil.dev"
-app_url = "https://app.openpencil.dev"
indexing = "deny"
-trusted_origins = ["https://app.openpencil.dev", "https://cloud-staging.openpencil.dev"]
+local_editor = false
[database]
-[authentication]
-enrollment_mode = "approval"
-admin_notification_emails = ["[email protected]"]
-
-[authentication.mfa]
-deployment_admin_required = false
-totp_enabled = false
-passkeys_enabled = false
-recovery_codes_enabled = false
-trusted_device_days = 14
+[authentication.enrollment]
+mode = "approval"
+notification_emails = ["[email protected]"]
[authentication.email_password]
enabled = false
@@ -40,23 +33,13 @@ bucket = "openpencil-cloud-staging"
force_path_style = true
checksum_verification = "metadata"
+[documents]
+retention_days = 30
+
[email]
transport = "cloudflare"
-[workers.email]
-batch_size = 50
-interval_ms = 30000
-lease_ms = 300000
-maximum_attempts = 5
-
-[workers.cleanup]
-enabled = true
-batch_size = 100
-interval_ms = 60000
-lease_ms = 300000
-document_retention_days = 30
-
[entitlements]
source = "static"
@@ -68,10 +51,10 @@ revision_history = true
maximum_bytes = 107_374_182_400
[entitlements.sharing]
-capability_links = true
-anonymous_view = true
-anonymous_edit = true
-guest_presence = true
+links = true
+guest_view = false
+guest_edit = false
+guest_presence = false
[entitlements.collaboration]
enabled = true
diff --git a/packages/cloud/deploy/openpencil/staging/wrangler.jsonc b/packages/cloud/deploy/openpencil/staging/wrangler.jsonc
index 4da9951ab..6c5dba528 100644
--- a/packages/cloud/deploy/openpencil/staging/wrangler.jsonc
+++ b/packages/cloud/deploy/openpencil/staging/wrangler.jsonc
@@ -1,16 +1,14 @@
// cloud-staging.openpencil.dev, deployed by the Deploy Cloud workflow with target `staging`: a
-// filled-in copy of ../../cloudflare. For a deployment of your own, copy that folder instead.
+// filled-in copy of deploy/cloudflare. For a deployment of your own, copy that folder instead.
{
- "$schema": "../../../node_modules/wrangler/config-schema.json",
"name": "openpencil-cloud-staging",
"main": "worker.ts",
"compatibility_date": "2026-10-01",
"compatibility_flags": ["nodejs_compat"],
- "tsconfig": "../../../src/runtime/cloudflare/tsconfig.json",
"rules": [{ "type": "Text", "globs": ["**/*.toml"], "fallthrough": false }],
"observability": { "enabled": true },
+ // The site build comes from `--assets`.
"assets": {
- "directory": "../../../../../dist-cloud-portal",
"binding": "ASSETS",
"html_handling": "none",
"run_worker_first": true
diff --git a/packages/cloud/src/contract/discovery.ts b/packages/cloud/src/contract/discovery.ts
index 721ec3a32..5fbc14e06 100644
--- a/packages/cloud/src/contract/discovery.ts
+++ b/packages/cloud/src/contract/discovery.ts
@@ -60,6 +60,8 @@ export const cloudDiscoverySchema = v.object({
apiURL: v.pipe(v.string(), v.url()),
authURL: v.pipe(v.string(), v.url()),
appURL: v.optional(v.pipe(v.string(), v.url())),
+ /** Whether the server's own editor works with files on this device without signing in. */
+ localEditor: v.optional(v.boolean(), true),
authentication: cloudAuthenticationSchema,
capabilities: cloudCapabilitiesSchema,
listing: v.optional(cloudListingSchema),
diff --git a/packages/cloud/src/contract/entitlements.ts b/packages/cloud/src/contract/entitlements.ts
index cbcf3bbd8..bc0abc229 100644
--- a/packages/cloud/src/contract/entitlements.ts
+++ b/packages/cloud/src/contract/entitlements.ts
@@ -2,9 +2,9 @@ import * as v from 'valibot'
export const workspaceEntitlementsSchema = v.object({
features: v.object({
- capabilityLinks: v.boolean(),
- anonymousView: v.boolean(),
- anonymousEdit: v.boolean(),
+ links: v.boolean(),
+ guestView: v.boolean(),
+ guestEdit: v.boolean(),
guestPresence: v.boolean(),
collaboration: v.boolean(),
revisionHistory: v.boolean(),
diff --git a/packages/cloud/src/contract/portal.ts b/packages/cloud/src/contract/portal.ts
index 8fd73c8a3..dd892970d 100644
--- a/packages/cloud/src/contract/portal.ts
+++ b/packages/cloud/src/contract/portal.ts
@@ -1,14 +1,17 @@
/**
- * The pages a Cloud server shows on its own address: sign-in, desktop sign-in approval, account
- * settings, and the administration console. Every runtime serves the portal's `cloud.html` at
- * and below these paths, and at the server's root, which the portal sends on to its home;
- * everything else reaches the API.
+ * The pages a Cloud server shows on its own address, apart from the editor: the welcome page for
+ * visitors who are not signed in, sign-in, desktop sign-in approval, account settings, and the
+ * administration console. Every runtime serves the portal's `cloud.html` at and below these
+ * paths, and the editor's `index.html` at the root and at any other page the API does not answer.
*/
-export const CLOUD_PORTAL_PAGE_ROOTS = ['/auth', '/cloud/device', '/account', '/admin'] as const
+export const CLOUD_PORTAL_PAGE_ROOTS = [
+ '/welcome',
+ '/auth',
+ '/cloud/device',
+ '/account',
+ '/admin'
+] as const
export function isCloudPortalPage(path: string): boolean {
- return (
- path === '/' ||
- CLOUD_PORTAL_PAGE_ROOTS.some((root) => path === root || path.startsWith(`${root}/`))
- )
+ return CLOUD_PORTAL_PAGE_ROOTS.some((root) => path === root || path.startsWith(`${root}/`))
}
diff --git a/packages/cloud/src/runtime/cloudflare/environment.ts b/packages/cloud/src/runtime/cloudflare/environment.ts
index be771e896..d18e95090 100644
--- a/packages/cloud/src/runtime/cloudflare/environment.ts
+++ b/packages/cloud/src/runtime/cloudflare/environment.ts
@@ -14,7 +14,7 @@ export type CloudflareCloudBindings = {
HYPERDRIVE: Hyperdrive
/** The collaboration relay, one object per document. */
RELAY: DurableObjectNamespace<CollaborationRelayRPC>
- /** The built portal, `dist-cloud-portal`. */
+ /** The built site, `dist-cloud`: the editor and the portal. */
ASSETS: Fetcher
/** Required by `[email] transport = "cloudflare"`. */
EMAIL?: SendEmail
diff --git a/packages/cloud/src/runtime/cloudflare/portal.ts b/packages/cloud/src/runtime/cloudflare/site.ts
similarity index 58%
rename from packages/cloud/src/runtime/cloudflare/portal.ts
rename to packages/cloud/src/runtime/cloudflare/site.ts
index 40cd1a723..2afcc90f2 100644
--- a/packages/cloud/src/runtime/cloudflare/portal.ts
+++ b/packages/cloud/src/runtime/cloudflare/site.ts
@@ -1,7 +1,7 @@
-import type { PortalFiles } from '#cloud/runtime/portal/server'
+import type { SiteFiles } from '#cloud/runtime/site/server'
-/** The built portal's files from the Worker's static assets. */
-export function assetPortalFiles(assets: Fetcher): PortalFiles {
+/** The built site's files from the Worker's static assets. */
+export function assetSiteFiles(assets: Fetcher): SiteFiles {
return async (path, request) => {
const file = await assets.fetch(new URL(path, request.url))
if (!file.ok || !file.body) return null
diff --git a/packages/cloud/src/runtime/cloudflare/worker.ts b/packages/cloud/src/runtime/cloudflare/worker.ts
index 4cf19174c..17d0036b9 100644
--- a/packages/cloud/src/runtime/cloudflare/worker.ts
+++ b/packages/cloud/src/runtime/cloudflare/worker.ts
@@ -1,7 +1,7 @@
import { defaultRelayURL, RELAY_PATH } from '#cloud/contract'
-import { createCloudServer } from '#cloud/runtime/portal/server'
import { createPostgresCloudDatabase } from '#cloud/runtime/postgres/database'
import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
+import { createCloudServer } from '#cloud/runtime/site/server'
import {
cleanupPassOptions,
createCleanupServices,
@@ -21,8 +21,8 @@ import {
type CloudflareCloudEnvironment,
type PreparedCloudflareCloud
} from './environment'
-import { assetPortalFiles } from './portal'
import { createCloudflareRelayObject, relayFor, routeToRelay } from './relay'
+import { assetSiteFiles } from './site'
function emailTransport({ config }: PreparedCloudflareCloud, env: CloudflareCloudEnvironment) {
if (config.emailTransport !== 'cloudflare') return undefined
@@ -92,7 +92,7 @@ function cloudServices(
/**
* OpenPencil Cloud on Cloudflare Workers, configured by a deployment TOML. The Worker serves the
- * API and portal per request, a Durable Object per document runs its collaboration rooms, and a
+ * API, the editor, and the portal per request, a Durable Object per document runs its collaboration rooms, and a
* Cron Trigger runs cleanup and retries email.
*/
export function createCloudflareCloud(configSource: string) {
@@ -125,7 +125,7 @@ export function createCloudflareCloud(configSource: string) {
runInBackground(relayFor(c.env, documentId).announceVersions(documentId))
})
return await createCloudServer(app, {
- portal: assetPortalFiles(c.env.ASSETS),
+ site: assetSiteFiles(c.env.ASSETS),
indexingPolicy: config.indexingPolicy
}).fetch(c.req.raw)
} finally {
diff --git a/packages/cloud/src/runtime/node/portal.ts b/packages/cloud/src/runtime/node/portal.ts
deleted file mode 100644
index 31c7785a8..000000000
--- a/packages/cloud/src/runtime/node/portal.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { readFile } from 'node:fs/promises'
-import { resolve, sep } from 'node:path'
-
-import type { PortalFiles } from '#cloud/runtime/portal/server'
-import { getMimeType } from 'hono/utils/mime'
-
-/** The built portal's files in `directory`, never anything outside it. */
-export function nodePortalFiles(directory: string): PortalFiles {
- const root = resolve(directory)
- return async (path) => {
- let decoded: string
- try {
- decoded = decodeURIComponent(path)
- } catch {
- return null
- }
- const type = getMimeType(decoded)
- const file = resolve(root, `.${decoded}`)
- if (!type || !file.startsWith(`${root}${sep}`)) return null
- try {
- return { body: new Uint8Array(await readFile(file)), type }
- } catch {
- return null
- }
- }
-}
diff --git a/packages/cloud/src/runtime/node/server.ts b/packages/cloud/src/runtime/node/server.ts
index c9cc36fa4..2c333b82a 100644
--- a/packages/cloud/src/runtime/node/server.ts
+++ b/packages/cloud/src/runtime/node/server.ts
@@ -1,8 +1,8 @@
import { createServer } from 'node:http'
import { defaultRelayURL } from '#cloud/contract'
-import { createCloudServer } from '#cloud/runtime/portal/server'
import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
+import { createCloudServer } from '#cloud/runtime/site/server'
import {
createCloudApp,
loadAISigningKey,
@@ -20,8 +20,8 @@ import { getRequestListener } from '@hono/node-server'
import { createMigratedNodeCloudDatabase } from './bootstrap'
import { createNodeTransactionalEmailRuntime } from './email/runtime'
-import { nodePortalFiles } from './portal'
import { attachCollaborationRelay } from './relay'
+import { nodeSiteFiles } from './site'
export type NodeCloudServerOptions = {
environment?: Readonly<Record<string, string | undefined>>
@@ -80,11 +80,13 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})
onError: (error) => console.error('[Cloud] Email worker failed:', error)
})
: undefined
- const portalDirectory = environment.OPENPENCIL_CLOUD_PORTAL_DIR
- if (!portalDirectory)
- console.warn('[Cloud] OPENPENCIL_CLOUD_PORTAL_DIR is not set; sign-in pages are off.')
+ const siteDirectory = environment.OPENPENCIL_CLOUD_SITE_DIR
+ if (!siteDirectory)
+ console.warn(
+ '[Cloud] OPENPENCIL_CLOUD_SITE_DIR is not set; the editor and sign-in pages are off.'
+ )
const cloudServer = createCloudServer(app, {
- portal: portalDirectory ? nodePortalFiles(portalDirectory) : undefined,
+ site: siteDirectory ? nodeSiteFiles(siteDirectory) : undefined,
indexingPolicy: config.indexingPolicy
})
const server = await listen(
diff --git a/packages/cloud/src/runtime/node/site.ts b/packages/cloud/src/runtime/node/site.ts
new file mode 100644
index 000000000..9a54ed80a
--- /dev/null
+++ b/packages/cloud/src/runtime/node/site.ts
@@ -0,0 +1,29 @@
+import { readFile } from 'node:fs/promises'
+import { resolve, sep } from 'node:path'
+
+import type { SiteFiles } from '#cloud/runtime/site/server'
+import { getMimeType } from 'hono/utils/mime'
+
+/** The built site's files in `directory`, never anything outside it. */
+export function nodeSiteFiles(directory: string): SiteFiles {
+ const root = resolve(directory)
+ return async (path) => {
+ let decoded: string
+ try {
+ decoded = decodeURIComponent(path)
+ } catch {
+ return null
+ }
+ const file = resolve(root, `.${decoded}`)
+ if (!file.startsWith(`${root}${sep}`)) return null
+ try {
+ return {
+ body: new Uint8Array(await readFile(file)),
+ // Documents such as the editor's demo `.fig` have no registered type.
+ type: getMimeType(decoded) ?? 'application/octet-stream'
+ }
+ } catch {
+ return null
+ }
+ }
+}
diff --git a/packages/cloud/src/runtime/portal/server.ts b/packages/cloud/src/runtime/portal/server.ts
deleted file mode 100644
index 519a094cf..000000000
--- a/packages/cloud/src/runtime/portal/server.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { CLOUD_PORTAL_PAGE_ROOTS } from '#cloud/contract'
-import { withIndexingPolicy } from '#cloud/server'
-import { Hono } from 'hono'
-
-/** A file of the built portal (`bun run build:cloud-portal`). */
-export type PortalFile = { body: ReadableStream | Uint8Array<ArrayBuffer>; type: string }
-
-/** Reads the built portal's file at a URL path, or null when there is none. */
-export type PortalFiles = (path: string, request: Request) => Promise<PortalFile | null>
-
-const PAGE_PATH = '/cloud.html'
-
-const PAGE_HEADERS = {
- 'Content-Type': 'text/html; charset=utf-8',
- 'Cache-Control': 'no-cache',
- // Desktop sign-in approval must never be framed by another site.
- 'Content-Security-Policy': "frame-ancestors 'none'",
- 'Referrer-Policy': 'no-referrer',
- 'X-Content-Type-Options': 'nosniff'
-}
-
-export type CloudServerOptions = {
- /** The built portal; without it, sign-in, account, and administration pages answer 404. */
- portal?: PortalFiles
- indexingPolicy: 'allow' | 'deny'
-}
-
-/**
- * A Cloud server as every runtime serves it: the portal's `cloud.html` at portal pages, the API
- * everywhere else, and the portal's assets and icons where the API has nothing.
- */
-export function createCloudServer(
- api: { fetch(request: Request): Response | Promise<Response> },
- { portal, indexingPolicy }: CloudServerOptions
-) {
- const server = new Hono()
- server.use(async (c, next) => {
- await next()
- c.res = withIndexingPolicy(c.res, c.req.path, indexingPolicy)
- })
- if (portal) {
- const pages = ['/', ...CLOUD_PORTAL_PAGE_ROOTS.flatMap((root) => [root, `${root}/*`])]
- server.on(['GET', 'HEAD'], pages, async (c) => {
- const page = await portal(PAGE_PATH, c.req.raw)
- return page ? c.body(page.body, 200, PAGE_HEADERS) : c.notFound()
- })
- server.on(['GET', 'HEAD'], '*', async (c, next) => {
- await next()
- if (c.res.status !== 404 || c.req.path === PAGE_PATH) return
- const file = await portal(c.req.path, c.req.raw)
- if (!file) return
- c.res = new Response(file.body, {
- headers: {
- 'Content-Type': file.type,
- 'Cache-Control': c.req.path.startsWith('/assets/')
- ? 'public, max-age=31536000, immutable'
- : 'public, max-age=3600',
- 'X-Content-Type-Options': 'nosniff'
- }
- })
- })
- }
- server.all('*', (c) => api.fetch(c.req.raw))
- return server
-}
diff --git a/packages/cloud/src/runtime/site/server.ts b/packages/cloud/src/runtime/site/server.ts
new file mode 100644
index 000000000..8509976a9
--- /dev/null
+++ b/packages/cloud/src/runtime/site/server.ts
@@ -0,0 +1,77 @@
+import { CLOUD_PORTAL_PAGE_ROOTS } from '#cloud/contract'
+import { withIndexingPolicy } from '#cloud/server'
+import { Hono } from 'hono'
+
+/** A file of the built Cloud site (`bun run build:cloud`): the editor and the portal. */
+export type SiteFile = { body: ReadableStream | Uint8Array<ArrayBuffer>; type: string }
+
+/** Reads the built site's file at a URL path, or null when there is none. */
+export type SiteFiles = (path: string, request: Request) => Promise<SiteFile | null>
+
+const PORTAL_PAGE = '/cloud.html'
+const EDITOR_PAGE = '/index.html'
+
+const PAGE_HEADERS = {
+ 'Content-Type': 'text/html; charset=utf-8',
+ 'Cache-Control': 'no-cache',
+ // Desktop sign-in approval and the editor must never be framed by another site.
+ 'Content-Security-Policy': "frame-ancestors 'none'",
+ 'Referrer-Policy': 'no-referrer',
+ 'X-Content-Type-Options': 'nosniff'
+}
+
+export type CloudServerOptions = {
+ /** The built site; without it, the server answers only its API. */
+ site?: SiteFiles
+ indexingPolicy: 'allow' | 'deny'
+}
+
+function cacheControl(path: string): string {
+ if (path.startsWith('/assets/')) return 'public, max-age=31536000, immutable'
+ return 'public, max-age=3600'
+}
+
+/**
+ * A Cloud server as every runtime serves it: the portal's `cloud.html` at portal pages, the API
+ * everywhere else, and, where the API has nothing, the site's files, or the editor's
+ * `index.html` for any other page, whose router knows the editor's own addresses.
+ */
+export function createCloudServer(
+ api: { fetch(request: Request): Response | Promise<Response> },
+ { site, indexingPolicy }: CloudServerOptions
+) {
+ const server = new Hono()
+ server.use(async (c, next) => {
+ await next()
+ c.res = withIndexingPolicy(c.res, c.req.path, indexingPolicy)
+ })
+ if (site) {
+ const pages = CLOUD_PORTAL_PAGE_ROOTS.flatMap((root) => [root, `${root}/*`])
+ server.on(['GET', 'HEAD'], pages, async (c) => {
+ const page = await site(PORTAL_PAGE, c.req.raw)
+ return page ? c.body(page.body, 200, PAGE_HEADERS) : c.notFound()
+ })
+ server.on(['GET', 'HEAD'], '*', async (c, next) => {
+ await next()
+ if (c.res.status !== 404) return
+ const file = await site(c.req.path, c.req.raw)
+ if (file) {
+ c.res = file.type.startsWith('text/html')
+ ? new Response(file.body, { headers: PAGE_HEADERS })
+ : new Response(file.body, {
+ headers: {
+ 'Content-Type': file.type,
+ 'Cache-Control': cacheControl(c.req.path),
+ 'X-Content-Type-Options': 'nosniff'
+ }
+ })
+ return
+ }
+ if (!c.req.header('Accept')?.includes('text/html')) return
+ const editor = await site(EDITOR_PAGE, c.req.raw)
+ if (editor) c.res = new Response(editor.body, { headers: PAGE_HEADERS })
+ })
+ }
+ server.all('*', (c) => api.fetch(c.req.raw))
+ return server
+}
diff --git a/packages/cloud/src/server/api/router.ts b/packages/cloud/src/server/api/router.ts
index 831b75ebf..d810d1cc8 100644
--- a/packages/cloud/src/server/api/router.ts
+++ b/packages/cloud/src/server/api/router.ts
@@ -39,8 +39,11 @@ export type CloudAPIServices = {
export function createPublicCloudAPIRouter(services: CloudAPIServices) {
return new Hono<CloudAPIEnvironment>()
- .route('/', createPublicSharingRoutes(services.sharing))
- .route('/', createPublicDocumentRoutes(services.sharing, services.documents))
+ .route('/', createPublicSharingRoutes(services.sharing, services.resolveSession))
+ .route(
+ '/',
+ createPublicDocumentRoutes(services.sharing, services.documents, services.resolveSession)
+ )
.route('/', createPublicCollaborationRoutes(services.collaboration, services.resolveSession))
}
diff --git a/packages/cloud/src/server/auth/factory.ts b/packages/cloud/src/server/auth/factory.ts
index 8c04dfb98..b147adcfa 100644
--- a/packages/cloud/src/server/auth/factory.ts
+++ b/packages/cloud/src/server/auth/factory.ts
@@ -282,15 +282,11 @@ export function createBetterAuthAdapter(
}
}),
passkey({
- rpID: config.passkeyRPID ?? new URL(config.publicURL).hostname,
+ rpID: new URL(config.publicURL).hostname,
rpName: config.passkeyRPName,
- origin: config.passkeyOrigin ?? new URL(config.publicURL).origin
+ origin: new URL(config.publicURL).origin
}),
- admin(
- config.deploymentAdminUserIds.length > 0
- ? { adminUserIds: config.deploymentAdminUserIds }
- : {}
- ),
+ admin(),
// Device authorization returns opaque database session tokens, not signed cookies.
bearer(),
deviceAuthorization({
@@ -306,11 +302,9 @@ export function createBetterAuthAdapter(
]
})
- // Better Auth's admin plugin treats `adminUserIds` as administrators too, so Cloud does the same.
+ // Administrators are granted only through the `admin` command or by another administrator.
const deploymentRole = (user: { id: string; role?: string | null }) =>
- user.role === 'admin' || config.deploymentAdminUserIds.includes(user.id)
- ? ('admin' as const)
- : ('user' as const)
+ user.role === 'admin' ? ('admin' as const) : ('user' as const)
const resolveIdentity = async (headers: Headers) => {
const session = await auth.api.getSession({ headers })
diff --git a/packages/cloud/src/server/collaboration/routes.ts b/packages/cloud/src/server/collaboration/routes.ts
index 0f31416b8..462909712 100644
--- a/packages/cloud/src/server/collaboration/routes.ts
+++ b/packages/cloud/src/server/collaboration/routes.ts
@@ -4,7 +4,7 @@ import type { CollaborationTicketService } from '#cloud/server/collaboration/ser
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 { DocumentShareInvalidError, DocumentShareSignInRequiredError } from '#cloud/server/sharing'
import { validatedJSON } from '#cloud/server/validation'
import { Hono, type Context } from 'hono'
import type { Kysely } from 'kysely'
@@ -15,6 +15,9 @@ 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)
}
+ if (error instanceof DocumentShareSignInRequiredError) {
+ return context.json({ error: { code: 'unauthorized' as const } }, 401)
+ }
return null
}
diff --git a/packages/cloud/src/server/config/deployment.ts b/packages/cloud/src/server/config/deployment.ts
index d19b86995..e1c8276eb 100644
--- a/packages/cloud/src/server/config/deployment.ts
+++ b/packages/cloud/src/server/config/deployment.ts
@@ -83,7 +83,7 @@ function workerConfig(config: CloudDeploymentConfig) {
cleanupBatchSize: cleanup?.batch_size,
cleanupIntervalMs: cleanup?.interval_ms,
cleanupLeaseDurationMs: cleanup?.lease_ms,
- documentRetentionMs: cleanup ? cleanup.document_retention_days * 86_400_000 : undefined
+ documentRetentionMs: config.documents.retention_days * 86_400_000
}
}
@@ -99,13 +99,12 @@ function serviceConfig(config: CloudDeploymentConfig, environment: CloudEnvironm
}
}
+/** Hard limits, whatever a plan allows; each lives in the section it limits. */
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
+ maximumUploadBytes: config.object_storage.maximum_upload_bytes,
+ maximumCollaborationMessageBytes: config.collaboration.maximum_message_bytes,
+ maximumConnectionsPerRoom: config.collaboration.maximum_connections_per_room
}
}
@@ -120,29 +119,27 @@ export function parseCloudDeploymentConfig(
appURL: config.deployment.app_url,
indexingPolicy: config.deployment.indexing,
trustedOrigins: config.deployment.trusted_origins,
+ localEditor: config.deployment.local_editor,
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,
+ enrollmentMode: config.authentication.enrollment.mode,
+ enrollmentAdminNotificationEmails: config.authentication.enrollment.notification_emails,
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,
+ config.authentication.email_password.verification_link_lifetime_minutes * 60,
passwordResetExpiresIn:
- config.authentication.email_password.password_reset_link_expires_minutes * 60,
+ config.authentication.email_password.password_reset_link_lifetime_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,
+ deploymentAdminMFARequired: config.authentication.mfa.required_for_admins,
+ totpEnabled: config.authentication.mfa.totp,
+ recoveryCodesEnabled: config.authentication.mfa.recovery_codes,
+ mfaTrustedDeviceDays: config.authentication.mfa.trusted_device_lifetime_days,
+ passkeysEnabled: config.authentication.passkeys.enabled,
+ passkeyRPName: config.authentication.passkeys.rp_name,
captchaProvider: config.authentication.captcha?.provider,
captchaSiteKey: config.authentication.captcha?.site_key,
captchaSecretKey: config.authentication.captcha
@@ -165,7 +162,7 @@ export function parseCloudDeploymentConfig(
s3ChecksumVerification: config.object_storage.checksum_verification,
s3ServerSideEncryption: config.object_storage.server_side_encryption,
s3KmsKeyId: config.object_storage.kms_key_id,
- relayURL: config.collaboration?.relay_url,
+ relayURL: config.collaboration.relay_url,
staticEntitlements: staticEntitlements(config),
...emailConfig(config, environment),
...workerConfig(config),
diff --git a/packages/cloud/src/server/config/public.ts b/packages/cloud/src/server/config/public.ts
index 81f88bb00..fc5c6f739 100644
--- a/packages/cloud/src/server/config/public.ts
+++ b/packages/cloud/src/server/config/public.ts
@@ -49,6 +49,7 @@ export function cloudDiscoveryFromConfig(config: CloudServerConfig): CloudDiscov
apiURL: withoutTrailingSlash(new URL('/api', config.publicURL).href),
authURL: withoutTrailingSlash(new URL('/api/auth', config.publicURL).href),
appURL: config.appURL ?? config.publicURL,
+ localEditor: config.localEditor,
authentication,
capabilities: {
documents: true,
diff --git a/packages/cloud/src/server/config/schema.ts b/packages/cloud/src/server/config/schema.ts
index 7799f04bb..30c55699d 100644
--- a/packages/cloud/src/server/config/schema.ts
+++ b/packages/cloud/src/server/config/schema.ts
@@ -62,6 +62,8 @@ const rawCloudServerConfigSchema = v.object({
databaseURL: v.pipe(v.string(), v.url()),
authSecret: v.pipe(v.string(), v.minLength(32)),
trustedOrigins: v.optional(v.array(httpURLSchema), []),
+ /** The server's editor works with files on this device without signing in to the server. */
+ localEditor: v.optional(v.boolean(), true),
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'),
@@ -70,7 +72,6 @@ const rawCloudServerConfigSchema = v.object({
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(
@@ -89,9 +90,7 @@ const rawCloudServerConfigSchema = v.object({
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,
@@ -186,15 +185,6 @@ function validateAuthenticationConfig(config: CloudServerConfig): void {
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' &&
@@ -301,13 +291,13 @@ const DEFAULT_SECRET_NAMES = {
const urlSchema = v.pipe(v.string(), v.url())
const textSchema = v.pipe(v.string(), v.trim(), v.minLength(1))
const positiveIntegerSchema = v.pipe(v.number(), v.integer(), v.minValue(1))
-const secretReferenceSchema = v.object({ from_env: textSchema })
+const secretReferenceSchema = v.strictObject({ from_env: textSchema })
const configurableTextSchema = v.union([textSchema, secretReferenceSchema])
const defaultReference = (name: string) => v.optional(secretReferenceSchema, { from_env: name })
-const providerSchema = v.object({
+const providerSchema = v.strictObject({
google: v.optional(
- v.object({
+ v.strictObject({
client_id: v.optional(configurableTextSchema, {
from_env: DEFAULT_SECRET_NAMES.googleClientId
}),
@@ -315,7 +305,7 @@ const providerSchema = v.object({
})
),
apple: v.optional(
- v.object({
+ v.strictObject({
client_id: textSchema,
team_id: textSchema,
key_id: textSchema,
@@ -327,11 +317,11 @@ const providerSchema = v.object({
const emailSchema = v.optional(
v.variant('transport', [
- v.object({ transport: v.literal('none') }),
- v.object({
+ v.strictObject({ transport: v.literal('none') }),
+ v.strictObject({
transport: v.literal('smtp'),
from: textSchema,
- smtp: v.object({
+ smtp: v.strictObject({
host: textSchema,
port: positiveIntegerSchema,
secure: v.optional(v.boolean()),
@@ -343,31 +333,44 @@ const emailSchema = v.optional(
})
})
}),
- v.object({ transport: v.literal('cloudflare'), from: textSchema })
+ v.strictObject({ transport: v.literal('cloudflare'), from: textSchema })
]),
{ transport: 'none' }
)
-export const cloudDeploymentConfigSchema = v.object({
+/**
+ * Every table is strict: a key the schema doesn't know, such as one renamed since, stops startup
+ * instead of leaving its setting at a default the operator never chose.
+ */
+export const cloudDeploymentConfigSchema = v.strictObject({
schema_version: v.literal(2),
- deployment: v.object({
+ deployment: v.strictObject({
mode: v.picklist(['official', 'self-hosted']),
public_url: urlSchema,
app_url: v.optional(urlSchema),
indexing: v.optional(v.picklist(['allow', 'deny']), 'deny'),
trusted_origins: v.optional(v.array(urlSchema), []),
- 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 }
+ // The server's editor works with files on this device without signing in to the server.
+ local_editor: v.optional(v.boolean(), true),
+ listing: v.optional(v.strictObject({ minimum_editor_version: cloudEditorVersionSchema }))
}),
- authentication: v.object({
+ database: v.optional(
+ v.strictObject({ url: defaultReference(DEFAULT_SECRET_NAMES.databaseURL) }),
+ {
+ url: { from_env: DEFAULT_SECRET_NAMES.databaseURL }
+ }
+ ),
+ authentication: v.strictObject({
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(textSchema), []),
+ enrollment: v.optional(
+ v.strictObject({
+ mode: v.optional(v.picklist(['open', 'approval', 'closed']), 'open'),
+ notification_emails: v.optional(v.array(v.pipe(v.string(), v.email())), [])
+ }),
+ { mode: 'open', notification_emails: [] }
+ ),
email_password: v.optional(
- v.object({
+ v.strictObject({
enabled: v.optional(v.boolean(), false),
sign_up: v.optional(v.boolean(), true),
minimum_password_length: v.optional(
@@ -378,8 +381,8 @@ export const cloudDeploymentConfigSchema = v.object({
v.pipe(v.number(), v.integer(), v.minValue(15), v.maxValue(128)),
128
),
- verification_link_expires_minutes: v.optional(positiveIntegerSchema, 60),
- password_reset_link_expires_minutes: v.optional(positiveIntegerSchema, 60),
+ verification_link_lifetime_minutes: v.optional(positiveIntegerSchema, 60),
+ password_reset_link_lifetime_minutes: v.optional(positiveIntegerSchema, 60),
compromised_password_check: v.optional(v.boolean(), false)
}),
{
@@ -387,36 +390,35 @@ export const cloudDeploymentConfigSchema = v.object({
sign_up: true,
minimum_password_length: 8,
maximum_password_length: 128,
- verification_link_expires_minutes: 60,
- password_reset_link_expires_minutes: 60,
+ verification_link_lifetime_minutes: 60,
+ password_reset_link_lifetime_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)
+ v.strictObject({
+ required_for_admins: v.optional(v.boolean(), false),
+ totp: v.optional(v.boolean(), false),
+ recovery_codes: v.optional(v.boolean(), false),
+ trusted_device_lifetime_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
+ required_for_admins: false,
+ totp: false,
+ recovery_codes: false,
+ trusted_device_lifetime_days: 14
}
),
+ // Passkeys belong to public_url's host and origin.
passkeys: v.optional(
- v.object({
- rp_id: textSchema,
- rp_name: v.optional(textSchema, 'OpenPencil Cloud'),
- origin: urlSchema
- })
+ v.strictObject({
+ enabled: v.optional(v.boolean(), false),
+ rp_name: v.optional(textSchema, 'OpenPencil Cloud')
+ }),
+ { enabled: false, rp_name: 'OpenPencil Cloud' }
),
captcha: v.optional(
- v.object({
+ v.strictObject({
provider: v.literal('cloudflare-turnstile'),
site_key: textSchema,
secret_key: defaultReference(DEFAULT_SECRET_NAMES.turnstileSecretKey),
@@ -424,7 +426,7 @@ export const cloudDeploymentConfigSchema = v.object({
})
),
trusted_proxies: v.optional(
- v.object({
+ v.strictObject({
headers: v.optional(v.array(textSchema), []),
addresses: v.optional(v.array(textSchema), [])
}),
@@ -432,12 +434,12 @@ export const cloudDeploymentConfigSchema = v.object({
),
providers: v.optional(providerSchema, {})
}),
- object_storage: v.object({
+ object_storage: v.strictObject({
endpoint: urlSchema,
region: textSchema,
bucket: textSchema,
credentials: v.optional(
- v.object({
+ v.strictObject({
access_key_id: defaultReference(DEFAULT_SECRET_NAMES.s3AccessKeyId),
secret_access_key: defaultReference(DEFAULT_SECRET_NAMES.s3SecretAccessKey),
session_token: v.optional(secretReferenceSchema, {
@@ -452,14 +454,28 @@ export const cloudDeploymentConfigSchema = v.object({
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(textSchema)
+ kms_key_id: v.optional(textSchema),
+ maximum_upload_bytes: v.optional(positiveIntegerSchema)
}),
- collaboration: v.optional(v.object({ relay_url: v.pipe(v.string(), v.url()) })),
+ collaboration: v.optional(
+ v.strictObject({
+ relay_url: v.optional(urlSchema),
+ maximum_message_bytes: v.optional(positiveIntegerSchema),
+ maximum_connections_per_room: v.optional(positiveIntegerSchema)
+ }),
+ {}
+ ),
+ documents: v.optional(
+ v.strictObject({
+ retention_days: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0)), 30)
+ }),
+ { retention_days: 30 }
+ ),
email: emailSchema,
workers: v.optional(
- v.object({
+ v.strictObject({
email: v.optional(
- v.object({
+ v.strictObject({
batch_size: v.optional(positiveIntegerSchema, 50),
interval_ms: v.optional(positiveIntegerSchema, 30_000),
lease_ms: v.optional(positiveIntegerSchema, 300_000),
@@ -468,31 +484,24 @@ export const cloudDeploymentConfigSchema = v.object({
{ batch_size: 50, interval_ms: 30_000, lease_ms: 300_000, maximum_attempts: 5 }
),
cleanup: v.optional(
- v.object({
+ v.strictObject({
enabled: v.optional(v.boolean(), true),
batch_size: v.optional(positiveIntegerSchema, 100),
interval_ms: v.optional(positiveIntegerSchema, 60_000),
- lease_ms: v.optional(positiveIntegerSchema, 300_000),
- document_retention_days: v.optional(v.pipe(v.number(), v.minValue(0)), 30)
+ lease_ms: v.optional(positiveIntegerSchema, 300_000)
}),
- {
- enabled: true,
- batch_size: 100,
- interval_ms: 60_000,
- lease_ms: 300_000,
- document_retention_days: 30
- }
+ { enabled: true, batch_size: 100, interval_ms: 60_000, lease_ms: 300_000 }
)
})
),
entitlements: v.optional(
v.variant('source', [
- v.object({ source: v.literal('static'), ...staticEntitlementsTOMLSchema.entries }),
- v.object({ source: v.literal('database') })
+ v.strictObject({ source: v.literal('static'), ...staticEntitlementsTOMLSchema.entries }),
+ v.strictObject({ source: v.literal('database') })
])
),
ai: v.optional(
- v.object({
+ v.strictObject({
endpoint: urlSchema,
signing_key: defaultReference(DEFAULT_SECRET_NAMES.aiSigningKey),
token_lifetime_minutes: v.optional(
@@ -501,16 +510,9 @@ export const cloudDeploymentConfigSchema = v.object({
)
})
),
- billing: v.optional(v.object({ portal_url: urlSchema })),
+ billing: v.optional(v.strictObject({ portal_url: urlSchema })),
internal_api: v.optional(
- v.object({ service_token: defaultReference(DEFAULT_SECRET_NAMES.internalServiceToken) })
- ),
- technical_limits: v.optional(
- v.object({
- maximum_upload_bytes: v.optional(positiveIntegerSchema),
- maximum_collaboration_message_bytes: v.optional(positiveIntegerSchema),
- maximum_connections_per_room: v.optional(positiveIntegerSchema)
- })
+ v.strictObject({ service_token: defaultReference(DEFAULT_SECRET_NAMES.internalServiceToken) })
)
})
diff --git a/packages/cloud/src/server/index.ts b/packages/cloud/src/server/index.ts
index 91d7fc116..90e0e8311 100644
--- a/packages/cloud/src/server/index.ts
+++ b/packages/cloud/src/server/index.ts
@@ -220,6 +220,7 @@ export {
createPublicSharingRoutes,
decryptContinuationToken,
DocumentShareInvalidError,
+ DocumentShareSignInRequiredError,
encryptContinuationToken,
hashCapability,
type DocumentShareCapability,
diff --git a/packages/cloud/src/server/policy/keys.ts b/packages/cloud/src/server/policy/keys.ts
index 60f413bf6..62db20243 100644
--- a/packages/cloud/src/server/policy/keys.ts
+++ b/packages/cloud/src/server/policy/keys.ts
@@ -1,7 +1,7 @@
export const CLOUD_FEATURE_KEYS = {
- capabilityLinks: 'cloud.sharing.capability-links',
- anonymousView: 'cloud.sharing.anonymous-view',
- anonymousEdit: 'cloud.sharing.anonymous-edit',
+ links: 'cloud.sharing.links',
+ guestView: 'cloud.sharing.guest-view',
+ guestEdit: 'cloud.sharing.guest-edit',
guestPresence: 'cloud.sharing.guest-presence',
collaboration: 'cloud.collaboration.enabled',
serverEnforcedWrites: 'cloud.collaboration.server-enforced-writes',
diff --git a/packages/cloud/src/server/policy/policy.ts b/packages/cloud/src/server/policy/policy.ts
index 0763092a8..22cf63093 100644
--- a/packages/cloud/src/server/policy/policy.ts
+++ b/packages/cloud/src/server/policy/policy.ts
@@ -10,17 +10,17 @@ import {
import { CLOUD_FEATURE_KEYS, type CloudPolicyContext } from './keys'
const DEFAULT_FLAGS = {
- [CLOUD_FEATURE_KEYS.capabilityLinks]: {
+ [CLOUD_FEATURE_KEYS.links]: {
variants: { enabled: true, disabled: false },
defaultVariant: 'enabled',
disabled: false
},
- [CLOUD_FEATURE_KEYS.anonymousView]: {
+ [CLOUD_FEATURE_KEYS.guestView]: {
variants: { enabled: true, disabled: false },
defaultVariant: 'enabled',
disabled: false
},
- [CLOUD_FEATURE_KEYS.anonymousEdit]: {
+ [CLOUD_FEATURE_KEYS.guestEdit]: {
variants: { enabled: true, disabled: false },
defaultVariant: 'enabled',
disabled: false
diff --git a/packages/cloud/src/server/policy/schema.ts b/packages/cloud/src/server/policy/schema.ts
index a408540f9..e46e561b1 100644
--- a/packages/cloud/src/server/policy/schema.ts
+++ b/packages/cloud/src/server/policy/schema.ts
@@ -14,9 +14,9 @@ export const staticEntitlementsSchema = v.object({
storage: v.optional(v.object({ maximumBytes: v.optional(positiveIntegerSchema) }), {}),
sharing: v.optional(
v.object({
- capabilityLinks: v.optional(v.boolean()),
- anonymousView: v.optional(v.boolean()),
- anonymousEdit: v.optional(v.boolean()),
+ links: v.optional(v.boolean()),
+ guestView: v.optional(v.boolean()),
+ guestEdit: v.optional(v.boolean()),
guestPresence: v.optional(v.boolean())
}),
{}
@@ -38,30 +38,30 @@ export const staticEntitlementsSchema = v.object({
})
export type StaticEntitlements = v.InferOutput<typeof staticEntitlementsSchema>
-export const staticEntitlementsTOMLSchema = v.object({
+export const staticEntitlementsTOMLSchema = v.strictObject({
documents: v.optional(
- v.object({
+ v.strictObject({
maximum_file_bytes: v.optional(positiveIntegerSchema),
revision_history: v.optional(v.boolean())
})
),
- storage: v.optional(v.object({ maximum_bytes: v.optional(positiveIntegerSchema) })),
+ storage: v.optional(v.strictObject({ maximum_bytes: v.optional(positiveIntegerSchema) })),
sharing: v.optional(
- v.object({
- capability_links: v.optional(v.boolean()),
- anonymous_view: v.optional(v.boolean()),
- anonymous_edit: v.optional(v.boolean()),
+ v.strictObject({
+ links: v.optional(v.boolean()),
+ guest_view: v.optional(v.boolean()),
+ guest_edit: v.optional(v.boolean()),
guest_presence: v.optional(v.boolean())
})
),
collaboration: v.optional(
- v.object({
+ v.strictObject({
enabled: v.optional(v.boolean()),
maximum_participants: v.optional(positiveIntegerSchema)
})
),
ai: v.optional(
- v.object({
+ v.strictObject({
enabled: v.optional(v.boolean()),
monthly_credit_allowance: v.optional(nonNegativeIntegerSchema)
})
diff --git a/packages/cloud/src/server/policy/service.ts b/packages/cloud/src/server/policy/service.ts
index 723f5b853..4f333446d 100644
--- a/packages/cloud/src/server/policy/service.ts
+++ b/packages/cloud/src/server/policy/service.ts
@@ -25,9 +25,9 @@ export function createEntitlementService(
deploymentMode: 'self-hosted' as const
}
const [
- capabilityLinks,
- anonymousView,
- anonymousEdit,
+ links,
+ guestView,
+ guestEdit,
guestPresence,
collaboration,
revisionHistory,
@@ -38,9 +38,9 @@ export function createEntitlementService(
monthlyCreditAllowance,
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.links, false, context),
+ policy.boolean(CLOUD_FEATURE_KEYS.guestView, false, context),
+ policy.boolean(CLOUD_FEATURE_KEYS.guestEdit, 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),
@@ -59,9 +59,9 @@ export function createEntitlementService(
const participants = Math.min(technicalMaximumParticipants, maximumParticipants)
return {
features: {
- capabilityLinks,
- anonymousView,
- anonymousEdit,
+ links,
+ guestView,
+ guestEdit,
guestPresence,
collaboration,
revisionHistory,
diff --git a/packages/cloud/src/server/policy/static.ts b/packages/cloud/src/server/policy/static.ts
index 371cfde95..002e300e3 100644
--- a/packages/cloud/src/server/policy/static.ts
+++ b/packages/cloud/src/server/policy/static.ts
@@ -23,9 +23,9 @@ export function staticEntitlementsFromTOML(
},
storage: { maximumBytes: value.storage?.maximum_bytes },
sharing: {
- capabilityLinks: value.sharing?.capability_links,
- anonymousView: value.sharing?.anonymous_view,
- anonymousEdit: value.sharing?.anonymous_edit,
+ links: value.sharing?.links,
+ guestView: value.sharing?.guest_view,
+ guestEdit: value.sharing?.guest_edit,
guestPresence: value.sharing?.guest_presence
},
collaboration: {
@@ -49,9 +49,9 @@ export function staticEntitlementValues(input: unknown): Record<string, boolean
[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.links]: entitlements.sharing.links,
+ [CLOUD_FEATURE_KEYS.guestView]: entitlements.sharing.guestView,
+ [CLOUD_FEATURE_KEYS.guestEdit]: entitlements.sharing.guestEdit,
[CLOUD_FEATURE_KEYS.guestPresence]: entitlements.sharing.guestPresence,
[CLOUD_FEATURE_KEYS.collaboration]: entitlements.collaboration.enabled,
[CLOUD_FEATURE_KEYS.maximumParticipants]: entitlements.collaboration.maximumParticipants,
diff --git a/packages/cloud/src/server/sharing/actor.ts b/packages/cloud/src/server/sharing/actor.ts
new file mode 100644
index 000000000..636c6fa4d
--- /dev/null
+++ b/packages/cloud/src/server/sharing/actor.ts
@@ -0,0 +1,12 @@
+import type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'
+
+/**
+ * Who follows a link: the person signed in to the server, if any, whom the server lets in where
+ * it turns guests away.
+ */
+export async function shareActor(
+ request: Request,
+ resolveSession?: CloudSessionResolver
+): Promise<CloudActor | undefined> {
+ return resolveSession ? ((await resolveSession(request)) ?? undefined) : undefined
+}
diff --git a/packages/cloud/src/server/sharing/capabilities/service.ts b/packages/cloud/src/server/sharing/capabilities/service.ts
index 24243ece2..082118253 100644
--- a/packages/cloud/src/server/sharing/capabilities/service.ts
+++ b/packages/cloud/src/server/sharing/capabilities/service.ts
@@ -17,7 +17,7 @@ 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 { DocumentShareInvalidError, DocumentShareSignInRequiredError } from '../errors'
import { createSharingPolicy } from '../policy'
const SHARE_SECRET_BYTES = 24
@@ -88,11 +88,7 @@ export function createCapabilityService(
input: CreateDocumentShareInput
): Promise<DocumentShareCapability> {
await requireSharingAccess(database, userId, documentId)
- await sharingPolicy.requireCapabilityLink({
- actorId: userId,
- documentId,
- permission: input.permission
- })
+ await sharingPolicy.requireCapabilityLink({ actorId: userId, documentId })
const id = crypto.randomUUID()
const secret = randomHex(SHARE_SECRET_BYTES)
const row = await database.transaction().execute(async (transaction) => {
@@ -132,14 +128,13 @@ export function createCapabilityService(
await requireSharingAccess(database, userId, documentId)
const current = await database
.selectFrom('documentShare')
- .select('permission')
+ .select('id')
.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 })
+ await sharingPolicy.requireCapabilityLink({ actorId: userId, documentId })
const changes: UpdateObject<CloudDatabase, 'documentShare'> = { updatedAt: new Date() }
if (input.permission) changes.permission = input.permission
if (input.expiresAt !== undefined) {
@@ -230,9 +225,7 @@ export function createCapabilityService(
.where('id', '=', row.documentId)
.executeTakeFirstOrThrow()
const featureKey =
- row.permission === 'edit'
- ? CLOUD_FEATURE_KEYS.anonymousEdit
- : CLOUD_FEATURE_KEYS.anonymousView
+ row.permission === 'edit' ? CLOUD_FEATURE_KEYS.guestEdit : CLOUD_FEATURE_KEYS.guestView
if (
!(await options.policy.boolean(featureKey, false, {
targetingKey: document.workspaceId,
@@ -241,7 +234,8 @@ export function createCapabilityService(
deploymentMode: options.deploymentMode ?? 'self-hosted'
}))
) {
- throw new DocumentShareInvalidError()
+ // Guests are not let in here; people signed in to the server are.
+ throw new DocumentShareSignInRequiredError()
}
}
await database
diff --git a/packages/cloud/src/server/sharing/document-routes.ts b/packages/cloud/src/server/sharing/document-routes.ts
index a31ab7678..e7e06dfca 100644
--- a/packages/cloud/src/server/sharing/document-routes.ts
+++ b/packages/cloud/src/server/sharing/document-routes.ts
@@ -1,20 +1,25 @@
import { parseRequestSharedImageLinks, parseResolveDocumentShare } from '#cloud/contract'
+import type { CloudSessionResolver } from '#cloud/server/auth'
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'
+import { shareActor } from './actor'
+
export function createPublicDocumentRoutes(
sharing: DocumentSharingService,
- documents: DocumentService
+ documents: DocumentService,
+ resolveSession?: CloudSessionResolver
) {
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')
+ context.req.valid('json'),
+ await shareActor(context.req.raw, resolveSession)
)
return context.json({
resolution,
@@ -25,7 +30,11 @@ export function createPublicDocumentRoutes(
.post('/shares/:shareId/images', validatedJSON(parseRequestSharedImageLinks), (context) =>
sharingRoute(context, async () => {
const { checksums, ...share } = context.req.valid('json')
- const resolution = await sharing.resolveShare(context.req.param('shareId'), share)
+ const resolution = await sharing.resolveShare(
+ context.req.param('shareId'),
+ share,
+ await shareActor(context.req.raw, resolveSession)
+ )
return context.json(await documents.imageLinksShared(resolution.documentId, checksums))
})
)
diff --git a/packages/cloud/src/server/sharing/errors.ts b/packages/cloud/src/server/sharing/errors.ts
index ea85b8cc6..f54f22f9c 100644
--- a/packages/cloud/src/server/sharing/errors.ts
+++ b/packages/cloud/src/server/sharing/errors.ts
@@ -5,3 +5,8 @@ export class InvitationDeliveryError extends Error {
export class DocumentShareInvalidError extends Error {
override readonly name = 'DocumentShareInvalidError'
}
+
+/** A valid link this server opens only for people signed in to it. */
+export class DocumentShareSignInRequiredError extends Error {
+ override readonly name = 'DocumentShareSignInRequiredError'
+}
diff --git a/packages/cloud/src/server/sharing/http.ts b/packages/cloud/src/server/sharing/http.ts
index cfe8d6f12..87231c12a 100644
--- a/packages/cloud/src/server/sharing/http.ts
+++ b/packages/cloud/src/server/sharing/http.ts
@@ -1,5 +1,9 @@
import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents'
-import { DocumentShareInvalidError, InvitationDeliveryError } from '#cloud/server/sharing/errors'
+import {
+ DocumentShareInvalidError,
+ DocumentShareSignInRequiredError,
+ InvitationDeliveryError
+} from '#cloud/server/sharing/errors'
import { WorkspaceInvitationInvalidError } from '#cloud/server/workspaces/members'
import type { Context } from 'hono'
@@ -11,6 +15,9 @@ export function sharingDomainError(context: Context, error: unknown): Response |
) {
return context.json({ error: { code: 'not_found' as const } }, 404)
}
+ if (error instanceof DocumentShareSignInRequiredError) {
+ return context.json({ error: { code: 'unauthorized' as const } }, 401)
+ }
if (error instanceof InvitationDeliveryError) {
return context.json({ error: { code: 'invitation_delivery_failed' as const } }, 502)
}
diff --git a/packages/cloud/src/server/sharing/index.ts b/packages/cloud/src/server/sharing/index.ts
index b8f916da0..6ee4b670b 100644
--- a/packages/cloud/src/server/sharing/index.ts
+++ b/packages/cloud/src/server/sharing/index.ts
@@ -10,7 +10,11 @@ export {
encryptContinuationToken,
hashCapability
} from './crypto'
-export { DocumentShareInvalidError, InvitationDeliveryError } from './errors'
+export {
+ DocumentShareInvalidError,
+ DocumentShareSignInRequiredError,
+ InvitationDeliveryError
+} from './errors'
export { createGrantService, type GrantService } from './grants/service'
export { createPublicDocumentRoutes } from './document-routes'
diff --git a/packages/cloud/src/server/sharing/policy.ts b/packages/cloud/src/server/sharing/policy.ts
index eb2c48ffd..103a3d2e3 100644
--- a/packages/cloud/src/server/sharing/policy.ts
+++ b/packages/cloud/src/server/sharing/policy.ts
@@ -1,4 +1,3 @@
-import type { DocumentPermission } from '#cloud/contract'
import type { CloudDatabase } from '#cloud/server/db'
import { DocumentForbiddenError } from '#cloud/server/documents/errors'
import { CLOUD_FEATURE_KEYS, type CloudPolicy, type CloudPolicyContext } from '#cloud/server/policy'
@@ -12,7 +11,6 @@ export type SharingPolicyOptions = {
export type CapabilityLinkPolicyInput = {
actorId: string
documentId: string
- permission: DocumentPermission
}
export function createSharingPolicy(
@@ -33,13 +31,9 @@ export function createSharingPolicy(
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))
- ) {
+ // Whether guests may follow the link is checked when they do, so edit links still work for
+ // people signed in to the server.
+ if (!(await options.policy.boolean(CLOUD_FEATURE_KEYS.links, false, context))) {
throw new DocumentForbiddenError()
}
}
diff --git a/packages/cloud/src/server/sharing/routes.ts b/packages/cloud/src/server/sharing/routes.ts
index d35db861d..c8734b417 100644
--- a/packages/cloud/src/server/sharing/routes.ts
+++ b/packages/cloud/src/server/sharing/routes.ts
@@ -8,7 +8,7 @@ import {
parseResolveDocumentShare,
parseUpdateDocumentShare
} from '#cloud/contract'
-import type { CloudActor } from '#cloud/server/auth'
+import type { CloudActor, CloudSessionResolver } 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'
@@ -17,6 +17,8 @@ import { validatedJSON } from '#cloud/server/validation'
import { Hono } from 'hono'
import type { Kysely } from 'kysely'
+import { shareActor } from './actor'
+
export type SharingRouteEnvironment = {
Variables: { actor: CloudActor }
}
@@ -202,7 +204,10 @@ export function createDocumentSharingRoutes(
)
}
-export function createPublicSharingRoutes(service: DocumentSharingService) {
+export function createPublicSharingRoutes(
+ service: DocumentSharingService,
+ resolveSession?: CloudSessionResolver
+) {
return new Hono()
.post(
'/invitations/continuations',
@@ -237,7 +242,8 @@ export function createPublicSharingRoutes(service: DocumentSharingService) {
context.json({
resolution: await service.resolveShare(
context.req.param('shareId'),
- context.req.valid('json')
+ context.req.valid('json'),
+ await shareActor(context.req.raw, resolveSession)
)
})
)
diff --git a/packages/cloud/tests/client/auth/navigation.test.ts b/packages/cloud/tests/client/auth/navigation.test.ts
index 4a799991b..a93667896 100644
--- a/packages/cloud/tests/client/auth/navigation.test.ts
+++ b/packages/cloud/tests/client/auth/navigation.test.ts
@@ -9,6 +9,7 @@ const discovery: CloudDiscovery = {
apiURL: 'https://cloud.example/api',
authURL: 'https://cloud.example/api/auth',
appURL: 'https://editor.example',
+ localEditor: true,
authentication: { socialProviders: [], enterpriseSSO: false, enrollmentMode: 'open' },
capabilities: { documents: true, workspaces: true, collaboration: true }
}
diff --git a/packages/cloud/tests/client/device-authorization.test.ts b/packages/cloud/tests/client/device-authorization.test.ts
index 0ff5ed771..9d54bb4b2 100644
--- a/packages/cloud/tests/client/device-authorization.test.ts
+++ b/packages/cloud/tests/client/device-authorization.test.ts
@@ -10,6 +10,7 @@ const discovery: CloudDiscovery = {
apiURL: 'https://cloud.example.com/api',
authURL: 'https://cloud.example.com/api/auth',
appURL: 'https://app.example.com',
+ localEditor: true,
authentication: { socialProviders: [], enterpriseSSO: false, enrollmentMode: 'open' },
capabilities: { documents: true, workspaces: true, collaboration: true }
}
diff --git a/packages/cloud/tests/client/discovery.test.ts b/packages/cloud/tests/client/discovery.test.ts
index db0b2662d..b7bf82008 100644
--- a/packages/cloud/tests/client/discovery.test.ts
+++ b/packages/cloud/tests/client/discovery.test.ts
@@ -9,6 +9,7 @@ const discovery = {
apiURL: 'https://cloud.openpencil.dev/api',
authURL: 'https://cloud.openpencil.dev/api/auth',
appURL: 'https://app.openpencil.dev',
+ localEditor: true,
authentication: {
socialProviders: ['apple' as const, 'google' as const],
enterpriseSSO: false,
diff --git a/packages/cloud/tests/contract/ai.test.ts b/packages/cloud/tests/contract/ai.test.ts
index 39a77e40e..419b5ebff 100644
--- a/packages/cloud/tests/contract/ai.test.ts
+++ b/packages/cloud/tests/contract/ai.test.ts
@@ -57,9 +57,9 @@ describe('workspace entitlements contract', () => {
test('reads entitlements from servers released before the AI service', () => {
const entitlements = v.parse(workspaceEntitlementsSchema, {
features: {
- capabilityLinks: true,
- anonymousView: true,
- anonymousEdit: false,
+ links: true,
+ guestView: true,
+ guestEdit: false,
guestPresence: true,
collaboration: true,
revisionHistory: true
diff --git a/packages/cloud/tests/contract/discovery.test.ts b/packages/cloud/tests/contract/discovery.test.ts
index e7d3feb82..45ef3ee49 100644
--- a/packages/cloud/tests/contract/discovery.test.ts
+++ b/packages/cloud/tests/contract/discovery.test.ts
@@ -8,6 +8,7 @@ const discovery = {
apiURL: 'https://pencil.example.com/api',
authURL: 'https://pencil.example.com/api/auth',
appURL: 'https://app.example.com',
+ localEditor: true,
authentication: {
socialProviders: ['google' as const],
enterpriseSSO: true,
diff --git a/packages/cloud/tests/contract/portal.test.ts b/packages/cloud/tests/contract/portal.test.ts
index 8485dfa8f..987d0261a 100644
--- a/packages/cloud/tests/contract/portal.test.ts
+++ b/packages/cloud/tests/contract/portal.test.ts
@@ -3,9 +3,9 @@ import { describe, expect, test } from 'bun:test'
import { isCloudPortalPage } from '#cloud/contract'
describe('Cloud portal pages', () => {
- test('cover sign-in, desktop approval, account, and console paths', () => {
+ test('cover welcome, sign-in, desktop approval, account, and console paths', () => {
for (const path of [
- '/',
+ '/welcome',
'/auth/sign-in',
'/cloud/device',
'/account',
@@ -16,8 +16,11 @@ describe('Cloud portal pages', () => {
expect(isCloudPortalPage(path)).toBe(true)
})
- test('leave the API, discovery, and look-alike paths to the server', () => {
+ test('leave the editor, the API, discovery, and look-alike paths to the server', () => {
for (const path of [
+ '/',
+ '/demo',
+ '/cloud/documents/abc',
'/api/auth/sign-in/email',
'/.well-known/openpencil-cloud',
'/accounts',
diff --git a/packages/cloud/tests/e2e/cloudflare/checks.ts b/packages/cloud/tests/e2e/cloudflare/checks.ts
index b7de310ef..6dd89e9df 100644
--- a/packages/cloud/tests/e2e/cloudflare/checks.ts
+++ b/packages/cloud/tests/e2e/cloudflare/checks.ts
@@ -15,7 +15,7 @@ import { createPostgresCloudDatabase } from '#cloud/runtime/postgres/database'
import { createCollaborationTicketService, createDocumentSharingService } from '#cloud/server'
import * as Y from 'yjs'
-// Checks a running Cloud Worker (see run.ts): the API and portal answer, and the relay's
+// Checks a running Cloud Worker (see run.ts): the API, the editor, and the portal answer, and the relay's
// Durable Object admits ticket holders, keeps the room, and saves it to PostgreSQL.
const base = process.env.CLOUD_WORKER_URL ?? ''
const databaseURL = process.env.DATABASE_URL ?? ''
@@ -140,15 +140,22 @@ for (const path of ['/health', '/ready', '/.well-known/openpencil']) {
const response = await fetch(`${base}${path}`)
check(response.ok, `${path} answered HTTP ${response.status}`)
}
-const page = await fetch(`${base}/auth/sign-in`)
-check(
- page.ok && (page.headers.get('content-type') ?? '').startsWith('text/html'),
- `The portal page answered HTTP ${page.status}`
-)
-check(
- page.headers.get('content-security-policy') === "frame-ancestors 'none'",
- 'The portal page is missing its headers'
-)
+for (const [path, title] of [
+ ['/auth/sign-in', 'OpenPencil Cloud'],
+ ['/', 'OpenPencil'],
+ ['/cloud/documents/missing', 'OpenPencil']
+]) {
+ const page = await fetch(`${base}${path}`, { headers: { Accept: 'text/html' } })
+ check(
+ page.ok && (page.headers.get('content-type') ?? '').startsWith('text/html'),
+ `The page at ${path} answered HTTP ${page.status}`
+ )
+ check(
+ page.headers.get('content-security-policy') === "frame-ancestors 'none'",
+ `The page at ${path} is missing its headers`
+ )
+ check((await page.text()).includes(`<title>${title}</title>`), `${path} is not the expected page`)
+}
const missing = await fetch(`${base}/api/collaboration/relay`)
check(missing.status === 426, `A plain request to the relay answered HTTP ${missing.status}`)
diff --git a/packages/cloud/tests/e2e/cloudflare/run.ts b/packages/cloud/tests/e2e/cloudflare/run.ts
index 4f2283dad..29222ca30 100644
--- a/packages/cloud/tests/e2e/cloudflare/run.ts
+++ b/packages/cloud/tests/e2e/cloudflare/run.ts
@@ -1,6 +1,6 @@
import { copyFile, mkdir, writeFile } from 'node:fs/promises'
-import { cloudDeployPath, cloudPackagePath } from '#cloud-tests/helpers/paths'
+import { cloudDeployPath, cloudPackagePath, repositoryPath } from '#cloud-tests/helpers/paths'
import { composeCommand, runProcess } from '#cloud-tests/helpers/process'
// Runs the Cloudflare Worker under `wrangler dev`, against PostgreSQL and SeaweedFS from Compose,
@@ -41,18 +41,8 @@ trusted_origins = []
[database]
-[authentication]
-enrollment_mode = "open"
-admin_notification_emails = []
-
-[authentication.mfa]
-deployment_admin_required = false
-totp_enabled = false
-passkeys_enabled = false
-recovery_codes_enabled = false
-
-[authentication.email_password]
-enabled = false
+[authentication.enrollment]
+mode = "open"
[authentication.trusted_proxies]
headers = []
@@ -105,6 +95,8 @@ try {
'bunx',
'wrangler',
'dev',
+ '--assets',
+ repositoryPath('dist-cloud'),
'--ip',
'127.0.0.1',
'--port',
diff --git a/packages/cloud/tests/integration/server/app.test.ts b/packages/cloud/tests/integration/server/app.test.ts
index 2d9d30efa..590662543 100644
--- a/packages/cloud/tests/integration/server/app.test.ts
+++ b/packages/cloud/tests/integration/server/app.test.ts
@@ -369,6 +369,7 @@ describe('createCloudApp', () => {
apiURL: 'https://pencil.example.com/api',
authURL: 'https://pencil.example.com/api/auth',
appURL: 'https://pencil.example.com',
+ localEditor: true,
authentication: {
socialProviders: ['google'],
enterpriseSSO: false,
diff --git a/packages/cloud/tests/integration/server/documents/images.test.ts b/packages/cloud/tests/integration/server/documents/images.test.ts
index 9cbd10100..35a170533 100644
--- a/packages/cloud/tests/integration/server/documents/images.test.ts
+++ b/packages/cloud/tests/integration/server/documents/images.test.ts
@@ -70,8 +70,8 @@ async function testApp() {
policy: createDefaultCloudPolicy(
new EntitlementOpenFeatureProvider(
new StaticEntitlementSource({
- [CLOUD_FEATURE_KEYS.capabilityLinks]: true,
- [CLOUD_FEATURE_KEYS.anonymousView]: true
+ [CLOUD_FEATURE_KEYS.links]: true,
+ [CLOUD_FEATURE_KEYS.guestView]: true
})
)
),
diff --git a/packages/cloud/tests/integration/server/policy/database.test.ts b/packages/cloud/tests/integration/server/policy/database.test.ts
index 3fcc51c01..d37baf37e 100644
--- a/packages/cloud/tests/integration/server/policy/database.test.ts
+++ b/packages/cloud/tests/integration/server/policy/database.test.ts
@@ -22,7 +22,7 @@ describe('database entitlement source', () => {
context.workspaceId,
{
documents: { maximumFileBytes: 100 },
- sharing: { anonymousEdit: false },
+ sharing: { guestEdit: false },
storage: {},
collaboration: {}
},
@@ -32,7 +32,7 @@ describe('database entitlement source', () => {
context.workspaceId,
{
documents: { maximumFileBytes: 200 },
- sharing: { anonymousEdit: true },
+ sharing: { guestEdit: true },
storage: {},
collaboration: {}
},
@@ -45,7 +45,7 @@ describe('database entitlement source', () => {
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, 'cloud.sharing.guest-edit')).toBe(true)
expect(await source.boolean(subject, 'unknown')).toBeNull()
} finally {
await context.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
index ae37fba2d..63e2173d7 100644
--- a/packages/cloud/tests/integration/server/sharing/capabilities/service.test.ts
+++ b/packages/cloud/tests/integration/server/sharing/capabilities/service.test.ts
@@ -4,7 +4,8 @@ import { CLOUD_FEATURE_KEYS, seedSharing, sharingWithPolicy } from '#cloud-tests
import {
DocumentForbiddenError,
DocumentNotFoundError,
- DocumentShareInvalidError
+ DocumentShareInvalidError,
+ DocumentShareSignInRequiredError
} from '#cloud/server'
describe('document sharing capabilities integration', () => {
@@ -79,32 +80,27 @@ describe('document sharing capabilities integration', () => {
}
})
- test('enforces capability policy on share updates', async () => {
+ test('lets edit links exist whatever guests may do, and needs links for any update', async () => {
const context = await seedSharing()
try {
const enabled = sharingWithPolicy(context, {
- [CLOUD_FEATURE_KEYS.capabilityLinks]: true,
- [CLOUD_FEATURE_KEYS.anonymousEdit]: false
+ [CLOUD_FEATURE_KEYS.links]: true,
+ [CLOUD_FEATURE_KEYS.guestEdit]: 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'
+ permission: 'edit'
})
- ).toMatchObject({ permission: 'view' })
+ ).toMatchObject({ permission: 'edit' })
for (const deploymentMode of ['official', 'self-hosted'] as const) {
const disabled = sharingWithPolicy(
context,
{
- [CLOUD_FEATURE_KEYS.capabilityLinks]: false,
- [CLOUD_FEATURE_KEYS.anonymousEdit]: true
+ [CLOUD_FEATURE_KEYS.links]: false,
+ [CLOUD_FEATURE_KEYS.guestEdit]: true
},
deploymentMode
)
@@ -119,6 +115,32 @@ describe('document sharing capabilities integration', () => {
}
})
+ test('asks guests to sign in where the server turns them away, and lets members in', async () => {
+ const context = await seedSharing()
+ try {
+ const closed = sharingWithPolicy(context, {
+ [CLOUD_FEATURE_KEYS.links]: true,
+ [CLOUD_FEATURE_KEYS.guestView]: false,
+ [CLOUD_FEATURE_KEYS.guestEdit]: false
+ })
+ for (const permission of ['view', 'edit'] as const) {
+ const capability = await closed.createShare('owner', context.documentId, { permission })
+ const input = { secret: capability.secret, guestName: 'Visitor' }
+ await expect(closed.resolveShare(capability.share.id, input)).rejects.toBeInstanceOf(
+ DocumentShareSignInRequiredError
+ )
+ const member = await closed.resolveShare(capability.share.id, input, {
+ userId: 'alice',
+ name: 'Alice',
+ })
+ expect(member).toMatchObject({ permission, principal: { kind: 'user', userId: 'alice' } })
+ }
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
test('checks sharing access before it looks up a share to update', async () => {
const context = await seedSharing()
try {
diff --git a/packages/cloud/tests/runtime/node/portal.test.ts b/packages/cloud/tests/runtime/node/site.test.ts
similarity index 53%
rename from packages/cloud/tests/runtime/node/portal.test.ts
rename to packages/cloud/tests/runtime/node/site.test.ts
index 177626066..c9c7385c2 100644
--- a/packages/cloud/tests/runtime/node/portal.test.ts
+++ b/packages/cloud/tests/runtime/node/site.test.ts
@@ -3,27 +3,28 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import { nodePortalFiles } from '#cloud/runtime/node/portal'
+import { nodeSiteFiles } from '#cloud/runtime/node/site'
let directory = ''
beforeAll(async () => {
- directory = await mkdtemp(join(tmpdir(), 'openpencil-portal-'))
+ directory = await mkdtemp(join(tmpdir(), 'openpencil-site-'))
await mkdir(join(directory, 'assets'))
await writeFile(join(directory, 'assets', 'cloud-abc.js'), 'export {}')
- await writeFile(join(tmpdir(), 'openpencil-portal-outside.txt'), 'secret')
+ await writeFile(join(directory, 'demo.fig'), 'fig-kiwi')
+ await writeFile(join(tmpdir(), 'openpencil-site-outside.txt'), 'secret')
})
afterAll(async () => {
await rm(directory, { recursive: true, force: true })
- await rm(join(tmpdir(), 'openpencil-portal-outside.txt'), { force: true })
+ await rm(join(tmpdir(), 'openpencil-site-outside.txt'), { force: true })
})
const request = new Request('https://cloud.example/')
-describe('Node portal files', () => {
+describe('Node site files', () => {
test('reads a file with its media type', async () => {
- const file = await nodePortalFiles(directory)('/assets/cloud-abc.js', request)
+ const file = await nodeSiteFiles(directory)('/assets/cloud-abc.js', request)
expect(file?.type).toContain('javascript')
expect(new TextDecoder().decode(file?.body instanceof Uint8Array ? file.body : undefined)).toBe(
'export {}'
@@ -31,8 +32,13 @@ describe('Node portal files', () => {
})
test('never reads outside its directory or answers missing files', async () => {
- const files = nodePortalFiles(directory)
- expect(await files('/..%2Fopenpencil-portal-outside.txt', request)).toBeNull()
+ const files = nodeSiteFiles(directory)
+ expect(await files('/..%2Fopenpencil-site-outside.txt', request)).toBeNull()
expect(await files('/assets/missing.js', request)).toBeNull()
})
+
+ test('reads files without a registered media type as bytes', async () => {
+ const file = await nodeSiteFiles(directory)('/demo.fig', request)
+ expect(file?.type).toBe('application/octet-stream')
+ })
})
diff --git a/packages/cloud/tests/runtime/portal/server.test.ts b/packages/cloud/tests/runtime/portal/server.test.ts
deleted file mode 100644
index deeccfd91..000000000
--- a/packages/cloud/tests/runtime/portal/server.test.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { describe, expect, test } from 'bun:test'
-
-import { createCloudServer, type PortalFiles } from '#cloud/runtime/portal/server'
-
-const files: Record<string, string> = {
- '/cloud.html': '<!doctype html><title>Portal</title>',
- '/assets/cloud-abc.js': 'export {}',
- '/favicon.svg': '<svg/>'
-}
-
-const portal: PortalFiles = async (path) => {
- const text = files[path]
- return text === undefined
- ? null
- : {
- body: Uint8Array.from(new TextEncoder().encode(text)),
- type: path.endsWith('.svg') ? 'image/svg+xml' : 'text/plain'
- }
-}
-
-const api = {
- fetch: (request: Request) =>
- new URL(request.url).pathname === '/api/session'
- ? Response.json({ ok: true })
- : new Response('Not found', { status: 404 })
-}
-
-const server = createCloudServer(api, { portal, indexingPolicy: 'deny' })
-const request = (path: string, method = 'GET') =>
- server.request(new Request(`https://cloud.example${path}`, { method }))
-
-describe('Cloud server', () => {
- test('serves the page at portal paths, never framed and never cached', async () => {
- const page = await request('/cloud/device?user_code=ABCD')
- expect(await page.text()).toContain('Portal')
- expect(page.headers.get('Content-Security-Policy')).toBe("frame-ancestors 'none'")
- expect(page.headers.get('Cache-Control')).toBe('no-cache')
- expect((await request('/account')).status).toBe(200)
- expect(await (await request('/')).text()).toContain('Portal')
- })
-
- test('leaves other paths and methods to the API', async () => {
- expect(await (await request('/api/session')).json()).toEqual({ ok: true })
- expect((await request('/account', 'POST')).status).toBe(404)
- })
-
- test('serves hashed assets as immutable and icons briefly cached where the API has nothing', async () => {
- const asset = await request('/assets/cloud-abc.js')
- expect(await asset.text()).toBe('export {}')
- expect(asset.headers.get('Cache-Control')).toContain('immutable')
- const icon = await request('/favicon.svg')
- expect(icon.headers.get('Content-Type')).toBe('image/svg+xml')
- expect(icon.headers.get('Cache-Control')).not.toContain('immutable')
- expect((await request('/assets/missing.js')).status).toBe(404)
- expect((await request('/cloud.html')).status).toBe(404)
- })
-
- test('applies the indexing policy to every answer', async () => {
- for (const path of ['/account', '/api/session', '/favicon.svg']) {
- expect((await request(path)).headers.get('X-Robots-Tag')).toContain('noindex')
- }
- })
-
- test('answers 404 at portal paths without a portal build', async () => {
- const bare = createCloudServer(api, { indexingPolicy: 'allow' })
- expect((await bare.request('https://cloud.example/account')).status).toBe(404)
- })
-})
diff --git a/packages/cloud/tests/runtime/site/server.test.ts b/packages/cloud/tests/runtime/site/server.test.ts
new file mode 100644
index 000000000..10c01ce12
--- /dev/null
+++ b/packages/cloud/tests/runtime/site/server.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudServer, type SiteFiles } from '#cloud/runtime/site/server'
+
+const files: Record<string, string> = {
+ '/cloud.html': '<!doctype html><title>Portal</title>',
+ '/index.html': '<!doctype html><title>Editor</title>',
+ '/assets/cloud-abc.js': 'export {}',
+ '/favicon.svg': '<svg/>'
+}
+
+const TYPES: Record<string, string> = { svg: 'image/svg+xml', html: 'text/html' }
+const typeOf = (path: string) => TYPES[path.split('.').at(-1) ?? ''] ?? 'text/plain'
+
+const site: SiteFiles = async (path) => {
+ const text = files[path]
+ return text === undefined
+ ? null
+ : { body: Uint8Array.from(new TextEncoder().encode(text)), type: typeOf(path) }
+}
+
+const api = {
+ fetch: (request: Request) =>
+ new URL(request.url).pathname === '/api/session'
+ ? Response.json({ ok: true })
+ : new Response('Not found', { status: 404 })
+}
+
+const server = createCloudServer(api, { site, indexingPolicy: 'deny' })
+const request = (path: string, init: RequestInit = {}) =>
+ server.request(new Request(`https://cloud.example${path}`, init))
+const navigate = (path: string) => request(path, { headers: { Accept: 'text/html' } })
+
+describe('Cloud server', () => {
+ test('serves the portal at portal paths, never framed and never cached', async () => {
+ const page = await request('/cloud/device?user_code=ABCD')
+ expect(await page.text()).toContain('Portal')
+ expect(page.headers.get('Content-Security-Policy')).toBe("frame-ancestors 'none'")
+ expect(page.headers.get('Cache-Control')).toBe('no-cache')
+ expect((await request('/account')).status).toBe(200)
+ expect(await (await request('/welcome')).text()).toContain('Portal')
+ })
+
+ test('serves the editor at the root and at any other page, never framed', async () => {
+ for (const path of ['/', '/demo', '/cloud/documents/abc?server=x']) {
+ const page = await navigate(path)
+ expect(await page.text()).toContain('Editor')
+ expect(page.headers.get('Content-Security-Policy')).toBe("frame-ancestors 'none'")
+ expect(page.headers.get('Cache-Control')).toBe('no-cache')
+ }
+ })
+
+ test('leaves other paths and methods to the API', async () => {
+ expect(await (await navigate('/api/session')).json()).toEqual({ ok: true })
+ expect((await request('/account', { method: 'POST' })).status).toBe(404)
+ expect((await request('/missing.json')).status).toBe(404)
+ })
+
+ test('serves hashed assets as immutable and other files briefly cached where the API has nothing', async () => {
+ const asset = await request('/assets/cloud-abc.js')
+ expect(await asset.text()).toBe('export {}')
+ expect(asset.headers.get('Cache-Control')).toContain('immutable')
+ const icon = await request('/favicon.svg')
+ expect(icon.headers.get('Content-Type')).toBe('image/svg+xml')
+ expect(icon.headers.get('Cache-Control')).not.toContain('immutable')
+ expect((await request('/assets/missing.js')).status).toBe(404)
+ // The service worker fetches the pages it keeps by their file names.
+ expect((await request('/index.html')).headers.get('Cache-Control')).toBe('no-cache')
+ })
+
+ test('applies the indexing policy to every answer', async () => {
+ for (const path of ['/', '/account', '/api/session', '/favicon.svg']) {
+ expect((await navigate(path)).headers.get('X-Robots-Tag')).toContain('noindex')
+ }
+ })
+
+ test('answers only the API without a site build', async () => {
+ const bare = createCloudServer(api, { indexingPolicy: 'allow' })
+ expect((await bare.request('https://cloud.example/account')).status).toBe(404)
+ expect(
+ (await bare.request('https://cloud.example/', { headers: { Accept: 'text/html' } })).status
+ ).toBe(404)
+ })
+})
diff --git a/packages/cloud/tests/server/config/deployment.test.ts b/packages/cloud/tests/server/config/deployment.test.ts
index 80118741e..e04a1a170 100644
--- a/packages/cloud/tests/server/config/deployment.test.ts
+++ b/packages/cloud/tests/server/config/deployment.test.ts
@@ -18,28 +18,27 @@ public_url = "https://cloud.example.com"
app_url = "https://app.example.com"
trusted_origins = ["https://app.example.com"]
-[authentication]
-enrollment_mode = "approval"
+[authentication.enrollment]
+mode = "approval"
+notification_emails = ["[email protected]"]
[authentication.mfa]
-deployment_admin_required = true
-totp_enabled = true
-passkeys_enabled = true
-recovery_codes_enabled = true
-trusted_device_days = 7
+required_for_admins = true
+totp = true
+recovery_codes = true
+trusted_device_lifetime_days = 7
[authentication.passkeys]
-rp_id = "cloud.example.com"
-rp_name = "OpenPencil Cloud"
-origin = "https://cloud.example.com"
+enabled = true
+rp_name = "Example Cloud"
[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
+verification_link_lifetime_minutes = 30
+password_reset_link_lifetime_minutes = 45
compromised_password_check = true
[authentication.captcha]
@@ -78,8 +77,16 @@ const environment = {
const completeSource = `${minimalSource.replace(
'trusted_origins = ["https://app.example.com"]',
- 'trusted_origins = ["https://app.example.com"]\nindexing = "allow"'
+ 'trusted_origins = ["https://app.example.com"]\nindexing = "allow"\nlocal_editor = false'
)}
+maximum_upload_bytes = 104857600
+
+[collaboration]
+maximum_message_bytes = 524288
+maximum_connections_per_room = 250
+
+[documents]
+retention_days = 14
[authentication.trusted_proxies]
headers = ["cf-connecting-ip"]
@@ -99,12 +106,6 @@ 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', () => {
@@ -114,6 +115,8 @@ describe('Cloud TOML deployment configuration', () => {
databaseURL: environment.DATABASE_URL,
authSecret: environment.BETTER_AUTH_SECRET,
enrollmentMode: 'approval',
+ enrollmentAdminNotificationEmails: ['[email protected]'],
+ localEditor: true,
emailPasswordEnabled: true,
emailPasswordSignUpEnabled: false,
emailPasswordMinimumLength: 16,
@@ -126,9 +129,7 @@ describe('Cloud TOML deployment configuration', () => {
passkeysEnabled: true,
recoveryCodesEnabled: true,
mfaTrustedDeviceDays: 7,
- passkeyRPID: 'cloud.example.com',
- passkeyRPName: 'OpenPencil Cloud',
- passkeyOrigin: 'https://cloud.example.com',
+ passkeyRPName: 'Example Cloud',
captchaProvider: 'cloudflare-turnstile',
captchaSiteKey: 'public-turnstile-site-key',
captchaSecretKey: 'turnstile-secret',
@@ -147,6 +148,7 @@ describe('Cloud TOML deployment configuration', () => {
})
expect(config).toMatchObject({
indexingPolicy: 'allow',
+ localEditor: false,
authTrustedIPHeaders: ['cf-connecting-ip'],
authTrustedProxies: ['192.0.2.10'],
s3SessionToken: 'session-token',
@@ -236,6 +238,18 @@ portal_url = "https://billing.example.com"
expect(parseCloudDeploymentTOML(minimalSource, environment).relayURL).toBeUndefined()
})
+ test('refuses keys it does not know rather than leaving their settings at defaults', () => {
+ const renamed = minimalSource.replace(
+ '[authentication.enrollment]\nmode = "approval"',
+ '[authentication]\nenrollment_mode = "approval"\n\n[authentication.enrollment]'
+ )
+ expect(renamed).not.toBe(minimalSource)
+ expect(() => parseCloudDeploymentTOML(renamed, environment)).toThrow()
+ expect(() =>
+ parseCloudDeploymentTOML(`${minimalSource}\n[technical_limits]\n`, environment)
+ ).toThrow()
+ })
+
test('supports explicit secret-reference names', () => {
const input = parseTOML(minimalSource)
const parsed = v.parse(cloudDeploymentConfigSchema, input)
diff --git a/packages/cloud/tests/server/config/schema.test.ts b/packages/cloud/tests/server/config/schema.test.ts
index df69aa567..e94f1db86 100644
--- a/packages/cloud/tests/server/config/schema.test.ts
+++ b/packages/cloud/tests/server/config/schema.test.ts
@@ -29,17 +29,6 @@ describe('Cloud server configuration', () => {
).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'
diff --git a/packages/cloud/tests/server/policy/policy.test.ts b/packages/cloud/tests/server/policy/policy.test.ts
index c8038abd4..4e9508e72 100644
--- a/packages/cloud/tests/server/policy/policy.test.ts
+++ b/packages/cloud/tests/server/policy/policy.test.ts
@@ -11,7 +11,7 @@ const context = {
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.links, 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
index f2997dd42..0dc1cfa75 100644
--- a/packages/cloud/tests/server/policy/static.test.ts
+++ b/packages/cloud/tests/server/policy/static.test.ts
@@ -8,16 +8,16 @@ describe('structured static entitlements', () => {
staticEntitlementValues({
documents: { maximumFileBytes: 100, revisionHistory: true },
storage: { maximumBytes: 1000 },
- sharing: { capabilityLinks: true, anonymousView: true, anonymousEdit: false },
+ sharing: { links: true, guestView: true, guestEdit: 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.sharing.links': true,
+ 'cloud.sharing.guest-view': true,
+ 'cloud.sharing.guest-edit': false,
'cloud.collaboration.enabled': true,
'cloud.collaboration.maximum-participants': 5
})
diff --git a/packages/cloud/tests/server/sharing/http.test.ts b/packages/cloud/tests/server/sharing/http.test.ts
new file mode 100644
index 000000000..6448e10f4
--- /dev/null
+++ b/packages/cloud/tests/server/sharing/http.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, test } from 'bun:test'
+
+import { DocumentShareInvalidError, DocumentShareSignInRequiredError } from '#cloud/server'
+import { sharingRoute } from '#cloud/server/sharing/http'
+import { Hono } from 'hono'
+
+const answer = (error: Error) =>
+ new Hono()
+ .get('/', (context) =>
+ sharingRoute(context, () => {
+ throw error
+ })
+ )
+ .request('/')
+
+describe('shared link answers', () => {
+ test('ask a guest the server turns away to sign in', async () => {
+ const response = await answer(new DocumentShareSignInRequiredError())
+ expect(response.status).toBe(401)
+ expect(await response.json()).toEqual({ error: { code: 'unauthorized' } })
+ })
+
+ test('tell nothing about links that do not open', async () => {
+ expect((await answer(new DocumentShareInvalidError())).status).toBe(404)
+ })
+})
diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.md
index 3ea16b356..a6b4ea3cb 100644
--- a/packages/docs/development/cloud.md
+++ b/packages/docs/development/cloud.md
@@ -194,22 +194,34 @@ either role: the first operator is approved and promoted through the `admin` com
## Portal
-The server shows its own pages on its public address: sign-in and sign-up, email verification,
-password reset, two-step sign-in, desktop sign-in approval, account security, and the administration
-console. They are a separate Vite entry, `cloud.html`, in the app project, so they reuse the
-editor's components and theme without loading the editor; `bun run build:cloud-portal` writes them
-to `dist-cloud-portal/`. The editor never embeds these pages; when it needs them, for a social
-provider or a second sign-in step, it opens them in a browser and gets the person back through
-`/auth/return` or the device code. A verification link started in the editor lands on
-`/auth/verified`, which sends the person back to the editor.
+The server shows its own pages on its public address: a welcome page, sign-in and sign-up, email
+verification, password reset, two-step sign-in, desktop sign-in approval, account security, and the
+administration console. They are a separate Vite entry, `cloud.html`, in the app project, so they
+reuse the editor's components and theme without loading the editor. `bun run build:cloud` writes
+them to `dist-cloud/` beside the editor itself, which every Cloud server serves at its root. The
+editor never embeds these pages; when it needs them, for a social provider or a second sign-in
+step, it opens them in a browser and gets the person back through `/auth/return` or the device
+code. A verification link started in the editor lands on `/auth/verified`, which sends the person
+back to the editor.
`CLOUD_PORTAL_PAGE_ROOTS` in the contract lists the page paths, and every runtime serves
`cloud.html` at and below them with `frame-ancestors 'none'`, so the approval page cannot be
-framed. The server's root gets the page too, and the portal sends it on to its home. Both runtimes put the API behind the same Hono router, `createCloudServer` in
-`src/runtime/portal`, which answers portal pages before the API and portal assets only where the
-API returns 404; Node reads the build named by `OPENPENCIL_CLOUD_PORTAL_DIR`, and the Worker reads
-its static assets. `bun run cloud:dev` keeps a
-watched portal build next to the server.
+framed. Both runtimes put the API behind the same Hono router, `createCloudServer` in
+`src/runtime/site`, which answers portal pages before the API, and only where the API returns 404
+the site's files, then the editor's `index.html` for any other page, so the editor's router keeps
+its own addresses. Node reads the build named by `OPENPENCIL_CLOUD_SITE_DIR`, and the Worker reads
+its static assets. `bun run cloud:dev` keeps a watched site build next to the server.
+
+The editor a server serves knows it from the build (`__OPENPENCIL_CLOUD_SITE__`). Before it boots,
+it asks who is signed in: an account that may use the server gets the editor, and anyone else at
+the root goes to `/welcome`, which signs them in, sends an account waiting for review to its
+standing page, or opens the editor without an account; this browser then keeps that choice.
+`[deployment] local_editor = false` takes that choice away and sends every editor page there.
+Links to documents, shared files, and invitations always open the editor, which signs in for them,
+and an unreachable server does too, since the editor works without it. The editor adds its server at startup and reaches it with the
+server's own sign-in session, and the portal leaves for the editor as a page load, never through
+its router. An official deployment builds the editor with its own address as
+`VITE_OPENPENCIL_OFFICIAL_CLOUD_URL`, so staging is the official server in its own editor.
## Editor client
@@ -242,7 +254,7 @@ opening a document nobody edited uploads nothing.
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
+entitlements, and technical limits, each in the section it 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.
@@ -251,8 +263,11 @@ looser.
## Policy, entitlements, and quotas
-OpenFeature answers concrete questions such as whether capability links, anonymous viewing, or
-full revision history is kept, and what a numeric limit is. Its provider reads one entitlement
+OpenFeature answers concrete questions such as whether links work, whether guests, people who
+follow a link without signing in, may view or edit through one, or whether full revision history
+is kept, and what a numeric limit is. Links always work for people signed in to the server: the
+share routes resolve the session, and a guest the server turns away gets `401` so the editor signs
+in and opens the link again. 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
@@ -426,3 +441,11 @@ document in one object lets a restore or a version change reach all its rooms in
needs the document before the ticket arrives, so the ticket's relay URL names it. Objects keep their
sockets without hibernation, so the relay runs unchanged; hibernating would need the relay to
rebuild rooms and peers on every wake.
+
+**2026-10 · Every Cloud server serves the editor at its root.** The official web editor moves from
+app.openpencil.dev to the official server's own address, so one site holds the editor, sign-in,
+and documents, and a self-hosted server is a complete product too. On its own origin the editor
+signs in through the server's pages and its session, with no device code and no CORS. A welcome
+page meets visitors who are not signed in, and the editor stays usable without an account, as it
+is on app.openpencil.dev, which can then redirect there. Keeping the editor only on a separate
+static host left a signed-in person on account settings with no way to their files.
diff --git a/packages/docs/reference/self-hosting-cloud.md b/packages/docs/reference/self-hosting-cloud.md
index 09a2e9f7a..7cbc15886 100644
--- a/packages/docs/reference/self-hosting-cloud.md
+++ b/packages/docs/reference/self-hosting-cloud.md
@@ -5,7 +5,7 @@ description: Run your own OpenPencil Cloud server with PostgreSQL and an S3-comp
# Self-hosting OpenPencil Cloud
-OpenPencil Cloud is one Node 22+ process in front of PostgreSQL 15 or later and an S3-compatible object store, with optional SMTP for email. The same process serves the API, the collaboration relay, and the server's own pages for signing in, account security, and administration. It also runs on [Cloudflare Workers](#cloudflare-workers) with the same configuration. People connect to it from the editor as described in [OpenPencil Cloud](/user-guide/openpencil-cloud).
+OpenPencil Cloud is one Node 22+ process in front of PostgreSQL 15 or later and an S3-compatible object store, with optional SMTP for email. The same process serves the API, the collaboration relay, the editor, and the server's own pages for signing in, account security, and administration. It also runs on [Cloudflare Workers](#cloudflare-workers) with the same configuration. People connect to it from the editor as described in [OpenPencil Cloud](/user-guide/openpencil-cloud).
## Build
@@ -14,24 +14,23 @@ From a checkout of the repository:
```sh
bun install
bun run build:packages
-bun run build:cloud-portal # writes dist-cloud-portal/
+bunx playwright install --with-deps chromium # draws the demo document's shader fills
+bun run build:cloud # writes dist-cloud/: the editor and the server's pages
bun --filter @open-pencil/cloud build:standalone # writes packages/cloud/dist-standalone/
```
-`dist-standalone/` bundles the server's dependencies, so copy the whole directory, together with `dist-cloud-portal/`, to a host that has Node but no `node_modules`. Start the server with `node dist-standalone/server.mjs`.
+`dist-standalone/` bundles the server's dependencies, so copy the whole directory, together with `dist-cloud/`, to a host that has Node but no `node_modules`. Start the server with `node dist-standalone/server.mjs`.
## Configure
-Settings live in a TOML file; environment variables supply secrets and tell the server where that file and the portal are and where to listen.
+Settings live in a TOML file; environment variables supply secrets and tell the server where that file and the site build are and where to listen.
1. Copy [`openpencil-cloud.example.toml`](https://github.com/open-pencil/open-pencil/blob/master/packages/cloud/deploy/openpencil-cloud.example.toml) and set at least:
- `deployment.public_url`: the address the server answers on, for example `https://cloud.example.com`;
- - `deployment.app_url`: the editor that invitation and share links open (see [The editor address](#the-editor-address));
- - `deployment.trusted_origins`: every editor origin that talks to the server, including `app_url`;
- `[object_storage]`: the bucket's endpoint, region, and name.
2. Copy [`.env.example`](https://github.com/open-pencil/open-pencil/blob/master/packages/cloud/deploy/.env.example) and set:
- `OPENPENCIL_CLOUD_CONFIG`: the path to the TOML file;
- - `OPENPENCIL_CLOUD_PORTAL_DIR`: the path to `dist-cloud-portal/`. Without it the server still runs, but sign-in, account, and administration pages answer 404, and it warns at startup;
+ - `OPENPENCIL_CLOUD_SITE_DIR`: the path to `dist-cloud/`. Without it the server still runs its API, but the editor and the sign-in, account, and administration pages answer 404, and it warns at startup;
- the secrets the TOML names, by default `DATABASE_URL`, `BETTER_AUTH_SECRET`, `S3_ACCESS_KEY_ID`, and `S3_SECRET_ACCESS_KEY`, plus `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `APPLE_PRIVATE_KEY`, `S3_SESSION_TOKEN`, `OPENPENCIL_CLOUD_SMTP_USER`, and `OPENPENCIL_CLOUD_SMTP_PASSWORD` when their sections are enabled.
3. Start the server with the environment loaded, for example `node --env-file=.env dist-standalone/server.mjs`.
@@ -41,34 +40,33 @@ The server migrates the database before it accepts requests and listens on `PORT
## The editor address
-`deployment.app_url` is where invitation and share links send people. Either:
+The server serves the editor at its own address. Visitors who are not signed in get a welcome page there first, where they sign in or use the editor without an account. Signed-in people whose account may use the server get the editor, already connected to it; an account waiting for approval gets a page that says so. Invitation and share links open the editor too.
-- use the hosted editor, `https://app.openpencil.dev`, which connects to any server; people sign in by approving a code, as in the desktop app;
-- or serve your own build of the editor (after `bun run build:packages`, `bunx vite build` writes `dist/`) on your own domain. When it is the server's editor address, people sign in on the server's pages and come straight back.
+For a server only its members use, set `deployment.local_editor = false`: the welcome page then offers only signing in, and every editor page asks for it. To keep shared links to members too, turn off `guest_view`, `guest_edit`, and `guest_presence` under `[entitlements.sharing]`; links then open after signing in to the server.
-Either way, the desktop app connects to the server directly, and the web editor offers to open links there.
+To send links to an editor at another address instead, set `deployment.app_url` to it and list its origin in `deployment.trusted_origins`. People sign in there by approving a code, as in the desktop app, which connects to the server directly either way.
## Reverse proxy
- Terminate TLS in front of the server and the object store, on stable hostnames.
- Forward WebSocket upgrades for `/api/collaboration/relay`. Collaboration tickets name the relay at `public_url` with a `ws:` or `wss:` scheme; set `[collaboration] relay_url` when clients reach it elsewhere.
-- The object store must accept presigned uploads from the editor's origins: allow `PUT` and `GET` from `trusted_origins` in its CORS rules, with the `Range` request header, which Home uses to read a document's preview without downloading the whole file.
+- The object store must accept presigned uploads from the editor's origins: allow `PUT` and `GET` from `public_url` and any `trusted_origins` in its CORS rules, with the `Range` request header, which Home uses to read a document's preview without downloading the whole file.
## Cloudflare Workers
-On Cloudflare a Worker serves the API and the portal, a Durable Object for each document runs its collaboration rooms, Hyperdrive connects to PostgreSQL, and a Cron Trigger every five minutes runs cleanup and retries email. [`packages/cloud/deploy/cloudflare`](https://github.com/open-pencil/open-pencil/tree/master/packages/cloud/deploy/cloudflare) is the deployment to copy: a Wrangler configuration and the Worker's entry, which reads `openpencil-cloud.toml` from the same folder.
+On Cloudflare a Worker serves the API, the editor, and the server's own pages, a Durable Object for each document runs its collaboration rooms, Hyperdrive connects to PostgreSQL, and a Cron Trigger every five minutes runs cleanup and retries email. [`packages/cloud/deploy/cloudflare`](https://github.com/open-pencil/open-pencil/tree/master/packages/cloud/deploy/cloudflare) is the deployment to copy: a Wrangler configuration and the Worker's entry, which reads `openpencil-cloud.toml` from the same folder.
-1. Copy the folder beside it, for example to `packages/cloud/deploy/mine`, so its relative paths still reach the runtime and the portal build.
+1. Copy the folder beside it, for example to `packages/cloud/deploy/mine`, so the Worker's entry still reaches the runtime.
2. Create a Hyperdrive configuration for the database with `wrangler hyperdrive create`, and put its ID, your domain, and a Worker name in the copy's `wrangler.jsonc`.
3. Add your TOML as `openpencil-cloud.toml` in the copy; Wrangler bundles it as text. Leave `[database]` empty, since `DATABASE_URL` comes from Hyperdrive, and trust `cf-connecting-ip` under `[authentication.trusted_proxies]`.
4. Migrate from a checkout, with that TOML as `OPENPENCIL_CLOUD_CONFIG` and a direct connection string as `DATABASE_URL`: `bun --filter @open-pencil/cloud migrate`. The Worker never migrates, so do this before every deploy.
-5. Build the portal with `bun run build:packages && bun run build:cloud-portal`, then deploy from the copy with `bunx wrangler deploy --secrets-file <file>`, where the JSON file holds the secrets the TOML names.
+5. Build the site with `bun run build:packages && bun run build:cloud`, then deploy from the copy with `bunx wrangler deploy --assets "$(git rev-parse --show-toplevel)/dist-cloud" --secrets-file secrets.json`, where `secrets.json` holds the secrets the TOML names.
The operator commands below work the same way, from a checkout with a direct connection. The `[workers]` intervals don't apply: mail a request queues is sent when the request finishes, and the Cron Trigger handles the rest.
## The first administrator
-Set `authentication.enrollment_mode = "approval"` for a controlled deployment: a verified identity then creates a pending request that an administrator reviews. Startup never grants roles, so bootstrap the first operator from a repository checkout that reads the same configuration and secrets and can reach the server's database at `DATABASE_URL`:
+Set `[authentication.enrollment] mode = "approval"` for a controlled deployment: a verified identity then creates a pending request that an administrator reviews. Startup never grants roles, so bootstrap the first operator from a repository checkout that reads the same configuration and secrets and can reach the server's database at `DATABASE_URL`:
```sh
bun --filter @open-pencil/cloud admin approve [email protected]
diff --git a/packages/docs/user-guide/openpencil-cloud.md b/packages/docs/user-guide/openpencil-cloud.md
index c386ac18c..8a218b4db 100644
--- a/packages/docs/user-guide/openpencil-cloud.md
+++ b/packages/docs/user-guide/openpencil-cloud.md
@@ -93,7 +93,7 @@ Select **Share** on a Cloud document.
- Invite people by email with **Can edit** or **Can view**. They get an email with a link, and the invitation expires after seven days. Change someone's access or remove it from the list.
- Everyone in the document's workspace has the access the workspace gives them.
-- Under **General access**, **Anyone with the link** lets people open the document without an account, with **Can view** or **Can edit**. Some workspaces' plans turn links off, and the dialog says so.
+- Under **General access**, **Anyone with the link** lets people open the document with **Can view** or **Can edit**. Where the server allows it, they need no account; otherwise they sign in to the server first, and the dialog says which. Some workspaces' plans turn links off, and the dialog says so too.
The server keeps only a fingerprint of each link, so a link can be copied only on the device that created it. On other devices, **Reset link** makes a new one you can copy; the old link stops working.
@@ -107,4 +107,4 @@ Invitation and share links open in the browser. If you use the desktop app, choo
Opening a Cloud document joins its live session: everyone who has it open sees each other's cursors and edits as they happen. One person's app saves the document for everyone, so editing together never makes your changes conflict with someone else's.
-People who open a link without an account join under the name OpenPencil gives them, or the one they chose. They edit when the link allows it, but their app never saves to the server; someone signed in who can edit saves for them.
+People who open a link without an account, where the server allows it, join under the name OpenPencil gives them, or the one they chose. They edit when the link allows it, but their app never saves to the server; someone signed in who can edit saves for them.
diff --git a/packages/vue/src/i18n/locales/de/cloud/editor.json b/packages/vue/src/i18n/locales/de/cloud/editor.json
index 173311edb..4a6a56750 100644
--- a/packages/vue/src/i18n/locales/de/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/de/cloud/editor.json
@@ -106,6 +106,7 @@
"shareRestricted": "Nur Personen mit Zugriff",
"shareAnyoneWithLink": "Jeder mit dem Link",
"shareLinkDetail": "Jeder, der den Link hat, kann diese Datei ohne Anmeldung öffnen.",
+ "shareLinkSignInDetail": "Alle mit dem Link können diese Datei öffnen, nachdem sie sich hier angemeldet haben.",
"shareRestrictedDetail": "Nur die oben genannten Personen und der Arbeitsbereich können diese Datei öffnen.",
"shareRestrictedNoLinksDetail": "Nur die oben genannten Personen und der Arbeitsbereich können diese Datei öffnen. Links sind für diesen Arbeitsbereich deaktiviert.",
"shareLinkPermission": "Linkberechtigung",
diff --git a/packages/vue/src/i18n/locales/de/cloud/portal.json b/packages/vue/src/i18n/locales/de/cloud/portal.json
index f00e77947..f674989fe 100644
--- a/packages/vue/src/i18n/locales/de/cloud/portal.json
+++ b/packages/vue/src/i18n/locales/de/cloud/portal.json
@@ -5,6 +5,11 @@
"unavailableTitle": "Dieser Server antwortet nicht",
"unavailableDescription": "Prüfe die Adresse oder versuche es gleich noch einmal.",
"tryAgain": "Erneut versuchen",
+ "welcomeTitle": "Gemeinsam gestalten in OpenPencil",
+ "welcomeDescription": "Speichere deine Dateien auf diesem Server, teile sie und bearbeite sie live mit anderen.",
+ "useWithoutAccount": "Ohne Konto nutzen",
+ "withoutAccountNote": "Ohne Konto bleiben Dateien auf diesem Gerät.",
+ "openEditor": "Editor öffnen",
"signInTitle": "Bei OpenPencil Cloud anmelden",
"signUpTitle": "Konto erstellen",
"returnsTo": "Danach geht es zurück zu {destination}.",
diff --git a/packages/vue/src/i18n/locales/es/cloud/editor.json b/packages/vue/src/i18n/locales/es/cloud/editor.json
index 6c465fafa..108cf55a2 100644
--- a/packages/vue/src/i18n/locales/es/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/es/cloud/editor.json
@@ -106,6 +106,7 @@
"shareRestricted": "Solo personas con acceso",
"shareAnyoneWithLink": "Cualquiera con el enlace",
"shareLinkDetail": "Cualquiera que tenga el enlace puede abrir este archivo sin iniciar sesión.",
+ "shareLinkSignInDetail": "Cualquiera con el enlace puede abrir este archivo después de iniciar sesión aquí.",
"shareRestrictedDetail": "Solo las personas y el espacio de trabajo indicados arriba pueden abrir este archivo.",
"shareRestrictedNoLinksDetail": "Solo las personas y el espacio de trabajo indicados arriba pueden abrir este archivo. Los enlaces están desactivados en este espacio de trabajo.",
"shareLinkPermission": "Permiso del enlace",
diff --git a/packages/vue/src/i18n/locales/es/cloud/portal.json b/packages/vue/src/i18n/locales/es/cloud/portal.json
index 0c0b6781a..5bfae283c 100644
--- a/packages/vue/src/i18n/locales/es/cloud/portal.json
+++ b/packages/vue/src/i18n/locales/es/cloud/portal.json
@@ -5,6 +5,11 @@
"unavailableTitle": "Este servidor no responde",
"unavailableDescription": "Comprueba la dirección o inténtalo de nuevo en un momento.",
"tryAgain": "Reintentar",
+ "welcomeTitle": "Diseña en equipo con OpenPencil",
+ "welcomeDescription": "Guarda tus archivos en este servidor, compártelos y edítalos con otras personas en tiempo real.",
+ "useWithoutAccount": "Usar sin cuenta",
+ "withoutAccountNote": "Sin cuenta, los archivos se quedan en este dispositivo.",
+ "openEditor": "Abrir editor",
"signInTitle": "Inicia sesión en OpenPencil Cloud",
"signUpTitle": "Crea tu cuenta",
"returnsTo": "Después volverás a {destination}.",
diff --git a/packages/vue/src/i18n/locales/fr/cloud/editor.json b/packages/vue/src/i18n/locales/fr/cloud/editor.json
index 6314ebc5e..6b5bf3dd4 100644
--- a/packages/vue/src/i18n/locales/fr/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/fr/cloud/editor.json
@@ -106,6 +106,7 @@
"shareRestricted": "Uniquement les personnes ayant accès",
"shareAnyoneWithLink": "Toute personne disposant du lien",
"shareLinkDetail": "Toute personne disposant du lien peut ouvrir ce fichier sans se connecter.",
+ "shareLinkSignInDetail": "Toute personne disposant du lien peut ouvrir ce fichier après s’être connectée ici.",
"shareRestrictedDetail": "Seuls les personnes et l’espace de travail ci-dessus peuvent ouvrir ce fichier.",
"shareRestrictedNoLinksDetail": "Seuls les personnes et l’espace de travail ci-dessus peuvent ouvrir ce fichier. Les liens sont désactivés pour cet espace de travail.",
"shareLinkPermission": "Autorisation du lien",
diff --git a/packages/vue/src/i18n/locales/fr/cloud/portal.json b/packages/vue/src/i18n/locales/fr/cloud/portal.json
index 713eac237..e486e64e8 100644
--- a/packages/vue/src/i18n/locales/fr/cloud/portal.json
+++ b/packages/vue/src/i18n/locales/fr/cloud/portal.json
@@ -5,6 +5,11 @@
"unavailableTitle": "Ce serveur ne répond pas",
"unavailableDescription": "Vérifiez l’adresse ou réessayez dans un instant.",
"tryAgain": "Réessayer",
+ "welcomeTitle": "Concevez ensemble dans OpenPencil",
+ "welcomeDescription": "Gardez vos fichiers sur ce serveur, partagez-les et modifiez-les à plusieurs en direct.",
+ "useWithoutAccount": "Utiliser sans compte",
+ "withoutAccountNote": "Sans compte, les fichiers restent sur cet appareil.",
+ "openEditor": "Ouvrir l’éditeur",
"signInTitle": "Se connecter à OpenPencil Cloud",
"signUpTitle": "Créer votre compte",
"returnsTo": "Vous reviendrez ensuite à {destination}.",
diff --git a/packages/vue/src/i18n/locales/it/cloud/editor.json b/packages/vue/src/i18n/locales/it/cloud/editor.json
index 467266107..34ae6ad24 100644
--- a/packages/vue/src/i18n/locales/it/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/it/cloud/editor.json
@@ -106,6 +106,7 @@
"shareRestricted": "Solo persone con accesso",
"shareAnyoneWithLink": "Chiunque abbia il link",
"shareLinkDetail": "Chiunque abbia il link può aprire questo file senza accedere.",
+ "shareLinkSignInDetail": "Chiunque abbia il link può aprire questo file dopo aver effettuato l’accesso qui.",
"shareRestrictedDetail": "Solo le persone e l’area di lavoro indicate sopra possono aprire questo file.",
"shareRestrictedNoLinksDetail": "Solo le persone e l’area di lavoro indicate sopra possono aprire questo file. I link sono disattivati per quest’area di lavoro.",
"shareLinkPermission": "Autorizzazione del link",
diff --git a/packages/vue/src/i18n/locales/it/cloud/portal.json b/packages/vue/src/i18n/locales/it/cloud/portal.json
index f1c732aee..a8a6598dd 100644
--- a/packages/vue/src/i18n/locales/it/cloud/portal.json
+++ b/packages/vue/src/i18n/locales/it/cloud/portal.json
@@ -5,6 +5,11 @@
"unavailableTitle": "Questo server non risponde",
"unavailableDescription": "Controlla l’indirizzo o riprova tra un momento.",
"tryAgain": "Riprova",
+ "welcomeTitle": "Progetta insieme in OpenPencil",
+ "welcomeDescription": "Conserva i file su questo server, condividili e modificali con altri in tempo reale.",
+ "useWithoutAccount": "Usa senza account",
+ "withoutAccountNote": "Senza account, i file restano su questo dispositivo.",
+ "openEditor": "Apri l’editor",
"signInTitle": "Accedi a OpenPencil Cloud",
"signUpTitle": "Crea il tuo account",
"returnsTo": "Poi tornerai a {destination}.",
diff --git a/packages/vue/src/i18n/locales/ja/cloud/editor.json b/packages/vue/src/i18n/locales/ja/cloud/editor.json
index 7be0e2d9d..a17237619 100644
--- a/packages/vue/src/i18n/locales/ja/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/ja/cloud/editor.json
@@ -105,6 +105,7 @@
"shareRestricted": "アクセス権のあるユーザーのみ",
"shareAnyoneWithLink": "リンクを知っている全員",
"shareLinkDetail": "リンクを知っている人は誰でも、サインインせずにこのファイルを開けます。",
+ "shareLinkSignInDetail": "リンクを知っている人は、ここにサインインした後でこのファイルを開けます。",
"shareRestrictedDetail": "このファイルを開けるのは、上記のユーザーとワークスペースだけです。",
"shareRestrictedNoLinksDetail": "このファイルを開けるのは、上記のユーザーとワークスペースだけです。このワークスペースではリンクがオフになっています。",
"shareLinkPermission": "リンクの権限",
diff --git a/packages/vue/src/i18n/locales/ja/cloud/portal.json b/packages/vue/src/i18n/locales/ja/cloud/portal.json
index 3d4536a96..ee5ba89f5 100644
--- a/packages/vue/src/i18n/locales/ja/cloud/portal.json
+++ b/packages/vue/src/i18n/locales/ja/cloud/portal.json
@@ -5,6 +5,11 @@
"unavailableTitle": "このサーバーが応答していません",
"unavailableDescription": "アドレスを確認するか、しばらくしてからもう一度お試しください。",
"tryAgain": "もう一度試す",
+ "welcomeTitle": "OpenPencil で一緒にデザイン",
+ "welcomeDescription": "ファイルをこのサーバーに保存し、共有して、ほかの人とリアルタイムで編集できます。",
+ "useWithoutAccount": "アカウントなしで使う",
+ "withoutAccountNote": "アカウントがない場合、ファイルはこのデバイスに保存されます。",
+ "openEditor": "エディターを開く",
"signInTitle": "OpenPencil Cloud にサインイン",
"signUpTitle": "アカウントを作成",
"returnsTo": "完了すると{destination}に戻ります。",
diff --git a/packages/vue/src/i18n/locales/pl/cloud/editor.json b/packages/vue/src/i18n/locales/pl/cloud/editor.json
index 65a037192..66de5a820 100644
--- a/packages/vue/src/i18n/locales/pl/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/pl/cloud/editor.json
@@ -107,6 +107,7 @@
"shareRestricted": "Tylko osoby z dostępem",
"shareAnyoneWithLink": "Każdy, kto ma link",
"shareLinkDetail": "Każdy, kto ma link, może otworzyć ten plik bez logowania.",
+ "shareLinkSignInDetail": "Każdy, kto ma link, może otworzyć ten plik po zalogowaniu się tutaj.",
"shareRestrictedDetail": "Ten plik mogą otworzyć tylko osoby i obszar roboczy wymienione powyżej.",
"shareRestrictedNoLinksDetail": "Ten plik mogą otworzyć tylko osoby i obszar roboczy wymienione powyżej. Linki są wyłączone w tym obszarze roboczym.",
"shareLinkPermission": "Uprawnienia linku",
diff --git a/packages/vue/src/i18n/locales/pl/cloud/portal.json b/packages/vue/src/i18n/locales/pl/cloud/portal.json
index c71a0755a..47092ce75 100644
--- a/packages/vue/src/i18n/locales/pl/cloud/portal.json
+++ b/packages/vue/src/i18n/locales/pl/cloud/portal.json
@@ -5,6 +5,11 @@
"unavailableTitle": "Ten serwer nie odpowiada",
"unavailableDescription": "Sprawdź adres lub spróbuj ponownie za chwilę.",
"tryAgain": "Spróbuj ponownie",
+ "welcomeTitle": "Projektuj razem w OpenPencil",
+ "welcomeDescription": "Przechowuj pliki na tym serwerze, udostępniaj je i edytuj razem z innymi na żywo.",
+ "useWithoutAccount": "Używaj bez konta",
+ "withoutAccountNote": "Bez konta pliki zostają na tym urządzeniu.",
+ "openEditor": "Otwórz edytor",
"signInTitle": "Zaloguj się do OpenPencil Cloud",
"signUpTitle": "Utwórz konto",
"returnsTo": "Następnie wrócisz do {destination}.",
diff --git a/packages/vue/src/i18n/locales/ru/cloud/editor.json b/packages/vue/src/i18n/locales/ru/cloud/editor.json
index a70c44944..90c1564e3 100644
--- a/packages/vue/src/i18n/locales/ru/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/ru/cloud/editor.json
@@ -107,6 +107,7 @@
"shareRestricted": "Только люди с доступом",
"shareAnyoneWithLink": "Все, у кого есть ссылка",
"shareLinkDetail": "Любой, у кого есть ссылка, может открыть этот файл без входа.",
+ "shareLinkSignInDetail": "Любой, у кого есть ссылка, сможет открыть этот файл, войдя здесь в аккаунт.",
"shareRestrictedDetail": "Открыть этот файл могут только люди и рабочее пространство, указанные выше.",
"shareRestrictedNoLinksDetail": "Открыть этот файл могут только люди и рабочее пространство, указанные выше. Ссылки в этом рабочем пространстве отключены.",
"shareLinkPermission": "Права по ссылке",
diff --git a/packages/vue/src/i18n/locales/ru/cloud/portal.json b/packages/vue/src/i18n/locales/ru/cloud/portal.json
index 8458e7345..ceff496f4 100644
--- a/packages/vue/src/i18n/locales/ru/cloud/portal.json
+++ b/packages/vue/src/i18n/locales/ru/cloud/portal.json
@@ -5,6 +5,11 @@
"unavailableTitle": "Сервер не отвечает",
"unavailableDescription": "Проверьте адрес или попробуйте чуть позже.",
"tryAgain": "Попробовать снова",
+ "welcomeTitle": "Проектируйте вместе в OpenPencil",
+ "welcomeDescription": "Храните файлы на этом сервере, делитесь ими и редактируйте вместе с другими в реальном времени.",
+ "useWithoutAccount": "Пользоваться без аккаунта",
+ "withoutAccountNote": "Без аккаунта файлы остаются на этом устройстве.",
+ "openEditor": "Открыть редактор",
"signInTitle": "Вход в OpenPencil Cloud",
"signUpTitle": "Создание аккаунта",
"returnsTo": "Затем вы вернётесь в {destination}.",
diff --git a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json
index 86d2df94b..0f6319f9e 100644
--- a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json
@@ -105,6 +105,7 @@
"shareRestricted": "仅限有访问权限的人",
"shareAnyoneWithLink": "任何拥有链接的人",
"shareLinkDetail": "任何拥有链接的人无需登录即可打开此文件。",
+ "shareLinkSignInDetail": "任何拥有链接的人在此登录后都可以打开此文件。",
"shareRestrictedDetail": "只有上方的成员和工作区可以打开此文件。",
"shareRestrictedNoLinksDetail": "只有上方的成员和工作区可以打开此文件。此工作区已关闭链接分享。",
"shareLinkPermission": "链接权限",
diff --git a/packages/vue/src/i18n/locales/zh-cn/cloud/portal.json b/packages/vue/src/i18n/locales/zh-cn/cloud/portal.json
index 73c9f5106..0e7bb37ef 100644
--- a/packages/vue/src/i18n/locales/zh-cn/cloud/portal.json
+++ b/packages/vue/src/i18n/locales/zh-cn/cloud/portal.json
@@ -5,6 +5,11 @@
"unavailableTitle": "此服务器没有响应",
"unavailableDescription": "请检查地址,或稍后重试。",
"tryAgain": "重试",
+ "welcomeTitle": "在 OpenPencil 中协作设计",
+ "welcomeDescription": "将文件保存在此服务器上,与他人共享并实时协作编辑。",
+ "useWithoutAccount": "不登录直接使用",
+ "withoutAccountNote": "不登录时,文件保存在此设备上。",
+ "openEditor": "打开编辑器",
"signInTitle": "登录 OpenPencil Cloud",
"signUpTitle": "创建账号",
"returnsTo": "完成后将返回{destination}。",
diff --git a/packages/vue/src/i18n/messages/cloud/editor.ts b/packages/vue/src/i18n/messages/cloud/editor.ts
index 0c1d025e6..b52f7e63f 100644
--- a/packages/vue/src/i18n/messages/cloud/editor.ts
+++ b/packages/vue/src/i18n/messages/cloud/editor.ts
@@ -146,6 +146,7 @@ export const cloudMessageDefaults = {
shareRestricted: 'Only people with access',
shareAnyoneWithLink: 'Anyone with the link',
shareLinkDetail: 'Anyone who has the link can open this file without signing in.',
+ shareLinkSignInDetail: 'Anyone who has the link can open this file after signing in here.',
shareRestrictedDetail: 'Only the people and workspace above can open this file.',
shareRestrictedNoLinksDetail:
'Only the people and workspace above can open this file. Links are turned off for this workspace.',
diff --git a/packages/vue/src/i18n/messages/cloud/portal.ts b/packages/vue/src/i18n/messages/cloud/portal.ts
index d8b57078c..71afa4a34 100644
--- a/packages/vue/src/i18n/messages/cloud/portal.ts
+++ b/packages/vue/src/i18n/messages/cloud/portal.ts
@@ -11,6 +11,12 @@ export const cloudPortalMessageDefaults = {
unavailableDescription: 'Check the address, or try again in a moment.',
tryAgain: 'Try again',
+ welcomeTitle: 'Design together in OpenPencil',
+ welcomeDescription: 'Keep your files on this server, share them, and edit them with others live.',
+ useWithoutAccount: 'Use without an account',
+ withoutAccountNote: 'Without an account, files stay on this device.',
+ openEditor: 'Open editor',
+
signInTitle: 'Sign in to OpenPencil Cloud',
signUpTitle: 'Create your account',
returnsTo: params('Then you go back to {destination}.'),
diff --git a/src/AGENTS.md b/src/AGENTS.md
index 78dcb5295..e46e28302 100644
--- a/src/AGENTS.md
+++ b/src/AGENTS.md
@@ -31,9 +31,10 @@ Root Tauri/Vite app. Services and state live under `src/app/**`, views under `sr
- Outside Cloud's own folders, app code reaches Cloud only through `@/app/cloud/integration` (and its `/storage` provider list) and components through `@/components/cloud/integration`; a `VITE_OPENPENCIL_CLOUD=off` build swaps both for their `off` stand-ins, which must keep the same names (`tests/app/cloud/integration/off.test.ts`), and must bundle no other Cloud module (`bun run check:cloud-off`).
- Cloud servers are profiles of the `openpencil-cloud` storage provider (server = profile, workspace = container) and their sessions its credential; app code reaches a server through `src/app/cloud/sessions/connection.ts`, never with its own fetch (`tests/app/cloud/sessions/connection.test.ts`).
- An open Cloud document is live in its relay room, and only the elected saver (`electCloudSaver` in `src/app/cloud/rooms/live.ts`) uploads its revisions; guests from a link never save (`tests/integration/collab/cloud-relay.test.ts`).
-- The Cloud portal is its own entry (`cloud.html`, `src/cloud/`, `src/views/cloud/`) served by the Cloud server, not the editor; it must not import editor sessions, CanvasKit, or `src/app/shell/**`, so `bun run build:cloud-portal` stays small (`open-pencil/no-editor-imports-in-cloud-portal`, `check:arch`).
+- The Cloud portal is its own entry (`cloud.html`, `src/cloud/`, `src/views/cloud/`) that the Cloud server serves beside the editor (`bun run build:cloud`); it must not import editor sessions, CanvasKit, or `src/app/shell/**`, so its pages load without the editor (`open-pencil/no-editor-imports-in-cloud-portal`, `check:arch`).
- The team's metrics dashboard is its own entry too (`metrics.html`, `src/metrics/`, `src/views/metrics/`), built by `bun run build:metrics` into `dist-metrics/` with base `/admin/` and served only by the feedback Worker behind Cloudflare Access; it follows the Cloud portal's isolation rule and reads its numbers through `@open-pencil/feedback/client` (`packages/feedback/tests/admin.test.ts`).
-- Which portal pages a visitor may open, by sign-in and account standing, is decided in `portalDestination` alone (`tests/app/cloud-portal/navigation.test.ts`).
+- Which portal pages a visitor may open, by sign-in and account standing, is decided in `portalDestination` alone, and whether an editor page opens the editor or the welcome page in `siteDestination` (`tests/app/cloud-portal/navigation.test.ts`, `site.test.ts`).
+- On a Cloud server's own build (`__OPENPENCIL_CLOUD_SITE__`), `src/main.ts` runs the welcome check (`enterCloudSite` in `src/app/cloud-portal/site.ts`) after the support check and before `boot()`, so signed-out visitors never load the editor (`tests/app/cloud-portal/site.test.ts`).
- A room is a document: every room tab owns its session (`src/app/collab/rooms.ts`, `session.ts`), joining always opens a new tab, and only Share binds an existing document; the collaboration UI reads the active tab's room through `useCollab()` and publishes cursors through the canvas's own tab (`tests/app/collab/session.test.ts`, `tests/e2e/collab/rooms.spec.ts`).
- A shared document records each layer's parent history, order key and page, never `parentId` or `childIds`, and only Share or a room's conversion sets its root in `meta`; local edits are written by `writeLocalPlacement` and remote changes applied by `applySharedTree` in `src/app/collab/shared-tree/sync.ts`, which resolve the tree with `LayerTree` from `src/app/collab/tree/` (`tests/app/collab/random-edits.test.ts`).
- A room's voice call lives in its session (`src/app/collab/voice/room.ts`): who is in it and muted travels in awareness, the microphone goes only to peers in the call through the transport's `media`, and speaking comes from WebRTC's reported audio levels. One window holds one call, owned by `useVoiceCall()` in `src/app/collab/voice/call.ts`, which opens the microphone with VueUse and ends the call when its room goes (`tests/app/collab/voice/room.test.ts`).
diff --git a/src/app/cloud-portal/navigation.ts b/src/app/cloud-portal/navigation.ts
index f748889e3..de865fe6c 100644
--- a/src/app/cloud-portal/navigation.ts
+++ b/src/app/cloud-portal/navigation.ts
@@ -3,8 +3,11 @@ import type { LocationQuery, RouteLocationRaw, RouteMeta } from 'vue-router'
import { cloudRedirectPath } from '@open-pencil/cloud/client'
import type { CloudAccountStatus } from '@open-pencil/cloud/contract'
-/** Where signed-in people land when nothing else asked for them. */
-export const PORTAL_HOME = '/account'
+/** Where signed-in people land when nothing else asked for them: the editor. */
+export const PORTAL_HOME = '/'
+
+/** The signed-in person's own settings, where a page they may not open sends them. */
+export const ACCOUNT_PAGE = '/account'
/** A same-origin path to continue to after a sign-in step, from a `redirect` query value. */
export function continuationPath(value: unknown): string {
@@ -55,13 +58,15 @@ export function portalDestination(
to: PortalRouteTarget,
account: CloudAccountStatus | null
): true | RouteLocationRaw {
- if (to.meta.signedOut && account) return continuationPath(to.query.redirect)
+ if (to.meta.signedOut && account) {
+ return standingPath(account) ?? continuationPath(to.query.redirect)
+ }
if (!to.meta.account) return true
if (!account) return { name: 'sign-in', query: { redirect: to.fullPath } }
const standing = standingPath(account)
if (standing && to.path !== standing) return standing
// An active account has nothing waiting or declined to read about.
if (!standing && STANDING_PAGES.has(to.path)) return PORTAL_HOME
- if (to.meta.admin && account.user.deploymentRole !== 'admin') return PORTAL_HOME
+ if (to.meta.admin && account.user.deploymentRole !== 'admin') return ACCOUNT_PAGE
return true
}
diff --git a/src/app/cloud-portal/site.ts b/src/app/cloud-portal/site.ts
new file mode 100644
index 000000000..21f07b667
--- /dev/null
+++ b/src/app/cloud-portal/site.ts
@@ -0,0 +1,97 @@
+import { useLocalStorage } from '@vueuse/core'
+
+import {
+ CloudPortalAPIError,
+ createCloudPortalClient,
+ discoverCloud,
+ type CloudPortalClient
+} from '@open-pencil/cloud/client'
+import type { CloudAccountStatus } from '@open-pencil/cloud/contract'
+
+/**
+ * A Cloud server serves the editor to signed-in people and, where the server allows the local
+ * editor, to visitors who chose to use it without an account; everyone else gets the welcome
+ * page first.
+ */
+export const WELCOME_PATH = '/welcome'
+
+const CLOUD_LINK_PATH = /^\/cloud\/(documents|share|invitations)\/[^/]+$/
+
+/**
+ * Whether an address is a link to a document, a shared file, or an invitation, which sign in on
+ * their own: it names its server, and a shared file or invitation carries its secret.
+ */
+export function isCloudLink(url: URL): boolean {
+ const [, kind] = url.pathname.match(CLOUD_LINK_PATH) ?? []
+ if (!kind || !url.searchParams.get('server')) return false
+ return kind === 'documents' || url.hash.length > 1
+}
+
+/** Whether this browser chose to use the server's editor without an account. */
+const localEditor = useLocalStorage('open-pencil:cloud-site-local', false, {
+ // Written before the page leaves for the editor.
+ flush: 'sync',
+ writeDefaults: false
+})
+
+/** Opens the server's editor without an account, now and on later visits from this browser. */
+export function openLocalEditor(): void {
+ localEditor.value = true
+ globalThis.location.assign('/')
+}
+
+/** Who is signed in to the server, or `unreachable` when it cannot say. */
+export type SiteAccount = CloudAccountStatus | null | 'unreachable'
+
+/**
+ * Where a visit to an editor page belongs: null for the editor, or the welcome page, which sends
+ * an account waiting for review on to its standing page. An account that may use the server
+ * gets the editor, and so does an unreachable server, since the editor works without it.
+ * Without an account, the root asks first unless this browser chose the local editor, and every
+ * page does where the server does not allow it.
+ */
+export function siteDestination(visit: {
+ path: string
+ account: SiteAccount
+ localEditor: boolean
+ choseLocalEditor: boolean
+}): string | null {
+ const { path, account } = visit
+ if (account === 'unreachable' || account?.state === 'active') return null
+ if (visit.localEditor && (path !== '/' || visit.choseLocalEditor)) return null
+ return WELCOME_PATH
+}
+
+async function signedInAccount(api: CloudPortalClient): Promise<SiteAccount> {
+ try {
+ return await api.accountStatus()
+ } catch (error) {
+ if (error instanceof CloudPortalAPIError && error.kind === 'authentication-required')
+ return null
+ console.warn('[Cloud] Could not read who is signed in', error)
+ return 'unreachable'
+ }
+}
+
+/**
+ * Before the editor boots on a Cloud server: leaves for the welcome page when the visit belongs
+ * there (`siteDestination`). Returns whether the editor should boot. A server whose discovery
+ * fails is taken not to allow the local editor; one that cannot say who is signed in at all is
+ * unreachable, and the editor opens.
+ */
+export async function enterCloudSite(location: Location = globalThis.location): Promise<boolean> {
+ if (isCloudLink(new URL(location.href))) return true
+ const [discovery, account] = await Promise.all([
+ discoverCloud(location.origin).catch(() => null),
+ signedInAccount(createCloudPortalClient({ baseURL: location.origin }))
+ ])
+ const destination = siteDestination({
+ path: location.pathname,
+ account,
+ localEditor: discovery?.localEditor ?? false,
+ choseLocalEditor: localEditor.value
+ })
+ if (!destination) return true
+ location.replace(destination)
+ return false
+}
diff --git a/src/app/cloud/availability.ts b/src/app/cloud/availability.ts
index 3502e57ff..76386c1e3 100644
--- a/src/app/cloud/availability.ts
+++ b/src/app/cloud/availability.ts
@@ -2,7 +2,7 @@ import { useLocalStorage } from '@vueuse/core'
import { computed, ref } from 'vue'
import { APP_VERSION } from '@/app/runtime/version'
-import { IS_BROWSER, OFFICIAL_CLOUD_URL } from '@/constants'
+import { IS_BROWSER, IS_CLOUD_SITE, OFFICIAL_CLOUD_URL } from '@/constants'
import { discoverCloudServer } from './sessions/connection'
@@ -36,12 +36,14 @@ export function isVersionAtLeast(version: string, minimum: string): boolean {
}
/**
- * Whether the official server is open to this editor, or being previewed here; until then
- * Settings offers its waitlist.
+ * Whether the official server is open to this editor, being previewed here, or serving this
+ * editor itself; until then Settings offers its waitlist.
*/
export const cloudOfficialListed = computed(
() =>
- preview.value || (listedFrom.value !== null && isVersionAtLeast(APP_VERSION, listedFrom.value))
+ IS_CLOUD_SITE ||
+ preview.value ||
+ (listedFrom.value !== null && isVersionAtLeast(APP_VERSION, listedFrom.value))
)
/** Reads the preview switch from the address and asks the official server whether it is listed. */
diff --git a/src/app/cloud/documents/link.ts b/src/app/cloud/documents/link.ts
index ef83e7344..4908cbfb9 100644
--- a/src/app/cloud/documents/link.ts
+++ b/src/app/cloud/documents/link.ts
@@ -8,11 +8,11 @@ import { cloudMessages } from '@open-pencil/vue/i18n'
import type { EditorStore } from '@/app/editor/session'
import { toast } from '@/app/shell/ui'
import { openStorageDocumentInNewTab } from '@/app/tabs'
-import { IS_BROWSER, OFFICIAL_CLOUD_URL } from '@/constants'
+import { IS_BROWSER } from '@/constants'
import { cloudSignedIn, openCloudConnect } from '../connect/flow'
import { cloudServerHost, normalizeCloudServerURL } from '../servers/address'
-import { addCloudServer, cloudServers, findCloudServer } from '../servers/store'
+import { cloudServerForLink, findCloudServer } from '../servers/store'
import { cloudAPIClient, cloudConnection } from '../sessions/connection'
import { CLOUD_STORAGE_PROVIDER_ID } from '../sessions/token'
import { openVersionHistory, previewVersion, versionHistoryOf } from '../versions/history'
@@ -107,9 +107,7 @@ export async function openCloudDocumentLink(link: CloudDocumentLink): Promise<vo
toast.error(messages.documentLinkFailed)
return
}
- let server = cloudServers.value.find((candidate) => candidate.url === url) ?? null
- if (!server && url === OFFICIAL_CLOUD_URL)
- server = await addCloudServer({ kind: 'official', url })
+ const server = await cloudServerForLink(url)
if (!server) {
toast.error(messages.documentLinkUnknownServer({ host: cloudServerHost(url) }))
return
diff --git a/src/app/cloud/links.ts b/src/app/cloud/links.ts
index d24f4af9a..5fa81579f 100644
--- a/src/app/cloud/links.ts
+++ b/src/app/cloud/links.ts
@@ -1,4 +1,6 @@
+import { useSessionStorage } from '@vueuse/core'
import * as v from 'valibot'
+import { ref, watch } from 'vue'
import { cloudDesktopLinkURL, type CloudLinkKind } from '@open-pencil/cloud/contract'
import { useViewportKind } from '@open-pencil/vue/editor/viewport-kind'
@@ -9,7 +11,10 @@ import { isTauri } from '@/app/tauri/env'
import { bindDesktopLinkQueue } from '@/app/tauri/link-queue'
import { IS_BROWSER } from '@/constants'
+import { cloudSignedIn, openCloudConnect } from './connect/flow'
import { beginCloudInvitation } from './invitations/flow'
+import { cloudServerHost, normalizeCloudServerURL } from './servers/address'
+import { cloudServerForLink, findCloudServer } from './servers/store'
import { openCloudShareLink } from './sharing/link'
/**
@@ -56,19 +61,55 @@ export function canOfferDesktopApp(): boolean {
return IS_BROWSER && !isTauri() && !useViewportKind().isMobile.value
}
-/** Opens an invitation's dialog, or a shared document as a guest. */
+/**
+ * A shared link this tab is opening while it signs in, kept for the tab so it survives leaving for
+ * the server's sign-in pages, as an invitation is.
+ */
+const signingIn = IS_BROWSER
+ ? useSessionStorage<string | null>('open-pencil:cloud-share-link', null)
+ : ref<string | null>(null)
+
+/** Drops a shared link kept while signing in, as when the tab opens with another link. */
+export function forgetCloudLink(): void {
+ signingIn.value = null
+}
+
+/** Signs in to the server a link names, then opens the link again; see `resumeCloudLink`. */
+async function signInForLink(link: CloudLink): Promise<void> {
+ const url = normalizeCloudServerURL(link.server)
+ const server = url ? await cloudServerForLink(url) : null
+ if (!url || !server) {
+ const host = url ? cloudServerHost(url) : link.server
+ toast.error(cloudMessages.get().documentLinkUnknownServer({ host }))
+ return
+ }
+ signingIn.value = JSON.stringify(link satisfies CloudLink)
+ openCloudConnect({ serverId: server.id })
+}
+
+/** Opens an invitation's dialog, or a shared document. */
export async function openCloudLink(link: CloudLink): Promise<void> {
if (link.kind === 'invitations') {
beginCloudInvitation(link.id, link.server, link.secret)
return
}
const messages = cloudMessages.get()
+ signingIn.value = null
+ let outcome: 'opened' | 'sign-in'
try {
- await openCloudShareLink({ shareId: link.id, server: link.server, secret: link.secret })
+ outcome = await openCloudShareLink({
+ shareId: link.id,
+ server: link.server,
+ secret: link.secret
+ })
} catch {
toast.error(messages.shareLinkFailed)
return
}
+ if (outcome === 'sign-in') {
+ await signInForLink(link)
+ return
+ }
if (canOfferDesktopApp()) {
toast.info(messages.shareOpenedInBrowser, {
label: messages.openInDesktopApp,
@@ -77,6 +118,20 @@ export async function openCloudLink(link: CloudLink): Promise<void> {
}
}
+/** Opens a shared link again once signing in for it finished. */
+export function resumeCloudLink(): () => void {
+ return watch(cloudSignedIn, (signedIn) => {
+ const parsed = v.safeParse(
+ v.pipe(v.string(), v.parseJson(), cloudLinkSchema),
+ signingIn.value ?? ''
+ )
+ if (!signedIn || !parsed.success) return
+ const url = normalizeCloudServerURL(parsed.output.server)
+ if (url !== findCloudServer(signedIn.serverId)?.url) return
+ void openCloudLink(parsed.output)
+ })
+}
+
/**
* Opens the Cloud links the desktop app received, at startup and while running. The native side
* validates each link before it gets here.
diff --git a/src/app/cloud/servers/store.ts b/src/app/cloud/servers/store.ts
index ede9eb04f..122edd793 100644
--- a/src/app/cloud/servers/store.ts
+++ b/src/app/cloud/servers/store.ts
@@ -103,6 +103,31 @@ export async function addCloudServer(input: {
return server
}
+/**
+ * On the editor a Cloud server serves on its own address, that server, which the server's own
+ * sign-in session reaches without a token. The first server goes on Home.
+ */
+export async function addCloudSiteServer(
+ origin = globalThis.location.origin
+): Promise<CloudServer> {
+ const official = normalizeCloudServerURL(OFFICIAL_CLOUD_URL)
+ return normalizeCloudServerURL(origin) === official
+ ? addCloudServer({ kind: 'official' })
+ : addCloudServer({ kind: 'self-hosted', url: origin })
+}
+
+/**
+ * The server a link names: one this app knows, or the official one, which a link may add. Null
+ * for any other, so a link alone never connects the app anywhere new.
+ */
+export async function cloudServerForLink(url: string): Promise<CloudServer | null> {
+ const known = state.value.servers.find((server) => server.url === url)
+ if (known) return known
+ return url === normalizeCloudServerURL(OFFICIAL_CLOUD_URL)
+ ? addCloudServer({ kind: 'official' })
+ : null
+}
+
/** Forgets a server; Home moves to the next one. */
export function removeCloudServer(id: string): void {
const current = state.value
diff --git a/src/app/cloud/sessions/startup.ts b/src/app/cloud/sessions/startup.ts
index 73ae153a0..0f07574f6 100644
--- a/src/app/cloud/sessions/startup.ts
+++ b/src/app/cloud/sessions/startup.ts
@@ -1,3 +1,5 @@
+import { IS_CLOUD_SITE } from '@/constants'
+
import { checkCloudAvailability } from '../availability'
import { cloudSignedIn } from '../connect/flow'
import {
@@ -7,27 +9,39 @@ import {
resumeCloudDocumentLink
} from '../documents/link'
import { resumeCloudInvitation } from '../invitations/flow'
-import { bindDesktopCloudLinks, openCloudLink, readCloudLink } from '../links'
-import { cloudServers, findCloudServer } from '../servers/store'
+import {
+ bindDesktopCloudLinks,
+ forgetCloudLink,
+ openCloudLink,
+ readCloudLink,
+ resumeCloudLink
+} from '../links'
+import { addCloudSiteServer, cloudServers, findCloudServer } from '../servers/store'
import { refreshCloudConnection } from './connection'
import { takePendingCloudSignIn } from './sign-in'
/**
- * Checks every known server once the app starts, finishes a sign-in this tab left for the
- * server's pages to do, and opens an invitation, a shared link, or a document link the tab was
- * opened with, or the desktop app was sent. A link's secret is taken out of the address at once.
+ * Adds the server that serves this editor, if one does, checks every known server once the app
+ * starts, finishes a sign-in this tab left for the server's pages to do, and opens an invitation,
+ * a shared link, or a document link the tab was opened with, or the desktop app was sent. A
+ * link's secret is taken out of the address at once.
*/
export async function startCloudSessions(options: {
/** Leaves a Cloud link's address, so its secret is not kept in history. */
leaveLinkAddress(): Promise<unknown>
}): Promise<void> {
+ if (IS_CLOUD_SITE) await addCloudSiteServer()
void checkCloudAvailability(globalThis.location.href)
const address = new URL(globalThis.location.href)
const link = readCloudLink(address)
const documentLink = readCloudDocumentLink(address)
// The link the tab opens with is the one to open, not one kept from an earlier sign-in.
- if (documentLink) forgetCloudDocumentLink()
+ if (documentLink || link) {
+ forgetCloudDocumentLink()
+ forgetCloudLink()
+ }
resumeCloudDocumentLink()
+ resumeCloudLink()
if (link) await options.leaveLinkAddress()
const pending = takePendingCloudSignIn()
await Promise.all(cloudServers.value.map((server) => refreshCloudConnection(server)))
diff --git a/src/app/cloud/sharing/document.ts b/src/app/cloud/sharing/document.ts
index 564bc1bee..5e2b941a4 100644
--- a/src/app/cloud/sharing/document.ts
+++ b/src/app/cloud/sharing/document.ts
@@ -32,9 +32,15 @@ export type CloudSharing = {
members: CloudShareMember[]
link: CloudShareLink
/** What the workspace's plan allows for links. */
- links: { allowed: boolean; edit: boolean }
+ links: CloudLinkPolicy
}
+/**
+ * Whether the workspace allows links at all, and whether people who are not signed in to the
+ * server may follow view and edit links; people signed in may follow any link.
+ */
+export type CloudLinkPolicy = { allowed: boolean; guestView: boolean; guestEdit: boolean }
+
type Target = {
server: CloudServer
discovery: CloudDiscovery
@@ -69,7 +75,7 @@ const activeShare = (shares: DocumentShare[]) => shares.find((share) => !share.r
export async function readCloudSharing(target: Target): Promise<CloudSharing> {
const { client, documentId } = target
const access = await client.getDocumentAccess(documentId)
- const closed = { allowed: false, edit: false }
+ const closed: CloudLinkPolicy = { allowed: false, guestView: false, guestEdit: false }
if (!access.canManageSharing) {
return { canManage: false, members: [], link: { access: 'restricted' }, links: closed }
}
@@ -82,9 +88,8 @@ export async function readCloudSharing(target: Target): Promise<CloudSharing> {
: Promise.resolve(null)
])
const features = entitlements?.features
- // Links open the document without an account, so they need anonymous access as well.
- const links = features
- ? { allowed: features.capabilityLinks && features.anonymousView, edit: features.anonymousEdit }
+ const links: CloudLinkPolicy = features
+ ? { allowed: features.links, guestView: features.guestView, guestEdit: features.guestEdit }
: closed
const people = await Promise.all(
grants.map(async (grant) => {
diff --git a/src/app/cloud/sharing/link.ts b/src/app/cloud/sharing/link.ts
index 1754b1b93..d718f872d 100644
--- a/src/app/cloud/sharing/link.ts
+++ b/src/app/cloud/sharing/link.ts
@@ -1,7 +1,7 @@
import { useLocalStorage } from '@vueuse/core'
import { ref } from 'vue'
-import { createCloudAPIClient } from '@open-pencil/cloud/client'
+import { CloudAPIError, createCloudAPIClient } from '@open-pencil/cloud/client'
import { randomHex } from '@open-pencil/scene-graph/random'
import { useCollabIdentity } from '@/app/collab/identity'
@@ -18,7 +18,8 @@ import {
stopWithTab
} from '../rooms/live'
import { normalizeCloudServerURL } from '../servers/address'
-import { cloudFetch, discoverCloudServer } from '../sessions/connection'
+import { cloudServers } from '../servers/store'
+import { cloudFetch, cloudServerFetch, discoverCloudServer } from '../sessions/connection'
/** Who this browser is to rooms it joins from links, kept so a guest stays the same person. */
const guestId = IS_BROWSER
@@ -29,29 +30,41 @@ export type CloudShareLink = { shareId: string; server: string; secret: string }
/**
* Opens a document someone shared by link: its latest revision in a tab of its own, then its
- * room as a guest with the link's permission. A guest has no account on the server, so the tab
- * is a copy that never saves there; edits reach the document through the room.
+ * room with the link's permission. The tab is a copy that never saves to the server; edits reach
+ * the document through the room. Requests carry this app's session with the server when it has
+ * one, since a server may let only people signed in to it follow links. Returns `sign-in` when
+ * the server asks for that.
*/
-export async function openCloudShareLink(link: CloudShareLink): Promise<void> {
+export async function openCloudShareLink(link: CloudShareLink): Promise<'opened' | 'sign-in'> {
const url = normalizeCloudServerURL(link.server)
if (!url) throw new TypeError('The link names no server')
const discovery = await discoverCloudServer(url)
- const client = createCloudAPIClient(discovery.apiURL, { fetch: cloudFetch })
+ const server = cloudServers.value.find((candidate) => candidate.url === url)
+ const client = createCloudAPIClient(discovery.apiURL, {
+ fetch: server ? cloudServerFetch(server.id) : cloudFetch
+ })
const input = {
secret: link.secret,
guestName: useCollabIdentity().name.value,
guestId: guestId.value
}
- const { document } = await client.getSharedDocument(link.shareId, input)
+ let shared: Awaited<ReturnType<typeof client.getSharedDocument>>
+ try {
+ shared = await client.getSharedDocument(link.shareId, input)
+ } catch (error) {
+ if (error instanceof CloudAPIError && error.status === 401) return 'sign-in'
+ throw error
+ }
+ const { document } = shared
const bytes = await downloadCloudDocument(document, (input, init) => storageFetch(input, init))
const name = document.document.name
const store = await openFileInNewTab(
new File([Uint8Array.from(bytes)], `${name}.fig`, { type: 'application/octet-stream' })
)
- if (!discovery.capabilities.collaboration) return
+ if (!discovery.capabilities.collaboration) return 'opened'
const first = await client.getSharedCollaborationTicket(link.shareId, input)
// The tab may have closed while the ticket was on its way.
- if (first.provider !== 'relay' || !first.serverURL || !getTabForStore(store)) return
+ if (first.provider !== 'relay' || !first.serverURL || !getTabForStore(store)) return 'opened'
const room = openCloudDocumentRoom(store, {
roomId: first.roomId,
transport: cloudRelayTransport(
@@ -66,4 +79,5 @@ export async function openCloudShareLink(link: CloudShareLink): Promise<void> {
images: sharedCloudRoomImages(client, link.shareId, input)
})
stopWithTab(store, room)
+ return 'opened'
}
diff --git a/src/cloud/router.ts b/src/cloud/router.ts
index 665310940..2aab2a2c0 100644
--- a/src/cloud/router.ts
+++ b/src/cloud/router.ts
@@ -1,14 +1,24 @@
import { createRouter, createWebHistory } from 'vue-router'
+import { isCloudPortalPage } from '@open-pencil/cloud/contract'
+
import type { PortalContext } from '@/app/cloud-portal/context'
import { PORTAL_HOME, portalDestination } from '@/app/cloud-portal/navigation'
-/** The Cloud portal's pages, guarded by the portal's access rules (`portalDestination`). */
+/**
+ * The Cloud portal's pages, guarded by the portal's access rules (`portalDestination`). The
+ * editor, and anything else the server serves, loads as its own page.
+ */
export function createCloudPortalRouter(context: PortalContext) {
const router = createRouter({
history: createWebHistory(),
routes: [
- { path: '/', redirect: PORTAL_HOME },
+ {
+ path: '/welcome',
+ name: 'welcome',
+ component: () => import('@/views/cloud/WelcomeView.vue'),
+ meta: { signedOut: true }
+ },
{
path: '/auth/sign-in',
name: 'sign-in',
@@ -82,11 +92,16 @@ export function createCloudPortalRouter(context: PortalContext) {
component: () => import('@/views/cloud/ConsoleView.vue'),
meta: { account: true, admin: true }
},
+ // A stale or mistyped portal address, which the server still answers with this page.
{ path: '/:pathMatch(.*)*', redirect: PORTAL_HOME }
]
})
- router.beforeEach((to) => portalDestination(to, context.account.value))
+ router.beforeEach((to) => {
+ if (isCloudPortalPage(to.path)) return portalDestination(to, context.account.value)
+ globalThis.location.assign(to.fullPath)
+ return false
+ })
return router
}
diff --git a/src/components/cloud-portal/layout/PortalConsoleLayout.vue b/src/components/cloud-portal/layout/PortalConsoleLayout.vue
index ffdec7055..732d97c4b 100644
--- a/src/components/cloud-portal/layout/PortalConsoleLayout.vue
+++ b/src/components/cloud-portal/layout/PortalConsoleLayout.vue
@@ -6,14 +6,16 @@ import { useCloudPortalMessages } from '@open-pencil/vue/i18n'
import BrandMark from '@/components/brand/BrandMark.vue'
import AccountAvatar from '@/components/presence/AccountAvatar.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
+import { useAppButtonUI } from '@/theme/button/button'
import { portalLayout } from '@/theme/cloud-portal/layout'
import { sideList } from '@/theme/list/side-list'
import type { PortalSection } from '../types'
/**
- * Signed-in Cloud pages: account settings and, for operators, the deployment console. The side
- * list is drawn like the editor's Pages panel.
+ * Signed-in Cloud pages: account settings and, for operators, the deployment console. The bar
+ * leads back to the editor at the server's root; the side list is drawn like the editor's Pages
+ * panel.
*/
const { host, account, sections, active, heading, description } = defineProps<{
host: string
@@ -29,15 +31,19 @@ const ui = portalLayout()
const messages = useCloudPortalMessages()
const side = sideList()
const groups = () => uniq(sections.map((section) => section.group))
+const editorLink = useAppButtonUI({ variant: 'outline', size: 'sm' })
</script>
<template>
<div :class="ui.page()">
<header :class="ui.bar()">
- <BrandMark variant="micro" decorative />
- <span :class="ui.barTitle()">{{ messages.productName }}</span>
+ <a href="/" :class="ui.barHome()">
+ <BrandMark variant="micro" decorative />
+ <span :class="ui.barTitle()">{{ messages.productName }}</span>
+ </a>
<span :class="ui.barHost()">{{ host }}</span>
<div :class="ui.barEnd()">
+ <a href="/" :class="editorLink.base">{{ messages.openEditor }}</a>
<span :class="ui.barHost()">{{ account.email }}</span>
<AccountAvatar :id="account.id" :name="account.name" />
<IconButton :label="messages.signOut" @click="emit('signOut')">
diff --git a/src/components/cloud/share/CloudShareDialog.vue b/src/components/cloud/share/CloudShareDialog.vue
index 7c3370b00..79905f6c4 100644
--- a/src/components/cloud/share/CloudShareDialog.vue
+++ b/src/components/cloud/share/CloudShareDialog.vue
@@ -3,6 +3,7 @@ import { computed, ref } from 'vue'
import { useCloudMessages, useCommonMessages } from '@open-pencil/vue/i18n'
+import type { CloudLinkPolicy } from '@/app/cloud/sharing/document'
import AccountAvatar from '@/components/presence/AccountAvatar.vue'
import AppButton from '@/components/ui/button/AppButton.vue'
import AppDialogBody from '@/components/ui/dialog/AppDialogBody.vue'
@@ -31,7 +32,7 @@ const {
inviting = false,
copied = false,
sendsLink = false,
- links = { allowed: true, edit: true }
+ links = { allowed: true, guestView: true, guestEdit: true }
} = defineProps<{
documentName: string
/** The workspace the document lives in, when this account belongs to it. */
@@ -43,8 +44,8 @@ const {
copied?: boolean
/** Whether the link goes out through the system share sheet rather than the clipboard. */
sendsLink?: boolean
- /** What the workspace's plan allows for links: any link at all, and links that can edit. */
- links?: { allowed: boolean; edit: boolean }
+ /** What the workspace's plan allows for links, and whether guests may follow them. */
+ links?: CloudLinkPolicy
}>()
const open = defineModel<boolean>('open', { default: false })
@@ -212,7 +213,9 @@ function submitInvite() {
<p :class="ui.accessDetail()">
{{
link.access === 'link'
- ? t.shareLinkDetail
+ ? (link.permission === 'edit' ? links.guestEdit : links.guestView)
+ ? t.shareLinkDetail
+ : t.shareLinkSignInDetail
: links.allowed
? t.shareRestrictedDetail
: t.shareRestrictedNoLinksDetail
@@ -223,11 +226,7 @@ function submitInvite() {
v-if="link.access === 'link' && canManage"
:model-value="link.permission"
:label="t.shareLinkPermission"
- :options="
- links.edit
- ? permissionOptions
- : permissionOptions.filter((option) => option.value === 'view')
- "
+ :options="permissionOptions"
:ui="{ trigger: 'w-28' }"
@update:model-value="emit('changeLink', { ...link, permission: $event })"
/>
diff --git a/src/constants.ts b/src/constants.ts
index 41207bf8f..0eb0c29a8 100644
--- a/src/constants.ts
+++ b/src/constants.ts
@@ -82,8 +82,15 @@ export const WEB_APP_ORIGIN = 'https://app.openpencil.dev'
export const PRIVACY_URL = 'https://openpencil.dev/overview/privacy'
/** The OpenPencil Cloud section of the website, with its waitlist form. */
export const CLOUD_WAITLIST_URL = 'https://openpencil.dev/#cloud'
-/** The hosted OpenPencil Cloud server, offered first when connecting. */
-export const OFFICIAL_CLOUD_URL = 'https://cloud.openpencil.dev'
+/**
+ * The hosted OpenPencil Cloud server, offered first when connecting. An official deployment's own
+ * editor build names that deployment, such as staging.
+ */
+export const OFFICIAL_CLOUD_URL =
+ import.meta.env.VITE_OPENPENCIL_OFFICIAL_CLOUD_URL || 'https://cloud.openpencil.dev'
+/** Whether this is the editor a Cloud server serves on its own address (`bun run build:cloud`). */
+export const IS_CLOUD_SITE =
+ typeof __OPENPENCIL_CLOUD_SITE__ === 'boolean' && __OPENPENCIL_CLOUD_SITE__
/** Where the desktop app's installers are published. */
export const DESKTOP_DOWNLOAD_URL = 'https://github.com/open-pencil/open-pencil/releases/latest'
export const NODE_DOWNLOAD_URL = 'https://nodejs.org/en/download'
diff --git a/src/env.d.ts b/src/env.d.ts
index 984902e73..2d23bc072 100644
--- a/src/env.d.ts
+++ b/src/env.d.ts
@@ -5,9 +5,13 @@
interface ImportMetaEnv {
/** `on` only in official release builds; without it the app sends no pings or usage stats. */
readonly VITE_OPENPENCIL_FEEDBACK?: string
+ /** The official Cloud server's address, set by the build an official deployment serves. */
+ readonly VITE_OPENPENCIL_OFFICIAL_CLOUD_URL?: string
}
declare const __OPENPENCIL_APP_VERSION__: string
+/** Whether this is the editor a Cloud server serves on its own address (`bun run build:cloud`). */
+declare const __OPENPENCIL_CLOUD_SITE__: boolean
declare const __OPENPENCIL_LOCAL_AUTOMATION_TOKEN__: string | null
declare const __OPENPENCIL_LOCAL_AUTOMATION_URL__: string
declare const __OPENPENCIL_LOCAL_AUTOMATION_HTTP_URL__: string
diff --git a/src/main.ts b/src/main.ts
index 23cf02ba8..5fa62339b 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -5,6 +5,11 @@ import { reportBootFailure, runSupportGate } from '@/app/shell/support/gate'
async function start(): Promise<void> {
if (!(await runSupportGate())) return
try {
+ // A Cloud server's root welcomes visitors who are not signed in before loading the editor.
+ if (__OPENPENCIL_CLOUD_SITE__) {
+ const { enterCloudSite } = await import('@/app/cloud-portal/site')
+ if (!(await enterCloudSite())) return
+ }
const { boot } = await import('./boot')
await boot()
} catch (error) {
diff --git a/src/theme/cloud-portal/layout.ts b/src/theme/cloud-portal/layout.ts
index 32702fd7c..6571d5e4d 100644
--- a/src/theme/cloud-portal/layout.ts
+++ b/src/theme/cloud-portal/layout.ts
@@ -5,6 +5,8 @@ export const portalLayout = tv({
slots: {
page: 'flex h-full min-h-0 flex-col overflow-hidden bg-canvas text-surface',
bar: 'flex h-11 shrink-0 items-center gap-2 border-b border-border bg-panel px-4',
+ barHome:
+ 'flex items-center gap-2 rounded focus-visible:ring-2 focus-visible:ring-accent/50 focus-visible:outline-none',
barTitle: 'text-xs font-semibold whitespace-nowrap',
barHost: 'truncate text-[11px] text-muted max-sm:hidden',
barEnd: 'ml-auto flex items-center gap-2',
diff --git a/src/views/cloud/ConsoleView.vue b/src/views/cloud/ConsoleView.vue
index 97214a510..d15930123 100644
--- a/src/views/cloud/ConsoleView.vue
+++ b/src/views/cloud/ConsoleView.vue
@@ -84,7 +84,7 @@ function select(id: string) {
async function signOut() {
await portal.auth.signOut()
await portal.refreshAccount()
- await router.replace({ name: 'sign-in' })
+ await router.replace({ name: 'welcome' })
}
onMounted(() => void refreshWaiting())
diff --git a/src/views/cloud/StandingView.vue b/src/views/cloud/StandingView.vue
index 2ca998c66..aa65f01a1 100644
--- a/src/views/cloud/StandingView.vue
+++ b/src/views/cloud/StandingView.vue
@@ -5,6 +5,7 @@ import { useRoute, useRouter } from 'vue-router'
import { useCloudPortalMessages } from '@open-pencil/vue/i18n'
import { usePortal } from '@/app/cloud-portal/context'
+import { openLocalEditor } from '@/app/cloud-portal/site'
import PortalNotice from '@/components/cloud-portal/auth/PortalNotice.vue'
import AppButton from '@/components/ui/button/AppButton.vue'
@@ -18,7 +19,7 @@ const email = computed(() => portal.account.value?.user.email ?? '')
async function signOut() {
await portal.auth.signOut()
await portal.refreshAccount()
- await router.replace({ name: 'sign-in' })
+ await router.replace({ name: 'welcome' })
}
</script>
@@ -34,7 +35,16 @@ async function signOut() {
<icon-lucide-ban v-else class="size-6" />
</template>
<template v-if="portal.account.value" #actions>
- <AppButton size="lg" variant="outline" class="w-full" @click="signOut">
+ <AppButton
+ v-if="portal.discovery.localEditor"
+ size="lg"
+ variant="outline"
+ class="w-full"
+ @click="openLocalEditor"
+ >
+ {{ messages.useWithoutAccount }}
+ </AppButton>
+ <AppButton size="lg" variant="ghost" class="w-full" @click="signOut">
{{ messages.signOut }}
</AppButton>
</template>
diff --git a/src/views/cloud/WelcomeView.vue b/src/views/cloud/WelcomeView.vue
new file mode 100644
index 000000000..be8116055
--- /dev/null
+++ b/src/views/cloud/WelcomeView.vue
@@ -0,0 +1,52 @@
+<script setup lang="ts">
+import { useRouter } from 'vue-router'
+
+import { useCloudPortalMessages } from '@open-pencil/vue/i18n'
+
+import { usePortal } from '@/app/cloud-portal/context'
+import { openLocalEditor } from '@/app/cloud-portal/site'
+import PortalPublicLayout from '@/components/cloud-portal/layout/PortalPublicLayout.vue'
+import AppButton from '@/components/ui/button/AppButton.vue'
+import { portalPublic } from '@/theme/cloud-portal/public'
+
+/**
+ * The server's root for visitors who are not signed in: sign in, or use the editor without an
+ * account where the server allows it.
+ */
+const portal = usePortal()
+const router = useRouter()
+const messages = useCloudPortalMessages()
+const ui = portalPublic()
+</script>
+
+<template>
+ <PortalPublicLayout
+ :host="portal.host"
+ :heading="messages.welcomeTitle"
+ :description="messages.welcomeDescription"
+ >
+ <div :class="ui.actions()">
+ <AppButton
+ size="lg"
+ color="primary"
+ variant="solid"
+ class="w-full"
+ @click="router.push({ name: 'sign-in' })"
+ >
+ {{ messages.signIn }}
+ </AppButton>
+ <AppButton
+ v-if="portal.discovery.localEditor"
+ size="lg"
+ variant="outline"
+ class="w-full"
+ @click="openLocalEditor"
+ >
+ {{ messages.useWithoutAccount }}
+ </AppButton>
+ </div>
+ <template v-if="portal.discovery.localEditor" #aside>
+ {{ messages.withoutAccountNote }}
+ </template>
+ </PortalPublicLayout>
+</template>
diff --git a/tests/app/cloud-portal/navigation.test.ts b/tests/app/cloud-portal/navigation.test.ts
index 98d34759a..6786c9c89 100644
--- a/tests/app/cloud-portal/navigation.test.ts
+++ b/tests/app/cloud-portal/navigation.test.ts
@@ -31,7 +31,15 @@ describe('portal access rules', () => {
test('a signed-in person is never sent to another origin', () => {
const signIn = target('/auth/sign-in', { signedOut: true }, 'https://evil.example/')
- expect(portalDestination(signIn, account('active'))).toBe('/account')
+ expect(portalDestination(signIn, account('active'))).toBe('/')
+ })
+
+ test('the welcome page sends a signed-in person to the editor, or to their standing page', () => {
+ const welcome = target('/welcome', { signedOut: true })
+ expect(portalDestination(welcome, null)).toBe(true)
+ expect(portalDestination(welcome, account('active'))).toBe('/')
+ expect(portalDestination(welcome, account('pending'))).toBe('/account/pending')
+ expect(portalDestination(welcome, account('rejected'))).toBe('/account/closed')
})
test('account pages ask for a session and come back after it', () => {
@@ -54,8 +62,8 @@ describe('portal access rules', () => {
expect(portalDestination(pending, account('pending'))).toBe(true)
expect(portalDestination(closed, account('revoked'))).toBe(true)
expect(portalDestination(closed, account('pending'))).toBe('/account/pending')
- expect(portalDestination(closed, account('active'))).toBe('/account')
- expect(portalDestination(pending, account('active'))).toBe('/account')
+ expect(portalDestination(closed, account('active'))).toBe('/')
+ expect(portalDestination(pending, account('active'))).toBe('/')
expect(portalDestination(closed, null)).toEqual({
name: 'sign-in',
query: { redirect: '/account/closed' }
diff --git a/tests/app/cloud-portal/site.test.ts b/tests/app/cloud-portal/site.test.ts
new file mode 100644
index 000000000..9c532870d
--- /dev/null
+++ b/tests/app/cloud-portal/site.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { CloudAccountStatus } from '@open-pencil/cloud/contract'
+
+import { isCloudLink, siteDestination, type SiteAccount } from '@/app/cloud-portal/site'
+
+function account(state: CloudAccountStatus['state']): CloudAccountStatus {
+ return {
+ state,
+ user: { userId: 'user-1', email: '[email protected]', name: 'Ada', deploymentRole: 'user' }
+ }
+}
+
+const visit = (
+ path: string,
+ who: SiteAccount,
+ options: { localEditor?: boolean; choseLocalEditor?: boolean } = {}
+) =>
+ siteDestination({
+ path,
+ account: who,
+ localEditor: options.localEditor ?? true,
+ choseLocalEditor: options.choseLocalEditor ?? false
+ })
+
+describe('Cloud server editor pages', () => {
+ test('open the editor for an account that may use the server', () => {
+ expect(visit('/', account('active'))).toBeNull()
+ expect(visit('/', account('active'), { localEditor: false })).toBeNull()
+ })
+
+ test('welcome visitors at the root who are not signed in or not let in yet', () => {
+ expect(visit('/', null)).toBe('/welcome')
+ expect(visit('/', account('pending'))).toBe('/welcome')
+ expect(visit('/', account('revoked'))).toBe('/welcome')
+ })
+
+ test('open the local editor once this browser chose it, and other pages without asking', () => {
+ expect(visit('/', null, { choseLocalEditor: true })).toBeNull()
+ expect(visit('/demo', null)).toBeNull()
+ })
+
+ test('welcome everyone without an account where the server turns the local editor off', () => {
+ expect(visit('/', null, { localEditor: false, choseLocalEditor: true })).toBe('/welcome')
+ expect(visit('/demo', null, { localEditor: false })).toBe('/welcome')
+ expect(visit('/share/room', account('pending'), { localEditor: false })).toBe('/welcome')
+ })
+
+ test('tell links, which sign in on their own, from look-alike addresses', () => {
+ const link = (address: string) => isCloudLink(new URL(address, 'https://cloud.example'))
+ expect(link('/cloud/documents/a?server=https://cloud.example')).toBe(true)
+ expect(link('/cloud/share/b?server=https://cloud.example#secret')).toBe(true)
+ expect(link('/cloud/invitations/c?server=https://cloud.example#token')).toBe(true)
+ expect(link('/cloud/share/b?server=https://cloud.example')).toBe(false)
+ expect(link('/cloud/documents/a')).toBe(false)
+ expect(link('/cloud/share/b/c?server=x#secret')).toBe(false)
+ })
+
+ test('open the editor when the server cannot say, since the editor works without it', () => {
+ expect(visit('/', 'unreachable', { localEditor: false })).toBeNull()
+ })
+})
diff --git a/tests/helpers/cloud/discovery.ts b/tests/helpers/cloud/discovery.ts
index ea59ad24b..759e8457c 100644
--- a/tests/helpers/cloud/discovery.ts
+++ b/tests/helpers/cloud/discovery.ts
@@ -11,6 +11,7 @@ export function cloudDiscoveryFixture(
apiURL: `${origin}/api`,
authURL: `${origin}/api/auth`,
appURL,
+ localEditor: true,
authentication: {
socialProviders: ['google'],
enterpriseSSO: false,
diff --git a/tests/integration/cloud/service-worker.test.ts b/tests/integration/cloud/service-worker.test.ts
new file mode 100644
index 000000000..1275a6311
--- /dev/null
+++ b/tests/integration/cloud/service-worker.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, test } from 'bun:test'
+
+import { CLOUD_PORTAL_PAGE_ROOTS } from '@open-pencil/cloud/contract'
+import { NOT_EDITOR_PAGES } from '@open-pencil/vite-config/pwa'
+
+const servedByEditor = (path: string) => !NOT_EDITOR_PAGES.some((pattern) => pattern.test(path))
+
+describe('editor service worker on a Cloud server', () => {
+ test('leaves the server’s own pages and API to the server', () => {
+ for (const root of CLOUD_PORTAL_PAGE_ROOTS) {
+ expect(servedByEditor(root)).toBe(false)
+ expect(servedByEditor(`${root}/x`)).toBe(false)
+ }
+ expect(servedByEditor('/api/account/status')).toBe(false)
+ expect(servedByEditor('/.well-known/openpencil')).toBe(false)
+ })
+
+ test('serves the editor’s own pages offline', () => {
+ for (const path of ['/', '/demo', '/share/abc', '/cloud/documents/abc', '/cloud/share/abc']) {
+ expect(servedByEditor(path)).toBe(true)
+ }
+ })
+})
diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txt
index 7590ecb16..a4551ae5b 100644
--- a/tools/checks/i18n/mixed-script-baseline.txt
+++ b/tools/checks/i18n/mixed-script-baseline.txt
@@ -501,6 +501,7 @@ ja:cloud.settingsOfficialDescription
ja:cloud.settingsSelfHostedDescription
ja:cloudPortal.errorEmailInvalid
ja:cloudPortal.verifiedDescription
+ja:cloudPortal.welcomeTitle
zh-cn:cloud.connectHeading
zh-cn:cloud.connectServerDescription
zh-cn:cloud.officialDescription
@@ -517,3 +518,4 @@ zh-cn:cloud.settingsOfficialDescription
zh-cn:cloud.settingsSelfHostedDescription
zh-cn:cloudPortal.errorEmailInvalid
zh-cn:cloudPortal.verifiedDescription
+zh-cn:cloudPortal.welcomeTitle
diff --git a/tools/dev/cloud/src/config.ts b/tools/dev/cloud/src/config.ts
index 5432d33ef..9563cf64a 100644
--- a/tools/dev/cloud/src/config.ts
+++ b/tools/dev/cloud/src/config.ts
@@ -22,29 +22,23 @@ export function localCloudDeployment(endpoints: LocalCloudEndpoints): CloudDeplo
},
database: {},
authentication: {
- enrollment_mode: 'open',
- admin_notification_emails: [],
+ enrollment: { mode: 'open', 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,
+ verification_link_lifetime_minutes: 60,
+ password_reset_link_lifetime_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
+ required_for_admins: false,
+ totp: true,
+ recovery_codes: true,
+ trusted_device_lifetime_days: 14
},
+ passkeys: { enabled: true, rp_name: 'OpenPencil Cloud' },
trusted_proxies: { headers: [], addresses: [] }
},
object_storage: {
@@ -52,8 +46,11 @@ export function localCloudDeployment(endpoints: LocalCloudEndpoints): CloudDeplo
region: 'us-east-1',
bucket: 'openpencil',
force_path_style: true,
- checksum_verification: 'metadata'
+ checksum_verification: 'metadata',
+ maximum_upload_bytes: 1_073_741_824
},
+ collaboration: { maximum_message_bytes: 1_048_576, maximum_connections_per_room: 1000 },
+ documents: { retention_days: 30 },
email: {
transport: 'smtp',
from: 'OpenPencil Cloud <[email protected]>',
@@ -65,8 +62,7 @@ export function localCloudDeployment(endpoints: LocalCloudEndpoints): CloudDeplo
enabled: true,
batch_size: 100,
interval_ms: 60_000,
- lease_ms: 300_000,
- document_retention_days: 30
+ lease_ms: 300_000
}
},
entitlements: {
@@ -74,17 +70,12 @@ export function localCloudDeployment(endpoints: LocalCloudEndpoints): CloudDeplo
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,
+ links: true,
+ guest_view: true,
+ guest_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
}
}
}
diff --git a/tools/dev/cloud/src/index.ts b/tools/dev/cloud/src/index.ts
index 530a69e1a..4c47f2685 100644
--- a/tools/dev/cloud/src/index.ts
+++ b/tools/dev/cloud/src/index.ts
@@ -126,8 +126,8 @@ async function start(project: string): Promise<void> {
])
const betterAuthSecret = await authSecret()
- // The server serves the portal's pages from this build, rebuilt on every change.
- const portal = Bun.spawn(['bun', 'run', 'build:cloud-portal', '--watch'], {
+ // The server serves the editor and its own pages from this build, rebuilt on every change.
+ const site = Bun.spawn(['bun', 'run', 'build:cloud', '--watch'], {
cwd: root,
stdout: 'inherit',
stderr: 'inherit'
@@ -155,7 +155,7 @@ async function start(project: string): Promise<void> {
...process.env,
HOST: '127.0.0.1',
OPENPENCIL_CLOUD_CONFIG: generatedConfig,
- OPENPENCIL_CLOUD_PORTAL_DIR: join(root, 'dist-cloud-portal'),
+ OPENPENCIL_CLOUD_SITE_DIR: join(root, 'dist-cloud'),
DATABASE_URL: `postgresql://openpencil:${POSTGRES_PASSWORD}@127.0.0.1:${postgresPort}/openpencil`,
BETTER_AUTH_SECRET: betterAuthSecret,
S3_ACCESS_KEY_ID,
@@ -165,7 +165,7 @@ async function start(project: string): Promise<void> {
)
} finally {
// The watcher stops with the server however the server ends.
- portal.kill()
+ site.kill()
}
}
diff --git a/tools/dev/cloud/tests/config.test.ts b/tools/dev/cloud/tests/config.test.ts
index 8cd7d3192..ca0326700 100644
--- a/tools/dev/cloud/tests/config.test.ts
+++ b/tools/dev/cloud/tests/config.test.ts
@@ -33,8 +33,7 @@ describe('local Cloud development configuration', () => {
],
emailPasswordEnabled: true,
emailPasswordSignUpEnabled: true,
- passkeyRPID: 'feature.cloud.open-pencil.localhost',
- passkeyOrigin: 'https://feature.cloud.open-pencil.localhost',
+ passkeysEnabled: true,
s3Endpoint: 'http://127.0.0.1:41000',
emailTransport: 'smtp',
smtpHost: '127.0.0.1',
diff --git a/vite.config.ts b/vite.config.ts
index 4d87cae65..ce8336fdd 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -19,8 +19,9 @@ import {
localAutomationToken,
openPencilAutomationPlugin
} from './vite/automation'
-import { cloudPortalBrandPlugin } from './vite/cloud-portal'
+import { cloudSitePlugin } from './vite/cloud-site'
import { aiIconCollection } from './vite/icons'
+import { metricsBrandPlugin } from './vite/metrics'
import { openPencilPwaPlugin } from './vite/pwa'
import { rawMarkdownPlugin } from './vite/raw-markdown'
import { createDevServerOptions } from './vite/server'
@@ -29,22 +30,22 @@ const host = process.env.TAURI_DEV_HOST
const automationRoute = localAutomationRoute(host)
export default defineConfig(async ({ command, mode }) => {
- // `--mode cloud-portal` builds only the Cloud server's own pages (`cloud.html`), without the
- // editor, its demo document, CanvasKit, or the PWA.
- const cloudPortal = mode === 'cloud-portal'
+ // `--mode cloud` builds what a Cloud server serves on its own address: the editor and the
+ // server's own pages (`cloud.html`).
+ const cloudSite = mode === 'cloud'
// `--mode metrics` builds only the metrics dashboard (`metrics.html`) for the feedback Worker,
// which serves it under /admin behind Cloudflare Access.
const metrics = mode === 'metrics'
- const standalone = cloudPortal || metrics
// `VITE_OPENPENCIL_CLOUD=off` builds the editor without OpenPencil Cloud.
const cloud = loadEnv(mode, __dirname, 'VITE_').VITE_OPENPENCIL_CLOUD !== 'off'
- await Promise.all([ensureBrandAssets(['web']), standalone ? undefined : ensureDemoDocument()])
+ await Promise.all([ensureBrandAssets(['web']), metrics ? undefined : ensureDemoDocument()])
return {
resolve: {
alias: createOpenPencilAliases(__dirname, { cloud })
},
define: {
__OPENPENCIL_APP_VERSION__: JSON.stringify(packageJson.version),
+ __OPENPENCIL_CLOUD_SITE__: JSON.stringify(cloudSite),
__OPENPENCIL_LOCAL_AUTOMATION_TOKEN__: JSON.stringify(localAutomationToken(command)),
__OPENPENCIL_LOCAL_AUTOMATION_URL__: JSON.stringify(automationRoute.browserURL),
__OPENPENCIL_LOCAL_AUTOMATION_HTTP_URL__: JSON.stringify(
@@ -58,29 +59,26 @@ export default defineConfig(async ({ command, mode }) => {
tailwindcss(),
Icons({ compiler: 'vue3', customCollections: { ai: aiIconCollection() } }),
Components({ resolvers: [IconsResolver({ prefix: 'icon', customCollections: ['ai'] })] }),
- standalone ? undefined : openPencilAutomationPlugin(command, host),
+ metrics ? undefined : openPencilAutomationPlugin(command, host),
vue(),
- metrics
- ? cloudPortalBrandPlugin((outDir) => resolve(outDir, '..'))
- : cloudPortal
- ? cloudPortalBrandPlugin()
- : openPencilPwaPlugin()
+ metrics ? metricsBrandPlugin((outDir) => resolve(outDir, '..')) : openPencilPwaPlugin(),
+ cloudSite ? cloudSitePlugin() : undefined
],
clearScreen: false,
- publicDir: standalone ? false : 'public',
+ publicDir: metrics ? false : 'public',
base: metrics ? '/admin/' : '/',
build: {
// Syntax is lowered to the supported browser baseline; APIs are not polyfilled.
target: viteBuildTarget(),
chunkSizeWarningLimit: 2500,
- outDir: metrics ? 'dist-metrics/admin' : cloudPortal ? 'dist-cloud-portal' : 'dist',
+ outDir: metrics ? 'dist-metrics/admin' : cloudSite ? 'dist-cloud' : 'dist',
rolldownOptions: {
- // The desktop Software Update window is its own page; the Cloud portal and the metrics
- // dashboard build alone.
+ // The desktop Software Update window is its own page; a Cloud server adds its own
+ // pages beside the editor, and the metrics dashboard builds alone.
input: metrics
? { metrics: resolve(__dirname, 'metrics.html') }
- : cloudPortal
- ? { cloud: resolve(__dirname, 'cloud.html') }
+ : cloudSite
+ ? { main: resolve(__dirname, 'index.html'), cloud: resolve(__dirname, 'cloud.html') }
: {
main: resolve(__dirname, 'index.html'),
updater: resolve(__dirname, 'updater.html')
diff --git a/vite/cloud-site.ts b/vite/cloud-site.ts
new file mode 100644
index 000000000..94046a1a3
--- /dev/null
+++ b/vite/cloud-site.ts
@@ -0,0 +1,23 @@
+import { rmSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+import type { Plugin, ResolvedConfig } from 'vite'
+
+/**
+ * A Cloud server routes its own pages, so the site it serves leaves out the static host's
+ * `_redirects`, which would send every missing file, and every server page, to the editor.
+ */
+export function cloudSitePlugin(): Plugin {
+ let config: ResolvedConfig | undefined
+ return {
+ name: 'open-pencil-cloud-site',
+ apply: 'build',
+ configResolved(resolved) {
+ config = resolved
+ },
+ writeBundle() {
+ if (!config) return
+ rmSync(resolve(config.root, config.build.outDir, '_redirects'), { force: true })
+ }
+ }
+}
diff --git a/vite/cloud-portal.ts b/vite/metrics.ts
similarity index 55%
rename from vite/cloud-portal.ts
rename to vite/metrics.ts
index 4a995ef36..7b2385a21 100644
--- a/vite/cloud-portal.ts
+++ b/vite/metrics.ts
@@ -4,14 +4,14 @@ import { resolve } from 'node:path'
import type { Plugin, ResolvedConfig } from 'vite'
/**
- * The Cloud portal and the metrics dashboard build without the editor's public directory
- * (fonts, CanvasKit, demo files) and copy only the brand artwork, which components load from
- * `/brand/`. `site` is the folder served at the site's root, when the page itself lives below it.
+ * The metrics dashboard builds without the editor's public directory (fonts, CanvasKit, demo
+ * files) and copies only the brand artwork, which components load from `/brand/`. `site` is the
+ * folder served at the site's root, when the page itself lives below it.
*/
-export function cloudPortalBrandPlugin(site?: (outDir: string) => string): Plugin {
+export function metricsBrandPlugin(site?: (outDir: string) => string): Plugin {
let config: ResolvedConfig | undefined
return {
- name: 'open-pencil-cloud-portal-brand',
+ name: 'open-pencil-metrics-brand',
apply: 'build',
configResolved(resolved) {
config = resolved
diff --git a/vite/package.json b/vite/package.json
index 878fb8e5f..8fc70bb7b 100644
--- a/vite/package.json
+++ b/vite/package.json
@@ -3,7 +3,8 @@
"private": true,
"type": "module",
"exports": {
- "./app-source": "./app-source.ts"
+ "./app-source": "./app-source.ts",
+ "./pwa": "./pwa.ts"
},
"dependencies": {
"@open-pencil/core": "workspace:*",
diff --git a/vite/pwa.ts b/vite/pwa.ts
index c798bd3af..1a78668bb 100644
--- a/vite/pwa.ts
+++ b/vite/pwa.ts
@@ -1,5 +1,17 @@
import { VitePWA } from 'vite-plugin-pwa'
+/**
+ * Pages that are not the editor's: OAuth callbacks, which relay a redirect, and, where a Cloud
+ * server serves the editor, its API and its own pages, `CLOUD_PORTAL_PAGE_ROOTS` in
+ * `@open-pencil/cloud/contract`, which loads only once packages are built.
+ */
+export const NOT_EDITOR_PAGES = [
+ /^\/oauth\//,
+ /^\/api\//,
+ /^\/\.well-known\//,
+ /^\/(?:welcome|auth|cloud\/device|account|admin)(?:\/|$)/
+]
+
export function openPencilPwaPlugin() {
return VitePWA({
registerType: 'autoUpdate',
@@ -8,8 +20,7 @@ export function openPencilPwaPlugin() {
maximumFileSizeToCacheInBytes: 12 * 1024 * 1024,
globPatterns: ['**/*.{js,css,html,wasm,png,svg,ico,ttf,webmanifest}'],
navigateFallback: '/index.html',
- // OAuth callbacks are standalone pages that relay a redirect, not app routes.
- navigateFallbackDenylist: [/^\/oauth\//]
+ navigateFallbackDenylist: NOT_EDITOR_PAGES
},
manifest: {
name: 'OpenPencil',