sandcms 0.6.0 → 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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # SandCMS
2
2
 
3
- **0.6.0** adds admin search, entry duplication, reusable and conditional blueprint fields, editor layouts, link fields, image focal points, and agent API keys. It also upgrades to SvelteKit 3 and introduces direct R2 uploads and durable media deletion. Existing supported data and project-owned YAML are preserved; upgrading requires retained migrations, framework configuration changes, and the protocol-5 media Worker. See the [0.6.0 release notes](docs/releases.md#060), [upgrade workflow](docs/upgrades.md#060-upgrade-checklist) and [agent instructions](AGENTS.md).
3
+ **0.6.1** renames the media Worker secrets to the `SANDCMS_` prefix and adds opt-in automatic migration on website start with `SANDCMS_AUTO_MIGRATE=true`. Set the renamed Worker secrets before deploying the updated Worker; there is no new database migration, and stored data and project-owned YAML are preserved. See the [0.6.1 release notes](docs/releases.md#061), [upgrade workflow](docs/upgrades.md#061-upgrade-checklist) and [agent instructions](AGENTS.md).
4
4
 
5
5
  SandCMS embeds a content workspace into a SvelteKit website. Developers own YAML blueprints and public routes; editors manage drafts, publication, images, and form submissions at `/admin`.
6
6
 
@@ -97,12 +97,12 @@ export async function configureWorker(root, name) {
97
97
  writeFileSync(envFile, old + `\nSANDCMS_WORKER_TOKEN=${secret}\n`, { mode: 0o600 });
98
98
  chmodSync(envFile, 0o600);
99
99
  // Establish the Worker before secret put, which otherwise prompts to create a draft Worker.
100
- // Without CMS_TOKEN, all internal endpoints fail closed. No original is public at any stage.
100
+ // Without SANDCMS_WORKER_TOKEN, all internal endpoints fail closed. No original is public at any stage.
101
101
  const deployed = await capture(['deploy', '--config', file]);
102
102
  console.log(deployed);
103
- await run([...wrangler, 'secret', 'put', 'CMS_TOKEN', '--config', file], root, secret + '\n');
104
- await run([...wrangler, 'secret', 'put', 'R2_ACCOUNT_ID', '--config', file], root, accountId + '\n');
105
- await run([...wrangler, 'secret', 'put', 'R2_BUCKET_NAME', '--config', file], root, bucket + '\n');
103
+ await run([...wrangler, 'secret', 'put', 'SANDCMS_WORKER_TOKEN', '--config', file], root, secret + '\n');
104
+ await run([...wrangler, 'secret', 'put', 'SANDCMS_CF_ACCOUNT_ID', '--config', file], root, accountId + '\n');
105
+ await run([...wrangler, 'secret', 'put', 'SANDCMS_R2_BUCKET_NAME', '--config', file], root, bucket + '\n');
106
106
  console.log(`Create an R2 API token with Object Read & Write access restricted to ${bucket}: https://dash.cloudflare.com/?to=/:account/r2/api-tokens`);
107
107
  const accessKey = answer(await p.password({
108
108
  message: 'R2 Access Key ID',
@@ -112,8 +112,8 @@ export async function configureWorker(root, name) {
112
112
  message: 'R2 Secret Access Key',
113
113
  validate: (v) => (v?.trim() ? undefined : 'Required for direct uploads')
114
114
  }));
115
- await run([...wrangler, 'secret', 'put', 'R2_ACCESS_KEY_ID', '--config', file], root, accessKey.trim() + '\n');
116
- await run([...wrangler, 'secret', 'put', 'R2_SECRET_ACCESS_KEY', '--config', file], root, secretKey.trim() + '\n');
115
+ await run([...wrangler, 'secret', 'put', 'SANDCMS_R2_ACCESS_KEY_ID', '--config', file], root, accessKey.trim() + '\n');
116
+ await run([...wrangler, 'secret', 'put', 'SANDCMS_R2_SECRET_ACCESS_KEY', '--config', file], root, secretKey.trim() + '\n');
117
117
  const url = deployed.match(/https:\/\/[a-z0-9.-]+\.workers\.dev/i)?.[0];
118
118
  if (!url)
119
119
  throw new Error('Worker deployed; copy its URL into config.yaml before marking provisioning ready.');
@@ -12,6 +12,8 @@ export interface CmsOptions {
12
12
  workerUrl?: string;
13
13
  trustedProxyHeader?: string;
14
14
  migrate?: boolean;
15
+ /** Back up an existing database, then apply pending migrations on startup. */
16
+ autoMigrate?: boolean;
15
17
  email?: EmailOptions;
16
18
  seo?: SeoOptions;
17
19
  }
@@ -2,6 +2,7 @@ import { createLinkResolver } from './links.js';
2
2
  import { configureFileFields } from '../blueprints/files.js';
3
3
  import { loadDefinition } from '../blueprints/load.js';
4
4
  import { openStore, assertSchema } from './db/store.js';
5
+ import { autoMigrate } from './db/auto-migrate.js';
5
6
  import { createAuth, requireUser } from './auth.js';
6
7
  import { createContent } from './content.js';
7
8
  import { createSEO } from './seo.js';
@@ -13,8 +14,17 @@ import { createMedia } from './media/service.js';
13
14
  import { error } from '@sveltejs/kit';
14
15
  export function createCMS(options) {
15
16
  options = { ...options, origin: new URL(options.origin).origin };
17
+ // migrate would apply pending migrations before autoMigrate could take its snapshot.
18
+ if (options.migrate && options.autoMigrate)
19
+ throw new Error('Use either migrate or autoMigrate, not both.');
16
20
  const definition = configureFileFields(options.definition ?? loadDefinition(options.root)), store = openStore(options.database, { migrate: options.migrate });
17
21
  try {
22
+ if (options.autoMigrate) {
23
+ const result = autoMigrate(store);
24
+ if (result.applied.length)
25
+ console.info(`SandCMS applied migrations: ${result.applied.join(', ')}` +
26
+ (result.backup ? `. Backup: ${result.backup}` : ''));
27
+ }
18
28
  assertSchema(store);
19
29
  const email = createEmail(options.email), auth = createAuth(store, options), content = createContent(store, definition), notifications = createNotifications(store, definition, email, options.origin), forms = createForms(store, definition, notifications.send), media = createMedia(store, definition, content, options.workerToken ?? '', options.workerUrl);
20
30
  return {
@@ -0,0 +1,12 @@
1
+ import { type Store } from './store.js';
2
+ /**
3
+ * Apply pending migrations when the website starts. An existing database is first copied to a
4
+ * verified `<database>.before-migrate-<timestamp>-<id>.sqlite` snapshot next to it.
5
+ */
6
+ export declare function autoMigrate(store: Store): {
7
+ applied: string[];
8
+ backup?: undefined;
9
+ } | {
10
+ applied: string[];
11
+ backup: string | undefined;
12
+ };
@@ -0,0 +1,23 @@
1
+ import { backup } from '../../cli/backup.js';
2
+ import { applyMigrations, pendingMigrations } from './store.js';
3
+ /**
4
+ * Apply pending migrations when the website starts. An existing database is first copied to a
5
+ * verified `<database>.before-migrate-<timestamp>-<id>.sqlite` snapshot next to it.
6
+ */
7
+ export function autoMigrate(store) {
8
+ if (!pendingMigrations(store).length)
9
+ return { applied: [] };
10
+ const version = store.sqlite.query('PRAGMA user_version').get();
11
+ if (version.user_version === 0) {
12
+ // Without history, only an empty database is fresh; anything else cannot be snapshotted safely.
13
+ const tables = store.sqlite
14
+ .query("SELECT 1 FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' AND name != 'schema_migrations' LIMIT 1")
15
+ .get();
16
+ if (tables)
17
+ throw new Error('Database has no migration history but is not empty; automatic migration refused. Use the matching package version or an explicitly initialized fresh database. See docs/upgrades.md.');
18
+ }
19
+ const snapshot = store.path !== ':memory:' && version.user_version > 0
20
+ ? backup(store.path, `${store.path}.before-migrate-${Date.now()}-${crypto.randomUUID().slice(0, 8)}.sqlite`)
21
+ : undefined;
22
+ return { applied: applyMigrations(store), backup: snapshot };
23
+ }
@@ -71,15 +71,19 @@ export function openStore(path, { migrate = false, guard = true } = {}) {
71
71
  }
72
72
  }
73
73
  export function pendingMigrations(store) {
74
- const version = store.sqlite.query('PRAGMA user_version').get();
75
- if (version.user_version > SCHEMA_VERSION)
76
- throw new Error(`Database schema is incompatible with this package. ${resetGuidance}`);
77
- const exists = store.sqlite
78
- .query("SELECT name FROM sqlite_master WHERE name='schema_migrations'")
74
+ // Each statement reads one snapshot, so a concurrent migration cannot mix version and history.
75
+ const state = store.sqlite
76
+ .query("SELECT user_version, EXISTS (SELECT 1 FROM sqlite_master WHERE name='schema_migrations') AS tracked FROM pragma_user_version")
79
77
  .get();
80
- const applied = exists
81
- ? store.sqlite.query('SELECT name, hash FROM schema_migrations ORDER BY name').all()
78
+ const rows = state.tracked
79
+ ? store.sqlite
80
+ .query('SELECT NULL AS name, NULL AS hash, user_version FROM pragma_user_version UNION ALL SELECT name, hash, NULL FROM schema_migrations ORDER BY name')
81
+ .all()
82
82
  : [];
83
+ const version = { user_version: rows[0]?.user_version ?? state.user_version };
84
+ const applied = rows.slice(1);
85
+ if (version.user_version > SCHEMA_VERSION)
86
+ throw new Error(`Database schema is incompatible with this package. ${resetGuidance}`);
83
87
  const available = migrations();
84
88
  for (const old of applied) {
85
89
  const m = available.find((m) => m.name === old.name);
@@ -101,16 +105,27 @@ export function applyMigrations(store) {
101
105
  const completed = [];
102
106
  for (const m of pending) {
103
107
  try {
104
- store.sqlite
108
+ const applied = store.sqlite
105
109
  .transaction(() => {
110
+ // Another process starting concurrently may have applied it after the pending check.
111
+ const recorded = store.sqlite
112
+ .query('SELECT hash FROM schema_migrations WHERE name = ?')
113
+ .get(m.name);
114
+ if (recorded) {
115
+ if (recorded.hash !== m.hash)
116
+ throw new Error(`Incompatible or modified migration ${m.name}. ${resetGuidance}`);
117
+ return false;
118
+ }
106
119
  store.sqlite.exec(m.sql);
107
120
  store.sqlite
108
121
  .query('INSERT INTO schema_migrations VALUES (?, ?, ?)')
109
122
  .run(m.name, m.hash, Date.now());
110
123
  store.sqlite.exec(`PRAGMA user_version=${migrations().findIndex((item) => item.name === m.name) + 1}`);
124
+ return true;
111
125
  })
112
126
  .immediate();
113
- completed.push(m.name);
127
+ if (applied)
128
+ completed.push(m.name);
114
129
  }
115
130
  catch (cause) {
116
131
  throw new Error(`Migration ${m.name} failed. Applied in this run: ${completed.join(', ') || 'none'}. ${String(cause)}`, { cause });
@@ -2,6 +2,7 @@ export { createCMS, type CMS, type CmsOptions } from './cms.js';
2
2
  export { cmsHandle, adminLoad, apiHandler } from './http.js';
3
3
  export { createUser, recoverUser } from './auth.js';
4
4
  export { openStore, applyMigrations, pendingMigrations } from './db/store.js';
5
+ export { autoMigrate } from './db/auto-migrate.js';
5
6
  export { loadDefinition } from '../blueprints/load.js';
6
7
  export { honeypotName } from './forms.js';
7
8
  export { createEmail, createSmtpAdapter, emailOptionsFromEnv, EmailError, type EmailMessage, type EmailResult, type EmailAdapter, type EmailOptions, type SmtpOptions, emailFailureMessage, type EmailFailureReason, type EmailErrorCode } from './email/index.js';
@@ -2,6 +2,7 @@ export { createCMS } from './cms.js';
2
2
  export { cmsHandle, adminLoad, apiHandler } from './http.js';
3
3
  export { createUser, recoverUser } from './auth.js';
4
4
  export { openStore, applyMigrations, pendingMigrations } from './db/store.js';
5
+ export { autoMigrate } from './db/auto-migrate.js';
5
6
  export { loadDefinition } from '../blueprints/load.js';
6
7
  export { honeypotName } from './forms.js';
7
8
  export { createEmail, createSmtpAdapter, emailOptionsFromEnv, EmailError, emailFailureMessage } from './email/index.js';
@@ -2,7 +2,7 @@ import type { R2Bucket } from '@cloudflare/workers-types/index.ts';
2
2
  import { type UploadSigningEnv } from './uploads.js';
3
3
  export interface WorkerEnv extends UploadSigningEnv {
4
4
  MEDIA: R2Bucket;
5
- CMS_TOKEN: string;
5
+ SANDCMS_WORKER_TOKEN: string;
6
6
  }
7
7
  declare const _default: {
8
8
  fetch(request: Request, env: WorkerEnv): Promise<Response>;
@@ -19,10 +19,10 @@ async function putAsset(env, id, key, value, options) {
19
19
  return stored;
20
20
  }
21
21
  async function authenticated(request, env) {
22
- if (!env.CMS_TOKEN || env.CMS_TOKEN.length < 32)
22
+ if (!env.SANDCMS_WORKER_TOKEN || env.SANDCMS_WORKER_TOKEN.length < 32)
23
23
  return false;
24
24
  const got = request.headers.get('authorization') ?? '';
25
- const a = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(got))), b = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`Bearer ${env.CMS_TOKEN}`)));
25
+ const a = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(got))), b = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`Bearer ${env.SANDCMS_WORKER_TOKEN}`)));
26
26
  let diff = 0;
27
27
  for (let i = 0; i < a.length; i++)
28
28
  diff |= a[i] ^ b[i];
@@ -117,7 +117,7 @@ export default {
117
117
  !idPattern.test(id) ||
118
118
  (staging !== undefined && !idPattern.test(staging)) ||
119
119
  extra.length > 0 ||
120
- !(await validSource(url, env.CMS_TOKEN)))
120
+ !(await validSource(url, env.SANDCMS_WORKER_TOKEN)))
121
121
  return new Response('Not found', {
122
122
  status: 404,
123
123
  headers: { 'Cache-Control': 'private, no-store' }
@@ -196,7 +196,7 @@ export default {
196
196
  await env.MEDIA.put(validation, object.body, {
197
197
  httpMetadata: { contentType: input.mime }
198
198
  });
199
- const info = await inspect(await sourceURL(url.origin, id, env.CMS_TOKEN, validationAttempt));
199
+ const info = await inspect(await sourceURL(url.origin, id, env.SANDCMS_WORKER_TOKEN, validationAttempt));
200
200
  const validated = await env.MEDIA.get(validation);
201
201
  if (!validated)
202
202
  throw new Error('Upload snapshot missing');
@@ -288,7 +288,7 @@ export default {
288
288
  });
289
289
  if (!stored || stored.size !== length)
290
290
  throw new Error('Upload length mismatch');
291
- const info = await inspect(await sourceURL(url.origin, id, env.CMS_TOKEN, attempt));
291
+ const info = await inspect(await sourceURL(url.origin, id, env.SANDCMS_WORKER_TOKEN, attempt));
292
292
  const validated = await env.MEDIA.get(staging);
293
293
  if (!validated)
294
294
  throw new Error('Upload missing');
@@ -342,7 +342,7 @@ export default {
342
342
  if (body.format === 'svg')
343
343
  throw new Error('Raster input cannot become SVG');
344
344
  await original.body.cancel();
345
- const source = await sourceURL(url.origin, id, env.CMS_TOKEN);
345
+ const source = await sourceURL(url.origin, id, env.SANDCMS_WORKER_TOKEN);
346
346
  // Older originals have no saved dimensions; inspect them remotely on rebuild.
347
347
  const metadata = original.customMetadata;
348
348
  const info = metadata?.width && metadata?.height
@@ -8,10 +8,10 @@ export default {
8
8
  return new Response('Local media Worker requires a loopback hostname', { status: 403 });
9
9
  const local = {
10
10
  ...env,
11
- R2_ENDPOINT: url.origin,
12
- R2_BUCKET_NAME: 'local-media',
13
- R2_ACCESS_KEY_ID: 'local-only',
14
- R2_SECRET_ACCESS_KEY: env.CMS_TOKEN
11
+ SANDCMS_R2_ENDPOINT: url.origin,
12
+ SANDCMS_R2_BUCKET_NAME: 'local-media',
13
+ SANDCMS_R2_ACCESS_KEY_ID: 'local-only',
14
+ SANDCMS_R2_SECRET_ACCESS_KEY: env.SANDCMS_WORKER_TOKEN
15
15
  };
16
16
  if (!url.pathname.startsWith('/local-media/'))
17
17
  return worker.fetch(request, local);
@@ -30,7 +30,7 @@ export default {
30
30
  const signature = url.searchParams.get('X-Amz-Signature');
31
31
  const expires = Number(url.searchParams.get('X-Amz-Expires'));
32
32
  const timestamp = Date.parse(date.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/, '$1-$2-$3T$4:$5:$6Z'));
33
- if (!env.CMS_TOKEN ||
33
+ if (!env.SANDCMS_WORKER_TOKEN ||
34
34
  request.method !== 'PUT' ||
35
35
  !/^incoming\/[a-f0-9-]{36}\/[a-f0-9-]{36}$/.test(key) ||
36
36
  !Number.isFinite(timestamp) ||
@@ -1,10 +1,10 @@
1
1
  import { AwsClient } from 'aws4fetch';
2
2
  export interface UploadSigningEnv {
3
- R2_ACCOUNT_ID?: string;
4
- R2_BUCKET_NAME?: string;
5
- R2_ACCESS_KEY_ID?: string;
6
- R2_SECRET_ACCESS_KEY?: string;
7
- R2_ENDPOINT?: string;
3
+ SANDCMS_CF_ACCOUNT_ID?: string;
4
+ SANDCMS_R2_BUCKET_NAME?: string;
5
+ SANDCMS_R2_ACCESS_KEY_ID?: string;
6
+ SANDCMS_R2_SECRET_ACCESS_KEY?: string;
7
+ SANDCMS_R2_ENDPOINT?: string;
8
8
  }
9
9
  export declare const uploadLifetime = 900;
10
10
  export declare function uploadSigner(env: UploadSigningEnv): AwsClient;
@@ -1,23 +1,25 @@
1
1
  import { AwsClient } from 'aws4fetch';
2
2
  export const uploadLifetime = 900;
3
3
  export function uploadSigner(env) {
4
- if (!env.R2_ACCESS_KEY_ID || !env.R2_SECRET_ACCESS_KEY || !env.R2_BUCKET_NAME)
5
- throw new Error('Configure R2_BUCKET_NAME, R2_ACCESS_KEY_ID and R2_SECRET_ACCESS_KEY on the media Worker');
4
+ if (!env.SANDCMS_R2_ACCESS_KEY_ID ||
5
+ !env.SANDCMS_R2_SECRET_ACCESS_KEY ||
6
+ !env.SANDCMS_R2_BUCKET_NAME)
7
+ throw new Error('Configure SANDCMS_R2_BUCKET_NAME, SANDCMS_R2_ACCESS_KEY_ID and SANDCMS_R2_SECRET_ACCESS_KEY on the media Worker');
6
8
  return new AwsClient({
7
9
  service: 's3',
8
10
  region: 'auto',
9
- accessKeyId: env.R2_ACCESS_KEY_ID,
10
- secretAccessKey: env.R2_SECRET_ACCESS_KEY
11
+ accessKeyId: env.SANDCMS_R2_ACCESS_KEY_ID,
12
+ secretAccessKey: env.SANDCMS_R2_SECRET_ACCESS_KEY
11
13
  });
12
14
  }
13
15
  export async function presignUpload(env, key, mime) {
14
16
  const signer = uploadSigner(env);
15
- if (!env.R2_ENDPOINT && !env.R2_ACCOUNT_ID)
16
- throw new Error('Configure R2_ACCOUNT_ID on the media Worker');
17
- const endpoint = env.R2_ENDPOINT ?? `https://${env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`;
18
- const url = new URL(`${endpoint.replace(/\/$/, '')}/${encodeURIComponent(env.R2_BUCKET_NAME)}/${key}`);
17
+ if (!env.SANDCMS_R2_ENDPOINT && !env.SANDCMS_CF_ACCOUNT_ID)
18
+ throw new Error('Configure SANDCMS_CF_ACCOUNT_ID on the media Worker');
19
+ const endpoint = env.SANDCMS_R2_ENDPOINT ?? `https://${env.SANDCMS_CF_ACCOUNT_ID}.r2.cloudflarestorage.com`;
20
+ const url = new URL(`${endpoint.replace(/\/$/, '')}/${encodeURIComponent(env.SANDCMS_R2_BUCKET_NAME)}/${key}`);
19
21
  if (url.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
20
- throw new Error('R2_ENDPOINT must use HTTPS');
22
+ throw new Error('SANDCMS_R2_ENDPOINT must use HTTPS');
21
23
  url.searchParams.set('X-Amz-Expires', String(uploadLifetime));
22
24
  const signed = await signer.sign(url, {
23
25
  method: 'PUT',
@@ -7,7 +7,7 @@ Website proxy caching is optional and separate from Worker deployment. Public im
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
 
@@ -25,7 +25,7 @@ Setup optionally uses the existing Wrangler login, asks for an account, displays
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
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/*`.
@@ -38,11 +38,11 @@ The browser uploads to the R2 S3 API endpoint using a 15-minute presigned PUT UR
38
38
 
39
39
  Set these **Worker** secrets with `bun x wrangler secret put NAME --config sandcms/worker/wrangler.jsonc`:
40
40
 
41
- - `R2_ACCOUNT_ID`: the account containing the bucket.
42
- - `R2_BUCKET_NAME`: exactly the bucket bound as `MEDIA`.
43
- - `R2_ACCESS_KEY_ID` and `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 `CMS_TOKEN`; never put them in browser or website configuration.
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
44
 
45
- For a jurisdiction-specific endpoint, set optional Worker `R2_ENDPOINT` to its HTTPS S3 endpoint. The endpoint and bucket must address the same bucket as `MEDIA`.
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
46
 
47
47
  Configure bucket CORS in R2 Settings for every authorized admin origin (merge with existing project-owned rules):
48
48
 
@@ -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:
package/docs/package.md CHANGED
@@ -17,13 +17,13 @@ npm pack --dry-run
17
17
  npm pack --pack-destination /tmp
18
18
  ```
19
19
 
20
- This release produces `/tmp/sandcms-0.6.0.tgz`. `npm pack` builds the package through `prepack`; it packages only the allowlisted distribution, templates, documentation, and package metadata. The repository's example website, tests, databases, and environment files are excluded. `release:check` checks types, runs unit tests, inspects an npm archive, and installs/builds that archive in both a fresh starter and an existing SvelteKit site.
20
+ This release produces `/tmp/sandcms-0.6.1.tgz`. `npm pack` builds the package through `prepack`; it packages only the allowlisted distribution, templates, documentation, and package metadata. The repository's example website, tests, databases, and environment files are excluded. `release:check` checks types, runs unit tests, inspects an npm archive, and installs/builds that archive in both a fresh starter and an existing SvelteKit site.
21
21
 
22
22
  Upload the archive you just built:
23
23
 
24
24
  ```sh
25
- npm publish /tmp/sandcms-0.6.0.tgz --access restricted --registry=https://registry.npmjs.org/
26
- npm view sandcms@0.6.0 version --registry=https://registry.npmjs.org/
25
+ npm publish /tmp/sandcms-0.6.1.tgz --access restricted --registry=https://registry.npmjs.org/
26
+ npm view sandcms@0.6.1 version --registry=https://registry.npmjs.org/
27
27
  ```
28
28
 
29
29
  Complete npm's authentication/2FA prompts. The logged-in account must have publishing permission in `sandquist-group`. The package also defaults to restricted access and the npmjs registry in `publishConfig`. Do not set `private: true` on this package: that prevents publication entirely. Generated websites do set it.
@@ -36,7 +36,7 @@ After publishing, authenticate as a user with read access to the package, then r
36
36
 
37
37
  ```sh
38
38
  npm login --registry=https://registry.npmjs.org/
39
- bunx --bun --package sandcms@0.6.0 sandcms setup --cwd ./my-site
39
+ bunx --bun --package sandcms@0.6.1 sandcms setup --cwd ./my-site
40
40
  cd my-site
41
41
  bun run dev
42
42
  ```
package/docs/releases.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Release notes
2
2
 
3
+ ## 0.6.1
4
+
5
+ This patch release renames the media Worker secrets and adds opt-in automatic migration on start. Before upgrading from 0.6.0, set the new `SANDCMS_`-prefixed Worker secrets, then deploy the Worker with `sandcms worker update`; see the [0.6.1 upgrade checklist](upgrades.md#061-upgrade-checklist). There is no new SQL migration, and website environment variables, stored data and project-owned YAML are unchanged.
6
+
7
+ **Breaking:** Worker secrets now use the `SANDCMS_` prefix. `CMS_TOKEN` is renamed to `SANDCMS_WORKER_TOKEN`, matching the website variable that holds the same value, and the direct-upload secrets `R2_ACCOUNT_ID`, `R2_BUCKET_NAME`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` and optional `R2_ENDPOINT` become `SANDCMS_CF_ACCOUNT_ID` and `SANDCMS_R2_*`. Old names are not read. Set the new Worker secrets before running `sandcms worker update` and rename `CMS_TOKEN` in `sandcms/worker/.dev.vars`. Website environment variables, the database and project-owned YAML are unchanged. See [renamed Worker secrets](upgrades.md#renamed-worker-secrets).
8
+
9
+ Adds opt-in automatic migration on website start with `SANDCMS_AUTO_MIGRATE=true` (`createCMS({ autoMigrate: true })`). Existing databases receive a verified snapshot before pending migrations are applied; incompatible histories are still rejected and concurrent starts apply each migration once. No SQL migration is required; customized integrations must opt in explicitly. See [automatic migration](deployment.md#automatic-migration-on-start).
10
+
3
11
  ## 0.6.0
4
12
 
5
13
  This minor release adds new content editing and media capabilities and changes framework requirements and API contracts. Before upgrading from 0.5.x, review the [0.6.0 upgrade checklist](upgrades.md#060-upgrade-checklist): migrate developer-owned SvelteKit configuration, deploy the protocol-5 Worker and configure direct R2 uploads, then apply retained migrations `0001` through `0006` before restarting the website. Supported accounts, content, and media are preserved; project-owned YAML and customized application files remain protected.
package/docs/upgrades.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Updates and generated files
2
2
 
3
+ ## 0.6.1 upgrade checklist
4
+
5
+ Version 0.6.1 adds no SQL migration. Follow this order when upgrading from 0.6.0:
6
+
7
+ 1. Copy each Worker secret to its new `SANDCMS_` name for every environment, as described in [renamed Worker secrets](#renamed-worker-secrets), and rename `CMS_TOKEN` in `sandcms/worker/.dev.vars`.
8
+ 2. Install `sandcms@0.6.1`, review `sandcms upgrade --check`, then apply integration updates with `sandcms upgrade`.
9
+ 3. Deploy the Worker with `sandcms worker update`, then rebuild and restart the website. Verify uploads, then delete the old Worker secrets.
10
+ 4. Optionally set `SANDCMS_AUTO_MIGRATE=true` to apply future migrations on start; see [automatic migration on start](#automatic-migration-on-start).
11
+
12
+ Upgrading from 0.5.x still requires the [0.6.0 upgrade checklist](#060-upgrade-checklist) first.
13
+
14
+ ## Automatic migration on start
15
+
16
+ The website can apply pending migrations itself when `SANDCMS_AUTO_MIGRATE=true` is set. It first takes a verified snapshot of an existing database beside it, then runs the same per-migration transactional runner as `sandcms migrate`. Unmodified generated integrations receive the setting through `sandcms upgrade`; merge `autoMigrate: env.SANDCMS_AUTO_MIGRATE === 'true'` into customized `src/lib/server/sandcms/index.ts` files. No SQL migration or configuration change is required, and leaving the variable unset keeps the explicit workflow below. See [automatic migration](deployment.md#automatic-migration-on-start).
17
+
3
18
  ## 0.6.0 upgrade checklist
4
19
 
5
20
  Version 0.6.0 requires SvelteKit 3 and includes retained database migrations `0001` through `0006`. Follow this order when upgrading from 0.5.x:
@@ -12,6 +27,27 @@ Version 0.6.0 requires SvelteKit 3 and includes retained database migrations `00
12
27
 
13
28
  Blueprint features and focal-point cropping are opt-in for existing project-owned YAML. Review the feature instructions below before changing it. Rollback requires the matching old package and its verified backup; no down migrations or automatic database reset are provided.
14
29
 
30
+ ## Renamed Worker secrets
31
+
32
+ The media Worker no longer reads `CMS_TOKEN` or the `R2_*` direct-upload secrets. Before deploying the new Worker, copy each existing value to its new name for every environment:
33
+
34
+ | Old Worker secret | New Worker secret |
35
+ | ---------------------- | ------------------------------ |
36
+ | `CMS_TOKEN` | `SANDCMS_WORKER_TOKEN` |
37
+ | `R2_ACCOUNT_ID` | `SANDCMS_CF_ACCOUNT_ID` |
38
+ | `R2_BUCKET_NAME` | `SANDCMS_R2_BUCKET_NAME` |
39
+ | `R2_ACCESS_KEY_ID` | `SANDCMS_R2_ACCESS_KEY_ID` |
40
+ | `R2_SECRET_ACCESS_KEY` | `SANDCMS_R2_SECRET_ACCESS_KEY` |
41
+ | `R2_ENDPOINT` | `SANDCMS_R2_ENDPOINT` |
42
+
43
+ ```sh
44
+ bun x wrangler secret put SANDCMS_WORKER_TOKEN --config sandcms/worker/wrangler.jsonc
45
+ # Repeat for SANDCMS_CF_ACCOUNT_ID and each SANDCMS_R2_* secret, then deploy:
46
+ bun x --no-install sandcms worker update
47
+ ```
48
+
49
+ `SANDCMS_WORKER_TOKEN` must equal the website's existing `SANDCMS_WORKER_TOKEN`. Cloudflare does not reveal stored secret values; if you no longer have them, generate a new token and set it on both the website and the Worker, and reuse or recreate the bucket-scoped R2 API token. Until the new names are set, the updated Worker rejects CMS requests and direct uploads fail closed. After verifying uploads, remove the old secrets with `wrangler secret delete`. For local development, rename `CMS_TOKEN` to `SANDCMS_WORKER_TOKEN` in `sandcms/worker/.dev.vars`. No database migration or website environment change is required.
50
+
15
51
  ## Durable media deletion
16
52
 
17
53
  Deploy the updated media Worker first using `sandcms worker update`; it speaks protocol 5, still accepts protocol 3 and 4 website processes, and adds permanent deletion markers to prevent late writes from recreating removed assets. Preserve the private `deleted/` prefix indefinitely and retain the one-day `incoming/` lifecycle rule. Apply `0006_durable_media_deletion.sql` using the retained migration workflow below before restarting the updated website. It adds a deletion queue and preserves existing assets, pending jobs, accounts, content, and YAML. Deletion now revokes references and active variants immediately and may finish storage cleanup asynchronously.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sandcms",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "scripts": {
5
5
  "dev": "bun run styles && bun --bun vite dev",
6
6
  "build": "bun run validate && bun run styles && bun --bun vite build && bun run package",
@@ -12,7 +12,8 @@ export function getCMS() {
12
12
  email: emailOptionsFromEnv(env),
13
13
  workerToken: env.SANDCMS_WORKER_TOKEN,
14
14
  workerUrl: env.SANDCMS_WORKER_URL,
15
- trustedProxyHeader: env.SANDCMS_TRUSTED_PROXY_HEADER
15
+ trustedProxyHeader: env.SANDCMS_TRUSTED_PROXY_HEADER,
16
+ autoMigrate: env.SANDCMS_AUTO_MIGRATE === 'true'
16
17
  });
17
18
  instance.media.start();
18
19
  }