sandcms 0.5.3 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +5 -3
  2. package/dist/admin/Account.svelte +4 -1
  3. package/dist/admin/ApiKeys.svelte +159 -0
  4. package/dist/admin/ApiKeys.svelte.d.ts +3 -0
  5. package/dist/admin/AssetAttachment.svelte +6 -4
  6. package/dist/admin/BlueprintFields.svelte +86 -0
  7. package/dist/admin/BlueprintFields.svelte.d.ts +15 -0
  8. package/dist/admin/Collection.svelte +40 -7
  9. package/dist/admin/Editor.svelte +57 -17
  10. package/dist/admin/Fields.svelte +217 -144
  11. package/dist/admin/Fields.svelte.d.ts +1 -0
  12. package/dist/admin/FocusPicker.svelte +136 -0
  13. package/dist/admin/FocusPicker.svelte.d.ts +11 -0
  14. package/dist/admin/Gallery.svelte +40 -34
  15. package/dist/admin/GlobalSearch.svelte +56 -0
  16. package/dist/admin/GlobalSearch.svelte.d.ts +3 -0
  17. package/dist/admin/Inbox.svelte +8 -5
  18. package/dist/admin/LinkField.svelte +116 -0
  19. package/dist/admin/LinkField.svelte.d.ts +17 -0
  20. package/dist/admin/MediaLibrary.svelte +41 -14
  21. package/dist/admin/MediaPicker.svelte +12 -2
  22. package/dist/admin/NotificationSettings.svelte +2 -2
  23. package/dist/admin/SearchList.svelte +55 -0
  24. package/dist/admin/SearchList.svelte.d.ts +42 -0
  25. package/dist/admin/SelectField.svelte +3 -1
  26. package/dist/admin/SelectField.svelte.d.ts +1 -0
  27. package/dist/admin/Shell.svelte +4 -2
  28. package/dist/admin/UnsavedChanges.svelte +1 -1
  29. package/dist/admin/Users.svelte +11 -5
  30. package/dist/admin/client.js +2 -1
  31. package/dist/admin/generated/admin.css +109 -0
  32. package/dist/admin/types.d.ts +5 -1
  33. package/dist/admin/uploads.js +27 -6
  34. package/dist/blueprints/conditions.d.ts +2 -0
  35. package/dist/blueprints/conditions.js +4 -0
  36. package/dist/blueprints/extends.d.ts +5 -0
  37. package/dist/blueprints/extends.js +76 -0
  38. package/dist/blueprints/files.d.ts +3 -1
  39. package/dist/blueprints/files.js +35 -2
  40. package/dist/blueprints/layout.d.ts +4 -0
  41. package/dist/blueprints/layout.js +12 -0
  42. package/dist/blueprints/load.d.ts +1 -1
  43. package/dist/blueprints/load.js +123 -12
  44. package/dist/blueprints/types.d.ts +35 -1
  45. package/dist/blueprints/validate.js +30 -6
  46. package/dist/cli/cloudflare.js +17 -5
  47. package/dist/cli/doctor.js +6 -3
  48. package/dist/cli/files.js +1 -1
  49. package/dist/cli/scaffold.js +8 -6
  50. package/dist/cli/setup.js +9 -2
  51. package/dist/cli/upgrade.js +2 -1
  52. package/dist/email-failure.d.ts +17 -0
  53. package/dist/email-failure.js +22 -0
  54. package/dist/index.d.ts +2 -1
  55. package/dist/index.js +1 -0
  56. package/dist/link.d.ts +17 -0
  57. package/dist/link.js +44 -0
  58. package/dist/notification-fields.js +1 -1
  59. package/dist/search.d.ts +8 -0
  60. package/dist/search.js +1 -0
  61. package/dist/server/access.d.ts +2 -0
  62. package/dist/server/access.js +59 -23
  63. package/dist/server/admin-load.d.ts +11 -2
  64. package/dist/server/admin-load.js +4 -2
  65. package/dist/server/api-access.d.ts +31 -0
  66. package/dist/server/api-access.js +52 -0
  67. package/dist/server/api-pagination.d.ts +34 -0
  68. package/dist/server/api-pagination.js +87 -0
  69. package/dist/server/api.js +224 -32
  70. package/dist/server/auth.d.ts +1150 -0
  71. package/dist/server/auth.js +11 -1
  72. package/dist/server/cms.d.ts +1210 -4
  73. package/dist/server/cms.js +12 -0
  74. package/dist/server/content.d.ts +17 -2
  75. package/dist/server/content.js +89 -14
  76. package/dist/server/db/auto-migrate.d.ts +12 -0
  77. package/dist/server/db/auto-migrate.js +23 -0
  78. package/dist/server/db/migration-data.js +24 -0
  79. package/dist/server/db/migrations/0001_independent_password_resets.sql +3 -0
  80. package/dist/server/db/migrations/0002_email_failure_reason.sql +1 -0
  81. package/dist/server/db/migrations/0003_direct_r2_uploads.sql +10 -0
  82. package/dist/server/db/migrations/0004_agent_api_keys.sql +38 -0
  83. package/dist/server/db/migrations/0005_api_retention_and_pagination.sql +3 -0
  84. package/dist/server/db/migrations/0006_durable_media_deletion.sql +7 -0
  85. package/dist/server/db/migrations/meta/0001_snapshot.json +1197 -0
  86. package/dist/server/db/migrations/meta/0002_snapshot.json +1204 -0
  87. package/dist/server/db/migrations/meta/0003_snapshot.json +1281 -0
  88. package/dist/server/db/migrations/meta/0004_snapshot.json +1546 -0
  89. package/dist/server/db/migrations/meta/0005_snapshot.json +1572 -0
  90. package/dist/server/db/migrations/meta/0006_snapshot.json +1627 -0
  91. package/dist/server/db/migrations/meta/_journal.json +42 -0
  92. package/dist/server/db/schema.d.ts +742 -2
  93. package/dist/server/db/schema.js +77 -5
  94. package/dist/server/db/store.js +24 -9
  95. package/dist/server/email/index.d.ts +11 -1
  96. package/dist/server/email/index.js +69 -6
  97. package/dist/server/forms.js +12 -2
  98. package/dist/server/hooks.d.ts +1 -1
  99. package/dist/server/hooks.js +37 -14
  100. package/dist/server/index.d.ts +2 -1
  101. package/dist/server/index.js +2 -1
  102. package/dist/server/links.d.ts +5 -0
  103. package/dist/server/links.js +44 -0
  104. package/dist/server/media/deletions.d.ts +2 -0
  105. package/dist/server/media/deletions.js +58 -0
  106. package/dist/server/media/presets.d.ts +10 -2
  107. package/dist/server/media/presets.js +14 -2
  108. package/dist/server/media/runner.d.ts +1 -1
  109. package/dist/server/media/runner.js +105 -8
  110. package/dist/server/media/service.d.ts +41 -3
  111. package/dist/server/media/service.js +146 -33
  112. package/dist/server/notifications.d.ts +1 -0
  113. package/dist/server/notifications.js +4 -2
  114. package/dist/server/request.d.ts +2 -0
  115. package/dist/server/request.js +5 -0
  116. package/dist/server/search.d.ts +13 -0
  117. package/dist/server/search.js +97 -0
  118. package/dist/worker/index.d.ts +4 -4
  119. package/dist/worker/index.js +208 -67
  120. package/dist/worker/local.d.ts +5 -0
  121. package/dist/worker/local.js +57 -0
  122. package/dist/worker/source.d.ts +1 -1
  123. package/dist/worker/source.js +2 -2
  124. package/dist/worker/uploads.d.ts +22 -0
  125. package/dist/worker/uploads.js +48 -0
  126. package/docs/api.md +73 -0
  127. package/docs/cloudflare.md +37 -10
  128. package/docs/content.md +162 -4
  129. package/docs/deployment.md +33 -4
  130. package/docs/email.md +11 -7
  131. package/docs/forms.md +3 -1
  132. package/docs/media.md +33 -4
  133. package/docs/package.md +6 -4
  134. package/docs/releases.md +54 -1
  135. package/docs/upgrades.md +91 -3
  136. package/package.json +19 -10
  137. package/templates/hooks.server.ts +2 -2
  138. package/templates/integration.ts +3 -2
  139. package/templates/routes/admin/+page.server.ts +1 -1
  140. package/templates/routes/api/+server.ts +1 -1
  141. package/templates/sandcms/blueprints/collections/projects.yaml +16 -8
  142. package/templates/sandcms/blueprints/fields/seo.yaml +5 -0
  143. package/templates/sandcms/blueprints/files/image.yaml +1 -0
  144. package/templates/sandcms/blueprints/pages/home.yaml +1 -0
  145. package/templates/sandcms/config.yaml +1 -0
  146. package/templates/sandcms/worker/local.ts +1 -0
  147. package/templates/sandcms/worker/wrangler.jsonc +1 -2
package/docs/api.md ADDED
@@ -0,0 +1,73 @@
1
+ # Agent content API
2
+
3
+ Coding agents map each site's content to its repository-owned YAML blueprints. SandCMS provides authenticated schema discovery, draft reads, validated writes, and retry protection; there is no importer.
4
+
5
+ ## Provision a key
6
+
7
+ Sign in as an administrator, finish the temporary password change (and two-factor sign-in if enabled), and open **Account & security → API keys**. Create a named **Read** or **Write** key and copy it immediately. The secret is shown once; Better Auth stores its hash. Write keys expire after 7 days by default; read keys expire after 30 days. Both allow an explicit lifetime of 1–365 days. Keys belong to the issuing account. Administrators can list and revoke keys for every account, including another administrator; the list shows owner, identifying prefix/start, expiration, and last use. Revocations are audited.
8
+
9
+ Use `x-api-key` on `/api/cms/` requests. No browser cookie or `Origin` header is needed. Read keys discover schemas and read drafts/media; write keys also edit, publish, unpublish, and delete content/media. Keys cannot access admin pages, browser preview delivery, auth endpoints, user management, invitations, or form submissions. Browser sessions retain the same-origin write requirement. Supplying an invalid key never falls back to a cookie. Keys are limited to 120 requests per minute; exceeding the limit returns 429. Revoked, disabled, or expired keys return 401. Missing permissions and an owner who still needs to change their password return 403. Every successful password change, emailed password reset, and operator password/two-factor recovery revokes the account's keys. Password changes and emailed resets audit the number of keys revoked. Deleting a user cascades to their keys. There is no role-change API; current owner permissions are checked on every key request.
10
+
11
+ Key management also has session-only endpoints: `POST /api/cms/keys/create` with `{ "name": "Migration agent", "scope": "write", "expiresIn": 604800 }`, `GET /api/cms/keys/list`, and `POST /api/cms/keys/delete` with `{ "id": "key-id" }`. Write requests require the site's `Origin`. Direct Better Auth key-management HTTP endpoints remain disabled; server integrations use the configured `cms.auth.api` methods.
12
+
13
+ ## Discover and read
14
+
15
+ All responses below require a key or browser session and use private, no-store caching.
16
+
17
+ | GET endpoint | Response |
18
+ | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
19
+ | `/api/cms/schema` | Content blueprints (IDs, kinds, field keys, validation rules, relation targets), file blueprints, default file blueprint, upload limit, image presets |
20
+ | `/api/cms/content/list?blueprint=projects` | A page of documents, including draft, published snapshot, ID, version and timestamps |
21
+ | `/api/cms/content/get?id=DOCUMENT_ID` | One document; 404 if missing |
22
+ | `/api/cms/media/list` | A page of media records, metadata, processing status and variants |
23
+
24
+ `content/list` and `media/list` return `{ "items": [...], "nextCursor": "..." }`. Pass `limit` (default 100, maximum 500) and the returned `cursor` to fetch the next page; `nextCursor: null` marks the last page. This replaces the initial unreleased API's array response. Cursors are opaque and tied to the endpoint and blueprint. Content pages sort by `updatedAt` then ID, descending; media pages sort by `createdAt` then ID, descending. Invalid limits/cursors return 400. A cursor is not a snapshot: edits during traversal may move documents between pages. `content/get` and `content/list` return 404 for form or unknown content blueprints.
25
+
26
+ Schemas come from the deployed YAML definition. Change project-owned blueprints in the repository and redeploy before mapping new fields. A key grants access across all content blueprints and file blueprints; it does not restrict access per collection.
27
+
28
+ ```sh
29
+ export CMS_ORIGIN=https://cms.example.com
30
+ # Set SANDCMS_API_KEY privately in your environment.
31
+ curl --fail-with-body "$CMS_ORIGIN/api/cms/schema" \
32
+ -H "x-api-key: $SANDCMS_API_KEY"
33
+ curl --fail-with-body "$CMS_ORIGIN/api/cms/content/list?blueprint=projects" \
34
+ -H "x-api-key: $SANDCMS_API_KEY"
35
+ ```
36
+
37
+ ## Content writes and retries
38
+
39
+ Send JSON to the existing POST endpoints. Every content write authenticated by a key requires an `Idempotency-Key` with 1–128 characters. Use a stable identifier for each source record and operation, and retain it across network retries. Each changed payload or later operation needs a new key. Browser clients may opt in to the same retry protection.
40
+
41
+ | POST endpoint | JSON body |
42
+ | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
43
+ | `/api/cms/content/save` | `{ "blueprint": "projects", "data": { "title": "Imported", "slug": "imported" } }` to create; include `id` and the current `version` to update |
44
+ | `/api/cms/content/duplicate` | `{ "id": "SOURCE_DOCUMENT_ID", "version": 1 }` to copy the current saved draft of a collection entry |
45
+ | `/api/cms/content/publish` | `{ "id": "DOCUMENT_ID", "version": 1 }` |
46
+ | `/api/cms/content/unpublish` | `{ "id": "DOCUMENT_ID", "version": 1 }` |
47
+ | `/api/cms/content/delete` | `{ "id": "DOCUMENT_ID", "version": 1 }` |
48
+
49
+ Save, duplicate, publish and unpublish return the complete resulting document. Delete returns `{ "ok": true }`. Saves validate fields and references; publishing also validates required fields and media readiness. Empty values must match their field type; for example, rich text accepts a document object or null, while an empty array is invalid. Optimistic version checks protect saves and publication. All unpublish requests, including browser requests, require the current integer version and return 409 when stale. Key-authenticated delete requests also require the current version; browser delete requests can omit it. Save/publish validation and stale-version failures return 400, with `error` and field errors where applicable. A singleton can be created with `content/save`; discover an existing singleton with `content/list` and update its ID/version.
50
+
51
+ Duplication requires write access and the source's current version. It creates an unpublished collection entry from the saved draft, preserving hidden data and media/relation IDs. Text titles receive ` (copy)` and nonempty slugs receive an unused `-copy` suffix, checking both draft and published slugs in that collection. Pages/site settings cannot be duplicated. Missing sources, stale versions and validation failures return 400. The same `Idempotency-Key` replay protection applies, so retrying a successful duplication does not create another copy.
52
+
53
+ ```sh
54
+ curl --fail-with-body "$CMS_ORIGIN/api/cms/content/save" \
55
+ -H "x-api-key: $SANDCMS_API_KEY" \
56
+ -H 'content-type: application/json' \
57
+ -H 'Idempotency-Key: legacy-project-42-create' \
58
+ --data '{"blueprint":"projects","data":{"title":"Imported","slug":"imported"}}'
59
+ ```
60
+
61
+ The mutation and stored response commit together. Repeating the same endpoint and JSON payload with the same retry key returns the original response without repeating the mutation, even after publication or subsequent edits. Reusing that retry key with a different endpoint or payload returns 409. Payload fingerprints ignore JSON object property order. Failed writes do not consume the retry key. Idempotency-Key replays are honored for 48 hours and survive server restarts. Expired receipts are pruned in a successful content-write transaction at most once per minute per database connection; a requested receipt's expiration is always checked. After 48 hours the same retry key is treated as a new request, so inspect current content before retrying an old create. Failed requests are revalidated on retry. Retry keys are scoped to the credential: keep using the same API key when retrying. Content mutations made with API keys are audited with the owner and key ID. Read the current document again before making a later edit; a replayed response describes the original operation.
62
+
63
+ ## Media mapping
64
+
65
+ Use `media/upload` with `{ "name": "image.jpg", "type": "image/jpeg", "size": 12345, "blueprint": "image" }`, PUT the exact bytes to the returned presigned `upload.url`, then call `media/upload/complete` with `{ "id": "MEDIA_ID" }`. Completion is idempotent. Poll `media/list` until the asset is ready before publishing documents that reference its ID. See [the media workflow](media.md).
66
+
67
+ Upload initiation is **not retry-safe** and returns 400 if `Idempotency-Key` is supplied; retain the returned media ID and upload URL instead of starting another upload after receiving a response. A lost initialization response can leave an unused upload session; agents must inspect all pages of `media/list` before retrying. There is no content-hash deduplication. The endpoint accepts JSON metadata, not multipart bytes; a retry receipt around asynchronous remote signing would not guarantee atomic creation. `media/update` takes `{ "id": "MEDIA_ID", "metadata": { "alt": "Description" } }`; `media/retry` and `media/delete` take `{ "id": "MEDIA_ID" }`. Content retry receipts do not apply to these endpoints.
68
+
69
+ `media/delete` returns `{ "ok": true }` once deletion is durably accepted. References and active variants are cleared immediately. If processing is active or storage is unavailable, the asset remains in `media/list` with status `deleting` until background cleanup succeeds. Repeated deletion requests are safe; deleting assets cannot be edited, retried, or selected in content.
70
+
71
+ ## Key security model
72
+
73
+ An API key is a bearer credential: possession grants its configured read/write access without a browser sign-in, two-factor challenge, or Origin check. Write access includes publishing and destructive content/media operations. Use named keys with the shortest practical lifetime, keep them in a private environment or secret store, and revoke them when a migration ends. Two-factor authentication still protects the browser session that provisions keys. Read/write scopes apply across the site's content and file blueprints; there is no IP restriction or per-blueprint allowlist in this release. Finer scopes and content-hash deduplication are follow-ups.
@@ -1,38 +1,65 @@
1
1
  # Cloudflare setup and operations
2
2
 
3
- SandCMS uses one Worker and one **private** R2 bucket per environment. The Worker accepts authenticated uploads and named variant requests, encodes images with remote transformations and inspects dimensions with its Images binding, and streams completed variants to authenticated CMS requests. It serves originals only to the processor using short-lived, signed source URLs. Keep staging and production resources separate.
3
+ SandCMS uses one Worker and one **private** R2 bucket per environment. The Worker signs direct browser uploads and accepts authenticated finalization and named variant requests, encodes images and inspects dimensions with remote transformations, and streams completed variants to authenticated CMS requests. It serves originals only to the processor using short-lived, signed source URLs. Keep staging and production resources separate.
4
4
 
5
5
  Website proxy caching is optional and separate from Worker deployment. Public image URLs remain on the website at `/_sandcms/media/{key}`. Enabling the website's Cloudflare proxy lets the CDN cache authorized image responses. No second bucket, object copying, public R2 access, or publication marker is needed.
6
6
 
7
7
  ## Local development
8
8
 
9
9
  1. Generate a random secret of at least 32 characters.
10
- 2. Put the same value in ignored `.env.local` as `SANDCMS_WORKER_TOKEN` and ignored `sandcms/worker/.dev.vars` as `CMS_TOKEN`.
10
+ 2. Put the same value as `SANDCMS_WORKER_TOKEN` in both ignored `.env.local` and ignored `sandcms/worker/.dev.vars`.
11
11
  3. Use `http://localhost:8787` as `media.workerUrl` (the starter default).
12
12
  4. Run the local Worker, then restart the website:
13
13
 
14
14
  ```sh
15
- bun x wrangler dev --config sandcms/worker/wrangler.jsonc --local --port 8787
15
+ bun x wrangler dev sandcms/worker/local.ts --config sandcms/worker/wrangler.jsonc --local --port 8787
16
16
  ```
17
17
 
18
- The local Worker uses simulated R2, Images metadata inspection, and `cf.image` transformations. Local processing checks format, dimensions, signed-source routing, and storage; production quality and limits require staging verification. The [offline Images implementation supports only a subset of transformations](https://developers.cloudflare.com/images/optimization/binding/). Automated tests need no production resources and do not exercise the Cloudflare CDN.
18
+ The loopback-only `sandcms/worker/local` entry emulates S3 presigned PUTs with the shared CMS token, so local development needs no R2 API credentials. Never deploy this entry; the production `index.ts` remains unchanged. The local Worker uses simulated R2 and `cf.image` transformations for metadata inspection and encoding. Local processing checks format, dimensions, signed-source routing, and storage; production quality and limits require staging verification. The [offline Images implementation supports only a subset of transformations](https://developers.cloudflare.com/images/optimization/binding/). Automated tests need no production resources and do not exercise the Cloudflare CDN.
19
19
 
20
20
  For quality checks, use a deployed staging Worker or remote development with a dedicated staging Worker configuration bound to a staging R2 bucket. Before running `wrangler dev --remote`, verify that the configuration's `MEDIA` binding targets staging, including any `preview_bucket_name` override, and select that configuration explicitly with `--config`. Remote development connects to the configured real remote resources; it does not automatically isolate storage and could otherwise write test uploads and variants to production. See [Cloudflare's development modes](https://developers.cloudflare.com/workers/local-development/).
21
21
 
22
22
  ## Provisioning and deployment
23
23
 
24
- Setup optionally uses the existing Wrangler login, asks for an account, displays project-derived Worker/R2 names, checks collisions, creates the resources, sets the Worker secret, and deploys. It writes non-secret names/URLs to tracked config and secrets to ignored environment files. The CLI does not store Wrangler credentials. Setup does not configure the website's DNS proxy or Cache Rules; complete those steps separately below.
24
+ Setup optionally uses the existing Wrangler login, asks for an account, displays project-derived Worker/R2 names, checks collisions, creates the resources, sets Worker secrets (including bucket-scoped R2 signing credentials entered through masked prompts), and deploys. It writes non-secret names/URLs to tracked config and secrets to ignored environment files. The CLI does not store Wrangler credentials. Setup does not configure the website's DNS proxy or Cache Rules; complete those steps separately below.
25
25
 
26
26
  - Keep R2 public access disabled, including `r2.dev`. Do not attach a public custom domain to the bucket.
27
27
  - Set `media.workerUrl` to the deployed Worker URL, or use the server-only `SANDCMS_WORKER_URL` environment override.
28
- - Supply the same secret as website `SANDCMS_WORKER_TOKEN` and Worker `CMS_TOKEN`.
28
+ - Supply the same secret as `SANDCMS_WORKER_TOKEN` to both the website and the Worker.
29
29
  - Use project-owned resources. The repository's `sandcms-local-media` name is a local example, not a production bucket to reuse.
30
30
 
31
- Keep the Images binding: only encoding moved to remote transformations; dimension inspection still calls `.info()`. Ensure image transformations are enabled for the Worker’s account and that its own hostname is an allowed source. Cloudflare supports `cf.image` on Worker zones, including `workers.dev`. The Worker constructs source URLs from its request origin; use the deployed hostname for `media.workerUrl` and avoid redirects or rewrites on `/internal/source/*`.
31
+ The `IMAGES` binding is no longer required: both dimension inspection (`format=json`) and encoding use remote transformations. Existing project-owned configurations may retain the unused binding. Ensure image transformations are enabled for the Worker’s account and that its own hostname is an allowed source. Cloudflare supports `cf.image` on Worker zones, including `workers.dev`. The Worker constructs source URLs from its request origin; use the deployed hostname for `media.workerUrl` and avoid redirects or rewrites on `/internal/source/*`.
32
32
 
33
33
  Signed source URLs are processor credentials, scoped to one asset and valid at the source for five minutes. Do not log or expose them, and bypass CDN cache rules on `/internal/*`. Source responses use `private, no-store`; Cloudflare maintains its own transformation cache keyed by the signed URL, which is not purged by token expiry. No `origin-auth: share-publicly` setting or public R2 bucket is needed. See [media privacy](media.md#privacy-and-publication). Never forward the CMS bearer token to a source URL.
34
34
 
35
- Set website `BODY_SIZE_LIMIT=101M` and configure upstream request limits to allow 100,000,000-byte files plus multipart overhead. The internal CMS-to-Worker upload is a raw body with an explicit Content-Length. A lower host or proxy limit can still reject uploads before they reach the CMS.
35
+ ### Direct upload configuration
36
+
37
+ The browser uploads to the R2 S3 API endpoint using a 15-minute presigned PUT URL. The bucket remains private. The CMS receives JSON metadata only; `BODY_SIZE_LIMIT=1M` is sufficient for its default JSON request limit. Existing customized host limits are preserved.
38
+
39
+ Set these **Worker** secrets with `bun x wrangler secret put NAME --config sandcms/worker/wrangler.jsonc`:
40
+
41
+ - `SANDCMS_CF_ACCOUNT_ID`: the Cloudflare account containing the bucket.
42
+ - `SANDCMS_R2_BUCKET_NAME`: exactly the bucket bound as `MEDIA`.
43
+ - `SANDCMS_R2_ACCESS_KEY_ID` and `SANDCMS_R2_SECRET_ACCESS_KEY`: an R2 S3 API token with Object Read & Write access restricted to that bucket. These are separate from Wrangler credentials and `SANDCMS_WORKER_TOKEN`; never put them in browser or website configuration.
44
+
45
+ For a jurisdiction-specific endpoint, set optional Worker `SANDCMS_R2_ENDPOINT` to its HTTPS S3 endpoint. The endpoint and bucket must address the same bucket as `MEDIA`.
46
+
47
+ Configure bucket CORS in R2 Settings for every authorized admin origin (merge with existing project-owned rules):
48
+
49
+ ```json
50
+ [
51
+ {
52
+ "AllowedOrigins": ["https://www.example.com"],
53
+ "AllowedMethods": ["PUT"],
54
+ "AllowedHeaders": ["Content-Type"],
55
+ "MaxAgeSeconds": 3600
56
+ }
57
+ ]
58
+ ```
59
+
60
+ Add an R2 object lifecycle rule expiring objects under **only** `incoming/` after one day. This bounds cleanup of abandoned transfers and objects recreated by replaying an unexpired PUT URL. Do not apply this rule to originals or variants. Finalization retries must complete before lifecycle expiration; otherwise the editor must upload again.
61
+
62
+ The signature binds the object key, method, content type and expiry. It is not a byte-range upload policy: declared size is checked by the CMS before signing and actual size is checked by the Worker before acceptance. A client can write an oversized staging object, but it cannot be accepted as an original. Treat upload URLs as temporary write credentials and keep them out of logs. See [R2 presigned URLs](https://developers.cloudflare.com/r2/api/s3/presigned-urls/) and [bucket CORS](https://developers.cloudflare.com/r2/buckets/cors/).
36
63
 
37
64
  Later deploys are explicit:
38
65
 
@@ -41,7 +68,7 @@ bun x --no-install sandcms worker update
41
68
  bun x --no-install sandcms doctor
42
69
  ```
43
70
 
44
- Worker updates verify recorded resource ownership. The current CMS/Worker protocol is **3**; incompatible internal requests fail. Deploy the updated Worker and website together for 100 MB remote processing. This processing change does not alter the database schema or require a database reset. For database schema changes, follow the [upgrade workflow](upgrades.md).
71
+ Worker updates verify recorded resource ownership. The current CMS/Worker protocol is **5**. The Worker also accepts protocols 3 and 4 for existing website processes and legacy BLOB transfers, allowing the Worker to be deployed first. Direct uploads require protocol 4 or 5. Focal-point crops require the protocol-5 Worker. Configure signing credentials, CORS and lifecycle cleanup, deploy the Worker, then migrate the database and deploy the website. The retained incremental migration adds `upload_sessions` without changing old media or pending BLOBs; follow the [upgrade workflow](upgrades.md).
45
72
 
46
73
  For deployments still using legacy public Worker `/media/*` URLs, deploy a protocol-3 Worker to close that route, update manually constructed URLs to the CMS routes, and purge old Worker URL caches. Legacy browser copies may have a one-year immutable lifetime and cannot be recalled. Confirm bucket public access is disabled before relying on draft privacy.
47
74
 
@@ -62,7 +89,7 @@ Draft-only images return an uncached 404. Authenticated previews at `/api/cms/me
62
89
 
63
90
  1. Deploy the updated website and Worker. The former `no-store` public policy cannot be fixed by simply enabling the proxy.
64
91
  2. In the website's Cloudflare zone, change the website hostname's DNS record to **Proxied** (orange cloud).
65
- 3. Use **Full (strict)** SSL/TLS with a valid origin certificate. Keep website `SANDCMS_ORIGIN` and adapter `ORIGIN` set to the public HTTPS origin; see [host configuration](deployment.md#host-configuration).
92
+ 3. Use **Full (strict)** SSL/TLS with a valid origin certificate. Keep website `SANDCMS_ORIGIN` and SvelteKit `paths.origin` configured to the public HTTPS origin; see [host configuration](deployment.md#host-configuration).
66
93
  4. In **Rules → Cache Rules**, add the two rules below, replacing `www.example.com` with the actual website hostname. Repeat for any other hostname that serves the website.
67
94
 
68
95
  Do not change trusted-client-IP settings just to enable caching. Trust a proxy header only after configuring the origin so clients cannot spoof it; see [deployment guidance](deployment.md#host-configuration).
package/docs/content.md CHANGED
@@ -18,14 +18,117 @@ fields:
18
18
  overrides: [alt]
19
19
  ```
20
20
 
21
- Content kinds: `page`, `site`, `collection`, `form`. File metadata uses `kind: file` (see below). Field types: `text`, `slug`, `textarea`, `number`, `date`, `boolean`, `select`, `multiselect`, `richtext`, `media`, `media-list`, `gallery`, `relation`, `group`, `repeatable`. Select fields require `options`; relation fields require `collection`; `group` and `repeatable` fields require `fields`. Fields accept `label`, `description`, `required`, and numeric `min`/`max`. Payloads are limited to 1 MB and 30 nesting levels. Galleries have no fixed item count.
21
+ Content kinds: `page`, `site`, `collection`, `form`. File metadata uses `kind: file` (see below). Field types: `text`, `slug`, `textarea`, `number`, `date`, `boolean`, `select`, `multiselect`, `richtext`, `link`, `media`, `media-list`, `gallery`, `relation`, `group`, `repeatable`. Select fields require `options`; relation fields require `collection`; `group` and `repeatable` fields require `fields`. Fields accept `label`, `description`, `required`, and numeric `min`/`max`. Payloads are limited to 1 MB and 30 nesting levels. Galleries have no fixed item count.
22
+
23
+ Draft saves allow incomplete required fields, while provided values must match their field type even when empty. Use null or omit an optional field to leave it unset; use an empty array for list fields and a document object for rich text. Publish validates the full document, existing relations, and current media preset readiness. Slugs are unique within a blueprint, separately for draft and published snapshots. Save uses a version number to reject stale writes. Publishing atomically replaces the published snapshot. Unpublish removes public visibility and checks the editor's current version before returning a new version, preserving unsaved local edits. If another session changed the document, reload before unpublishing or saving.
24
+
25
+ ## Field helpers
26
+
27
+ `help` displays plain text below any field; `description` stays above the control. `placeholder` supplies an empty-state hint for `text`, `slug`, `textarea`, `number`, `select`, and `relation`. Labels remain visible.
28
+
29
+ ```yaml
30
+ fields:
31
+ summary:
32
+ type: textarea
33
+ placeholder: A short introduction
34
+ help: Summarize the project for visitors.
35
+ counter: true
36
+ minLength: 20
37
+ maxLength: 200
38
+ price: { type: number, before: '€', min: 0 }
39
+ width: { type: number, after: px, min: 0 }
40
+ ```
41
+
42
+ `before` and `after` display plain-text prefixes/suffixes on `text`, `slug`, and `number` inputs. They are not included in stored values. `counter: true` shows the current character count on `text`, `slug`, and `textarea`, with any minimum/maximum and a warning color outside the range. Counters also work without limits; limits work without a counter.
43
+
44
+ `minLength` and `maxLength` must be nonnegative integers, with the maximum at least the minimum. Counts use JavaScript/HTML string length (UTF-16 code units). Text controls use native length attributes, and the server checks nonempty values on draft saves, publish, form submissions, and file metadata updates, including nested fields. Empty optional values remain allowed; `required` is enforced when publishing or submitting a form. `min` and `max` remain numeric bounds. Restart the application after editing YAML. No database migration is needed; existing project-owned blueprints are preserved.
22
45
 
23
46
  Draft saves allow incomplete required fields. Publish validates the full document, existing relations, and current media preset readiness. Slugs are unique within a blueprint, separately for draft and published snapshots. Save uses a version number to reject stale writes. Publishing atomically replaces the published snapshot. Unpublish removes public visibility.
24
47
 
48
+ ## Link fields
49
+
50
+ ```yaml
51
+ cta: { type: link, label: Call to action }
52
+ projectLink: { type: link, collection: projects }
53
+ imageLink: { type: link, fileBlueprint: image }
54
+ ```
55
+
56
+ A link stores `{ type, value, label?, newTab? }`, or `null` when cleared. `type` is `url`, `entry`, `file`, `email`, or `phone`; `value` contains the destination or an entry/file ID. Optional `collection` limits entry choices, and optional `fileBlueprint` limits file choices. Without these constraints, entries from any content blueprint and files from any file blueprint are available. Links work inside groups and repeatables too.
57
+
58
+ URL destinations accept HTTP(S), local `/paths`, and `#fragments`. Email and phone destinations contain the address/number without `mailto:` or `tel:`; phone numbers may include spaces, parentheses, periods, and hyphens. Executable schemes, protocol-relative URLs, control characters, and malformed destinations are rejected. An empty destination can be saved as a draft; required links must have a destination when published. Existing entry/file targets are validated on save. File links also check readiness and required file metadata at publication. Deleting a target clears known links in both snapshots and file metadata.
59
+
60
+ Use `cms.resolveLink(entry.data.cta)` to get `{ href, label, target?, rel? }` or `null`. For internal entries, it uses `seo.routes[blueprint]` when configured, otherwise the blueprint's `preview` route, filling placeholders from the published payload (`{id}` uses the entry ID). It follows published slug/title changes without republishing the referring entry. Missing/unpublished entries, missing routes, and unfilled route parameters return `null`. Custom routing can consume the structured value directly.
61
+
62
+ ```svelte
63
+ {#if cta}
64
+ <a href={cta.href} target={cta.target} rel={cta.rel}>{cta.label}</a>
65
+ {/if}
66
+ ```
67
+
68
+ Pass the resolved value as `cta` from your server load. Link text overrides the default destination, published entry title, or file alt text. New-tab links include `rel="noopener noreferrer"`. File destinations resolve to the largest available public image rendition, using the existing media delivery access checks. Draft-only files resolve to `null`. The current library supports images, not arbitrary downloadable files or public originals. A link in file metadata does not itself grant public access to another file; that file must be referenced by published content.
69
+
25
70
  When an editor has unsaved changes, SvelteKit's `beforeNavigate` check opens a shadcn alert dialog before navigating within the app, including browser back/forward. **Keep editing** cancels navigation; **Discard changes** continues to the requested destination. Refreshing, closing the tab or browser, and leaving the app with a full page load are intentionally unguarded. The editor does not register a browser-native unload prompt.
26
71
 
27
72
  When using the save API directly, supply complete repeatable rows, including hidden keys from the previous draft. The admin does this automatically when editing or reordering. Rows are replaced as ordered objects; merging by array index would attach retired data to the wrong row after a reorder.
28
73
 
74
+ ## Duplicate entries
75
+
76
+ Use **Duplicate** on a collection row or **Duplicate entry** in a saved entry's editor to open a new unpublished draft. Save pending edits first; duplication copies the latest saved draft, including nested content, hidden fields, galleries, and relation/media IDs. Media files are reused rather than uploaded again. Pages and site settings are singletons and cannot be duplicated.
77
+
78
+ When a blueprint has a text `title`, a nonempty title receives ` (copy)`. A nonempty top-level `slug` receives `-copy`, then `-copy-2`, `-copy-3`, and so on until it is unused by both draft and published snapshots in that collection. Entries without a slug keep it empty. The original entry and its live snapshot are preserved; editing or publishing the copy is independent. If another session changes the source, reload before duplicating.
79
+
80
+ Authenticated server callers can use `cms.content.duplicate(id, version)`. The normal draft validation and reference indexing apply. No new database migration or blueprint configuration is required.
81
+
82
+ ## Conditional fields
83
+
84
+ Add `when:` to show a field only when sibling values match:
85
+
86
+ ```yaml
87
+ fields:
88
+ linkType: { type: select, options: [internal, external] }
89
+ url:
90
+ type: text
91
+ required: true
92
+ when: { linkType: external }
93
+ ```
94
+
95
+ All entries must match (AND). Expected values may be strings, numbers, booleans, or null; comparison is exact, without coercion. Missing values do not match, including a null condition. Conditions must name another field in the same `fields` map. In groups and repeatables they read that group's values or the current row, not the parent document. Multiple rows are independent. Conditions read stored values even if the controlling field is hidden.
96
+
97
+ Hidden fields and descendants of hidden groups, repeatables, or galleries skip required-field validation, matching Kirby's behavior. Supplied values still receive type, option, range, relation, and media validation. Hiding a field preserves its value through saves and publication; it does not remove content from public payloads. Conditions control the admin editor; custom public forms must implement their own display and field validation behavior.
98
+
99
+ File metadata supports the same conditions. Gallery override controls evaluate effective metadata (file defaults plus explicit row overrides), so a condition can refer to a file field that is not itself overridable. An empty `when:` map, unknown sibling, self-reference, or nonscalar expected value fails blueprint validation. Restart the application after editing YAML.
100
+
101
+ ## Reusable field definitions
102
+
103
+ Put shared field definitions under `sandcms/blueprints/fields`, then reference them with `extends:` wherever a field is declared:
104
+
105
+ ```yaml
106
+ # sandcms/blueprints/fields/seo.yaml
107
+ type: group
108
+ label: Search appearance
109
+ fields:
110
+ title: { type: text }
111
+ description: { type: textarea }
112
+ ```
113
+
114
+ ```yaml
115
+ # Inside a page or collection blueprint
116
+ fields:
117
+ seo:
118
+ extends: fields/seo
119
+ label: Project search appearance
120
+ fields:
121
+ title: { required: true }
122
+ ```
123
+
124
+ The resolved `seo` group retains both fields, with a local label and a required title. Shared definitions can describe any supported field type, including CTA or address groups. They work in pages, collections, site settings, forms, file metadata, and nested group/repeatable fields. A shared definition can itself extend another shared definition.
125
+
126
+ References start with `fields/`, are relative to the blueprints directory, and omit the `.yaml` or `.yml` extension. Subdirectories are supported, for example `fields/address/postal`. Each reference must identify exactly one file; missing references, duplicate extensions, directory escapes and inheritance cycles are rejected. Shared files contain one complete field definition, without a blueprint `id` or `kind`, and are validated even when unused. The `blueprints/fields` directory is reserved for these definitions; they never appear in the sidebar or schema API as independent blueprints.
127
+
128
+ Local settings override inherited settings. Nested mappings merge by key, retaining inherited field order and appending new keys. Arrays such as `options` replace the inherited array. `false` overrides `true`; null does not remove inherited fields and is rejected where the field schema disallows it. The resolved definition must pass the usual field and relation validation. Blueprint-level inheritance and string shorthand references are not supported.
129
+
130
+ The starter and demo project blueprint use `fields/seo`. Existing inline YAML continues to work. Reusing a definition keeps the field key and stored payload shape unchanged; restart the application after YAML edits. Upgrades preserve project-owned YAML, so adopting shared definitions in an existing site is an explicit configuration edit.
131
+
29
132
  ## Sidebar groups
30
133
 
31
134
  Pages appear under a collapsible **Pages** group by default. Other blueprint kinds stay at the top level. Set `navigation.group` on a content blueprint to choose a group:
@@ -56,7 +159,7 @@ Routes and components remain developer-owned. Use the installed site's `getCMS`
56
159
 
57
160
  ```ts
58
161
  import { error } from '@sveltejs/kit';
59
- import { getCMS } from '$lib/server/sandcms';
162
+ import { getCMS } from '#lib/server/sandcms/index.js';
60
163
 
61
164
  export const load = async (event) => {
62
165
  const cms = getCMS();
@@ -108,7 +211,7 @@ Title precedence is `seo.title`, then `title`, then `site.title`. A nonempty sit
108
211
  Load published site settings in your public `+layout.server.ts`, for example:
109
212
 
110
213
  ```ts
111
- import { getCMS } from '$lib/server/sandcms';
214
+ import { getCMS } from '#lib/server/sandcms/index.js';
112
215
 
113
216
  export const load = () => ({
114
217
  site: getCMS().content.published('site')[0]?.data ?? { title: 'My website' }
@@ -139,7 +242,7 @@ In `sandcms/config.yaml`, set `media.defaultFileBlueprint: image`. Uploads store
139
242
 
140
243
  Without a configured default, SandCMS supplies `default`, with alt text only. A file blueprint with `id: default` replaces this fallback. Legacy `media.photographerCollection` adds a photographer relation to the fallback only; new sites should declare that field in a file blueprint instead. The starter uses an alt-only `image` blueprint. The demo site explicitly adds caption and photographer to its image blueprint to demonstrate those optional fields.
141
244
 
142
- Use the existing field types for metadata, including text, selects, booleans, relations, groups and repeatables. File metadata cannot contain media or gallery fields. The top-level key `image` is reserved for gallery references. `accept` contains exact supported image MIME types; it defaults to all supported image types when omitted. Non-image file uploads are not implemented yet, even though the blueprint and metadata model is designed to accommodate them.
245
+ Use the existing field types for metadata, including text, selects, booleans, relations, groups and repeatables. A single top-level `focus` field stores normalized `{x, y}` coordinates for focal-point crops; it is shared across placements and cannot be a gallery override. See [focal points](media.md#focal-points). File metadata cannot contain media or gallery fields. The top-level key `image` is reserved for gallery references. `accept` contains exact supported image MIME types; it defaults to all supported image types when omitted. Non-image file uploads are not implemented yet, even though the blueprint and metadata model is designed to accommodate them.
143
246
 
144
247
  Metadata is stored separately from technical file information. Saving file details validates configured fields, required values and relation targets. Uploads may initially have incomplete metadata; publishing content checks required metadata on each selected file. Removed metadata keys remain stored, but are omitted from the public metadata result. Relations are IDs; use `cms.content.resolveRelation` for custom relations. Deleting an entry clears known relations in file metadata too.
145
248
 
@@ -204,3 +307,58 @@ Absolute URLs use the configured `origin` (`SANDCMS_ORIGIN` in the standard inte
204
307
  Both endpoints support GET and HEAD and send `Cache-Control: no-store` so publishing changes are visible immediately. XML is escaped and URLs are deduplicated. No estimated modification dates, priorities, or change frequencies are emitted. This helper supports one sitemap up to 50,000 URLs and 50 MB; larger sites should omit `seo` and implement a sitemap index. These limits and XML requirements follow the [Sitemap protocol](https://www.sitemaps.org/protocol.html).
205
308
 
206
309
  For custom application-owned endpoints, `cms.seo.robots()` and `cms.seo.sitemap()` return the generated strings when SEO is enabled. To override the standard responses, handle those paths before calling `cmsHandle` in your hook.
310
+
311
+ ## Admin search
312
+
313
+ Use **Search** in the admin header or **Cmd/Ctrl+K** to find pages, saved collection entries, and media. Arrow keys move between results; Enter opens a result and Escape closes search. Opening an editor still checks for unsaved changes. Page blueprints can be found before their first draft exists; searching does not create drafts.
314
+
315
+ Collection lists, the media library, and media selectors have their own search input. Clearing it restores the full list. Media selection stays intact when a search hides selected images, and selector results retain the field's file blueprint and accepted MIME types. Global media results open the asset's details.
316
+
317
+ Search is case and accent insensitive and matches all space-separated terms, including partial words. Global results favor exact titles/filenames, then partial title/filename matches, then content matches; up to 30 results are grouped into pages, content, and media. Local lists retain newest-first order and support loading additional matches.
318
+
319
+ Search uses saved drafts and declared readable fields: text, slug, textarea, select/multiselect labels, rich-text text, nested groups/repeatables, and gallery text overrides. Media search includes filenames, text metadata, and related credit names (title/name). Internal reference IDs, removed fields, rich-text markup, form submissions, and unsaved editor changes are excluded.
320
+
321
+ Search scans eligible records on the server. No schema migration, external search service, or project configuration changes are needed. Its cost grows with stored content; large installations may need a persisted index in a future migration.
322
+
323
+ ## Editor layouts
324
+
325
+ Content blueprints (`page`, `site`, `collection`, and `form`) can organize the admin editor with optional `tabs`. Define fields once in the existing flat `fields` map; layouts reference their top-level keys. Group and repeatable data remain nested exactly as before. Layouts do not affect public forms, exports, submission tables, or content validation rules.
326
+
327
+ ```yaml
328
+ id: article
329
+ label: Article
330
+ kind: collection
331
+ fields:
332
+ title: { type: text, required: true, width: 1/2 }
333
+ slug: { type: slug, from: title, required: true, width: 1/2 }
334
+ body: { type: richtext }
335
+ featured: { type: boolean }
336
+ seo:
337
+ type: group
338
+ fields:
339
+ title: { type: text }
340
+ description: { type: textarea }
341
+ tabs:
342
+ content:
343
+ label: Content
344
+ columns:
345
+ - width: 2/3
346
+ sections:
347
+ story:
348
+ label: Story
349
+ fields: [title, slug, body]
350
+ - width: 1/3
351
+ sections:
352
+ options:
353
+ label: Options
354
+ fields: [featured]
355
+ settings:
356
+ label: Settings
357
+ fields: [seo]
358
+ ```
359
+
360
+ Tabs and sections are ordered maps with stable machine keys. Columns are an ordered list. A tab accepts either a `fields` list for a simple panel or `columns` containing named `sections`, each with a `fields` list. Labels are optional: tab keys become labels, while section headings appear only with an explicit label. Every top-level field must appear exactly once across the layout. Empty layouts, unknown or duplicate references, omitted fields, invalid widths, and unknown settings fail blueprint validation with YAML file and line diagnostics. Reference the whole group (`seo`), rather than nested keys such as `seo.title`.
361
+
362
+ Fields and columns accept `width: 1/1`, `1/2`, `1/3`, `2/3`, `1/4`, or `3/4`; omitted widths are full width. Field widths are relative to their containing section or group. They also work without tabs, in repeatable rows, and in file metadata editors. Items wrap in order; narrow editors and mobile screens stack them at full width. File blueprints support field widths but do not support tabs.
363
+
364
+ Tab changes preserve unsaved values. Tabs support keyboard navigation and indicate validation errors, including errors inside nested groups and repeatable rows. A failed save or publish opens the first tab with field errors; all fields remain validated regardless of the active tab. Top-level `columns: [name, email]` on form blueprints continues to configure the submissions table and is independent of editor columns.
@@ -2,7 +2,7 @@
2
2
 
3
3
  Run one long-lived Bun website container with a persistent writable volume. The public website, admin, auth, SQLite, and job runner stay in that process. The project media Worker/R2 bucket are deployed separately; follow [Cloudflare setup and proxy caching](cloudflare.md) for those resources and the website CDN.
4
4
 
5
- The repository pins Bun 1.4.0, SvelteKit 2.70.3, Svelte 5.57.1, and community `svelte-adapter-bun` 1.0.1. The production adapter output is tested under Bun. Build tooling also uses pinned Node 26.8.1. [Railpack detects Bun from packageManager or its lockfile](https://railpack.com/languages/bun/); `railpack.json` makes the build/start commands explicit.
5
+ The repository pins Bun 1.4.0, SvelteKit 3.0.0, Svelte 5.57.1, and official `@sveltejs/adapter-bun` 1.0.0. The production adapter output is tested under Bun. Build tooling also uses pinned Node 26.8.1. [Railpack detects Bun from packageManager or its lockfile](https://railpack.com/languages/bun/); `railpack.json` makes the build/start commands explicit.
6
6
 
7
7
  ## Server build configuration
8
8
 
@@ -15,7 +15,7 @@ ssr: {
15
15
  }
16
16
  ```
17
17
 
18
- Vite must bundle `@better-auth/core` using its server export conditions before `svelte-adapter-bun` 1.0.1 performs its second bundle pass. Otherwise the adapter can select Better Auth's browser async-storage fallback, which loses request state during concurrent requests and produces HTTP 500 responses for image previews. Do not also list `@better-auth/core` in `ssr.external`: explicit external entries take precedence over `noExternal`. See [Vite SSR options](https://vite.dev/config/ssr-options).
18
+ Vite bundles `@better-auth/core` using its server export conditions to retain native async request storage. Keep it out of `ssr.external`, which takes precedence over `noExternal`. The official Bun adapter uses Vite's server output without a second bundle pass unless executable compilation is enabled. See [Vite SSR options](https://vite.dev/config/ssr-options) and the [Bun adapter](https://svelte.dev/docs/kit/adapter-bun).
19
19
 
20
20
  Rebuild and restart the website after this configuration change. It requires no database reset or Worker update. Setup and upgrade preserve existing Vite files and report the required change.
21
21
 
@@ -23,8 +23,8 @@ Rebuild and restart the website after this configuration change. It requires no
23
23
 
24
24
  - Build: `bun run build`; start: `bun build/index.js`.
25
25
  - Mount a local persistent volume at `/data`, and set `SANDCMS_DATABASE=/data/sandcms.sqlite`.
26
- - Set `BODY_SIZE_LIMIT=101M` for the Bun adapter and allow 100 MB files plus multipart overhead through upstream proxies.
27
- - Set `SANDCMS_ORIGIN=https://your-site.example` and adapter `ORIGIN` to the same public origin.
26
+ - Set `BODY_SIZE_LIMIT=1M` for the Bun adapter’s normal JSON requests. Media bytes upload directly to private R2 using presigned URLs; configure [Worker signing credentials and bucket CORS](cloudflare.md#direct-upload-configuration).
27
+ - Set `SANDCMS_ORIGIN=https://your-site.example` and configure `paths.origin` in the SvelteKit Vite plugin to the same public origin at build time. The official adapter does not read `ORIGIN`.
28
28
  - Supply a stable random `SANDCMS_SECRET` with at least 32 characters and the project's `SANDCMS_WORKER_TOKEN`.
29
29
  - Set `SANDCMS_WORKER_URL` only if overriding the tracked media URL for this environment.
30
30
  - Set `PORT` to the host's assigned port. Route both the public website and `/admin` to this container.
@@ -44,6 +44,10 @@ bun x --no-install sandcms user bootstrap --database /data/sandcms.sqlite --emai
44
44
 
45
45
  In this source repository's demo image, use `bun dist/cli/index.js` in place of `bun x --no-install sandcms`. From 0.5.0, apply retained incremental migrations to upgrade supported databases. Changed pre-0.5.0 baselines still require a fresh database. If retaining the old state, take a verified backup with the matching old package before updating. See [upgrade workflow](upgrades.md). The app refuses to start with pending or incompatible migrations. Each numbered migration runs transactionally. Bootstrap only works when the selected database has no users, generates a password, and prints it once. A local account does not create a production account.
46
46
 
47
+ ### Automatic migration on start
48
+
49
+ Set `SANDCMS_AUTO_MIGRATE=true` to apply pending migrations when the website starts instead of running `sandcms migrate` separately. The generated integration passes it to `createCMS({ autoMigrate })`; customized integrations must add `autoMigrate: env.SANDCMS_AUTO_MIGRATE === 'true'` themselves. Before migrating an existing database, the website writes a verified snapshot to `<database>.before-migrate-<timestamp>-<id>.sqlite` beside it and logs its path; empty databases are initialized without a snapshot, and a non-empty database with no migration history is refused. Incompatible or modified histories are still rejected without changes, a failed migration rolls back and stops startup, and concurrent starts apply each migration once. Snapshots are not pruned automatically; remove them after verifying the upgrade. Auto-migration does not create accounts; still run `user bootstrap` on a fresh volume. Leave it unset to keep the explicit operator workflow.
50
+
47
51
  For a one-off Docker command, override Railpack's shell entrypoint with `--entrypoint bun`, then pass `dist/cli/index.js migrate` after the image name. Mount the same `/data` volume and supply runtime variables. See the [local container drill](acceptance.md) for the tested setup.
48
52
 
49
53
  A new user added later must have an operator/admin-supplied password. The CLI prompts without echo; automation may use `--password-stdin`. Both paths require a change at first login. Password and 2FA recovery invalidate sessions and write audit metadata:
@@ -56,6 +60,31 @@ bun x --no-install sandcms user reset-2fa --email editor@example.com
56
60
 
57
61
  HTTPS origins use secure cookies. CMS writes validate origin, authentication is enforced server-side, and logins have per-email and per-client limits. By default the application does not read proxy IP headers. Only set `SANDCMS_TRUSTED_PROXY_HEADER` after the reverse proxy strips/replaces the chosen header and the application cannot be reached around that proxy. Configure the adapter's client-address handling consistently. A wrongly trusted forwarded header defeats client rate limiting.
58
62
 
63
+ ## Client IP behind Dokploy and Cloudflare
64
+
65
+ For a Cloudflare-proxied website routed through Dokploy's reverse proxy, configure the trust boundary first:
66
+
67
+ 1. Restrict the website's origin ingress to [Cloudflare traffic](https://developers.cloudflare.com/fundamentals/security/protect-your-origin-server/). Keep the Bun container port private so requests cannot bypass Dokploy's proxy.
68
+ 2. Preserve Cloudflare's `CF-Connecting-IP` through Dokploy's proxy. Strip or replace untrusted copies on any other ingress; do not accept arbitrary client-supplied values. Cloudflare supplies the visitor address in [this single-address header](https://developers.cloudflare.com/fundamentals/reference/http-headers/).
69
+ 3. Set both runtime variables in Dokploy and restart the website. `sandcms setup` adds commented examples to `.env.local`; copying those values into Dokploy is a manual deployment step. The comments alone do not enable proxy trust:
70
+
71
+ ```dotenv
72
+ SANDCMS_TRUSTED_PROXY_HEADER=cf-connecting-ip
73
+ ADDRESS_HEADER=cf-connecting-ip
74
+ ```
75
+
76
+ `SANDCMS_TRUSTED_PROXY_HEADER` controls CMS login and access-link rate limits. The [Bun adapter's `ADDRESS_HEADER`](https://svelte.dev/docs/kit/adapter-bun) controls `event.getClientAddress()`, including website form actions. `XFF_DEPTH` is unnecessary for this single-address header. The CMS falls back to `event.getClientAddress()` if its configured header is absent or empty; the Bun adapter throws if its configured `ADDRESS_HEADER` is absent. Ensure requests that resolve a client address pass through the configured proxy chain.
77
+
78
+ Run `sandcms doctor` with the deployment environment. It warns when `SANDCMS_ORIGIN` uses HTTPS and no CMS proxy header is set; this warning does not verify ingress rules or the actual headers.
79
+
80
+ On staging, temporarily log only the resolved address immediately before a form submission:
81
+
82
+ ```ts
83
+ console.info('staging form client address', event.getClientAddress());
84
+ ```
85
+
86
+ Submit from two different networks and check the server logs: each should show that visitor's public IP rather than the same proxy IP. Confirm one visitor reaching the form limit does not block the other, and check that a supplied spoofed `CF-Connecting-IP` cannot override the address through the public ingress. Remove the temporary logging after verification. This staging check remains operator-owned until deployment access is available.
87
+
59
88
  ## Consistent backups
60
89
 
61
90
  ```sh
package/docs/email.md CHANGED
@@ -20,13 +20,15 @@ The sender must be allowed by your SMTP provider. Reply-to is optional. Credenti
20
20
 
21
21
  Port 587 requires STARTTLS. Port 465 requires immediate TLS (`SANDCMS_SMTP_SECURE=true`, or omit the flag when specifying port 465). With no port, the default is 465 when secure is true and 587 otherwise. Certificate validation is always enabled. Boolean values must be exactly `true` or `false`.
22
22
 
23
+ For Hetzner Cloud, use the port 587 STARTTLS configuration above. Hetzner blocks outbound ports 25 and 465 by default; port 587 is available for external mail delivery services without an unblock request. See the [Hetzner FAQ](https://docs.hetzner.com/cloud/servers/faq/#why-can-i-not-send-any-mails-from-my-server). A timeout can also indicate an incorrect host, firewall, or provider outage; it does not identify a specific hosting restriction. Port 465 remains supported where outbound access is available.
24
+
23
25
  Email is disabled when all email variables are absent or empty. `cms.email.enabled` reports configuration availability, not server connectivity. Partial or invalid configuration fails when the CMS is created; an unreachable provider fails only when sending. Startup does not contact the SMTP server.
24
26
 
25
27
  The generated integration and repository demo read these variables. For an existing customized integration, add the option yourself:
26
28
 
27
29
  ```ts
28
- import { env } from '$env/dynamic/private';
29
30
  import { createCMS, emailOptionsFromEnv } from 'sandcms/server';
31
+ const env = process.env;
30
32
 
31
33
  const cms = createCMS({
32
34
  database: env.SANDCMS_DATABASE!,
@@ -42,7 +44,7 @@ Call from server code and await the result:
42
44
 
43
45
  ```ts
44
46
  import { EmailError } from 'sandcms/server';
45
- import { getCMS } from '$lib/server/sandcms';
47
+ import { getCMS } from '#lib/server/sandcms/index.js';
46
48
 
47
49
  try {
48
50
  const result = await getCMS().email.send({
@@ -62,9 +64,9 @@ try {
62
64
 
63
65
  Each message accepts one bare recipient address. A nonempty subject and plain-text body are required; HTML is optional. Escape untrusted values when composing HTML. The configured sender may include a simple display name (`Example <sender@example.com>`). Reply-to accepts one bare address and can override the configured default. Attachments, recipient lists, arbitrary headers and per-message sender overrides are not supported.
64
66
 
65
- `EmailError.code` is `NOT_CONFIGURED`, `CONFIGURATION`, `INVALID_MESSAGE` or `SEND_FAILED`. Send errors exclude raw provider responses, credentials and message content. The service does not log or store messages.
67
+ `EmailError.code` is `NOT_CONFIGURED`, `CONFIGURATION`, `INVALID_MESSAGE` or `SEND_FAILED`. Send errors exclude raw provider responses, credentials and message content. The service does not log or store messages. `SEND_FAILED` errors include an allowlisted `reason`: `timeout`, `dns`, `connection`, `authentication`, `tls`, `recipient_rejected`, `message_rejected`, or `unknown`. Use `emailFailureMessage(error.reason)` from `sandcms/server` for fixed, actionable text. Custom adapters may throw `EmailError('SEND_FAILED', 'Email could not be sent', 'timeout')`; arbitrary adapter messages and unrecognized reasons are discarded.
66
68
 
67
- Success means the SMTP server accepted the message, not that it reached an inbox. Delivery is direct, with no queue, automatic retries or bounce tracking. The sending service itself does not persist messages; the built-in workflows store link hashes and send outcomes as described below. DNS, connection and greeting timeouts are 10 seconds; socket inactivity times out after 30 seconds. These are stage/inactivity limits, not a total send deadline. A failed connection can leave delivery uncertain. Applications decide whether to ignore failures or retry; retries can duplicate a message.
69
+ Success means the SMTP server accepted the message, not that it reached an inbox. Delivery is direct, with no durable queue, automatic retries or bounce tracking. Each email service limits active sends to two across all workflows, including custom adapters; up to 100 additional sends wait in process memory by default. Configure `email.maxPendingSends` with a non-negative integer to change the waiting limit (zero disables waiting). When the queue is full, new sends fail with `SEND_FAILED`; form notification outcomes record the failure without rejecting the saved submission. Separate CMS instances or processes have separate limits. The sending service itself does not persist messages; the built-in workflows store link hashes and send outcomes as described below. DNS, connection and greeting timeouts are 10 seconds; socket inactivity times out after 30 seconds. These are stage/inactivity limits, not a total send deadline. A failed connection can leave delivery uncertain. Applications decide whether to ignore failures or retry; retries can duplicate a message.
68
70
 
69
71
  ## Local mail capture
70
72
 
@@ -107,9 +109,9 @@ The SMTP adapter uses [Nodemailer's SMTP transport](https://nodemailer.com/smtp)
107
109
 
108
110
  With email configured, admins can use **Users → Invite user** to invite an admin or editor. The recipient chooses their own name and password. Invitations expire after seven days, are single-use, and store only a token hash. Pending invitations show email acceptance/failure and support resend and revoke. Resending invalidates the earlier link. Manual account creation with a temporary password remains available.
109
111
 
110
- The login screen offers **Forgot password?** when email is configured. Reset requests return the same message for unknown accounts and failed sends. Reset links expire after one hour, work once, and are invalidated by another request or a password change. Completing a reset revokes all sessions and preserves two-factor authentication; the user must sign in again. Public requests are rate-limited by client address and reset requests by email address. Links use the configured CMS origin and keep their token in the URL fragment, which is removed when the page loads. Keep the full link when opening it.
112
+ The login screen offers **Forgot password?** when email is configured. Reset requests return the same message for unknown accounts and failed sends. New reset links expire after 15 minutes and work once. Up to three links can be active per email address; requesting another does not invalidate earlier links. Requests at the active-link limit silently do nothing until a link expires or the password changes. Completing a reset removes all reset links for that email, and any password change makes earlier links unusable. The existing three-requests-per-hour email limit still applies, including failed or suppressed requests. Completing a reset revokes all sessions and preserves two-factor authentication; the user must sign in again. Public requests are rate-limited by client address and reset requests by email address. Links use the configured CMS origin and keep their token in the URL fragment, which is removed when the page loads. Keep the full link when opening it.
111
113
 
112
- A provider accepting an email does not confirm inbox delivery. An interrupted send can leave an uncertain outcome; resending can duplicate an email. Nothing retries automatically. SMTP failures appear on invitations; reset requests deliberately do not disclose account existence or delivery status.
114
+ A provider accepting an email does not confirm inbox delivery. An interrupted send can leave an uncertain outcome; resending can duplicate an email. Nothing retries automatically. Invitations and notification outcomes persist safe failure reasons and show actionable text in the admin. A new attempt clears the previous reason; historical failures without a reason show generic guidance. “Accepted by mail server” refers to transport acceptance, separate from accepting an invitation. SMTP failures appear on invitations; reset requests deliberately do not disclose account existence or delivery status.
113
115
 
114
116
  ## Form notifications
115
117
 
@@ -117,7 +119,9 @@ Admins configure each form through **Forms → Notifications**. Settings are sto
117
119
 
118
120
  The default email contains a notification and a link to the submission in the admin. Alternatively, choose individual fields to include. Nested groups are expanded into individual fields; repeated groups, files, galleries and rich text are excluded. New or unselected fields are never automatically included. A text field can supply reply-to when its submitted value is a valid bare email address; otherwise the configured default is used. Emails include a simple HTML layout using the CMS purple and stone palette, plus a plain-text alternative. Invitations and password resets use the same layout with a prominent action button and a fallback link. Submitted values are escaped before inclusion in HTML.
119
121
 
120
- Always **await `cms.forms.submit(...)`**. Accepted submissions are saved before email is attempted, and SMTP failure does not reject the submission. Honeypots and rejected submissions do not send notifications. Sending is direct and adds the provider's response time to the request.
122
+ Always **await `cms.forms.submit(...)`** to confirm storage. Automatic notifications are fire-and-forget: submission success means the submission was saved, without waiting for SMTP or notification outcomes. Notification errors do not reject a saved submission. Unexpected notification errors log only a generic message and the submission ID. Honeypots and rejected submissions do not send notifications.
123
+
124
+ Notifications are best effort and require a server that continues executing after the response. A shutdown, deployment, or host that suspends execution after responding can lose pending notifications. There is no durable queue or automatic recovery; submissions remain in the inbox and staff can resend manually.
121
125
 
122
126
  The submission view shows the latest attempt and each recipient's acceptance/failure. Staff can resend using current notification settings; this sends to all currently configured recipients, including those whose previous email was accepted. A process interruption may leave “sending or outcome unknown”; wait two minutes before attempting another send. The feature does not automatically recover interrupted sends. Deleted submissions cannot be resent; deleting a submission cannot recall email already sent.
123
127
 
package/docs/forms.md CHANGED
@@ -11,8 +11,10 @@ const result = await cms.forms.submit('registration', validatedData, {
11
11
 
12
12
  The helper accepts plain JSON objects up to 64 KB, rejects cycles, non-finite numbers, reserved keys, and excessive nesting, silently ignores filled honeypots, and applies a durable per-form/per-client limit of five accepted attempts per minute. Supply a server-derived client identity. Never pass a browser-provided identity or trust proxy headers without configuring your host's trusted proxy chain.
13
13
 
14
+ Behind Dokploy and Cloudflare, configure both `ADDRESS_HEADER` and `SANDCMS_TRUSTED_PROXY_HEADER` as described in the [client IP recipe](deployment.md#client-ip-behind-dokploy-and-cloudflare). The CMS setting alone does not change `event.getClientAddress()` in website form actions; without adapter configuration, visitors can share the proxy's five-attempt bucket.
15
+
14
16
  Form YAML supplies stable IDs, labels, optional nested field groups, list `columns`, and `export` ordering. Each accepted submission stores its own blueprint snapshot so prior labels and export columns remain readable after changes. Both CMS roles can read, mark read/unread, export CSV, and delete. Export preserves historical field labels and guards formula-like spreadsheet cells.
15
17
 
16
18
  `src/routes/(site)/registration` demonstrates native `use:enhance`, participant name, birth date, contact/address, program selection, gender, prior experience, and conditional guardian contact. The server independently checks the participant's age and requires guardian contact under 18; changing client-side markup cannot bypass that validation.
17
19
 
18
- Submissions stay until a staff member deletes them. Company review policy and deletion from backups are operator responsibilities. Admins can enable email notifications per form, choose recipients and selected fields, and inspect send outcomes in the inbox. See [transactional email](email.md#form-notifications). There are no replies, assignments, attachment uploads, or CMS retention schedules.
20
+ Submissions stay until a staff member deletes them. Company review policy and deletion from backups are operator responsibilities. Admins can enable best-effort email notifications per form, choose recipients and selected fields, and inspect send outcomes in the inbox. Submission success confirms storage without waiting for email; pending notifications can be lost when the server stops. See [transactional email](email.md#form-notifications). There are no replies, assignments, attachment uploads, or CMS retention schedules.