sandcms 0.6.3 → 0.7.0

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 (124) hide show
  1. package/README.md +14 -10
  2. package/dist/admin/Account.svelte +2 -0
  3. package/dist/admin/Admin.svelte +14 -1
  4. package/dist/admin/AssetAttachment.svelte +1 -3
  5. package/dist/admin/AssetAttachment.svelte.d.ts +0 -1
  6. package/dist/admin/BlueprintFields.svelte +0 -3
  7. package/dist/admin/BlueprintFields.svelte.d.ts +0 -1
  8. package/dist/admin/Editor.svelte +0 -1
  9. package/dist/admin/Fields.svelte +0 -7
  10. package/dist/admin/Fields.svelte.d.ts +0 -1
  11. package/dist/admin/Gallery.svelte +2 -6
  12. package/dist/admin/Gallery.svelte.d.ts +0 -1
  13. package/dist/admin/LinkField.svelte +0 -3
  14. package/dist/admin/LinkField.svelte.d.ts +0 -1
  15. package/dist/admin/MediaLibrary.svelte +10 -7
  16. package/dist/admin/MediaPicker.svelte +7 -15
  17. package/dist/admin/MediaPicker.svelte.d.ts +0 -1
  18. package/dist/admin/ThemePicker.svelte +72 -0
  19. package/dist/admin/ThemePicker.svelte.d.ts +18 -0
  20. package/dist/admin/UploadButton.svelte +2 -1
  21. package/dist/admin/UploadProgress.svelte +24 -0
  22. package/dist/admin/UploadProgress.svelte.d.ts +7 -0
  23. package/dist/admin/client.d.ts +3 -670
  24. package/dist/admin/client.js +2 -1
  25. package/dist/admin/components/ui/alert/alert.svelte.d.ts +3 -13
  26. package/dist/admin/components/ui/attachment/attachment-media.svelte.d.ts +3 -13
  27. package/dist/admin/components/ui/attachment/attachment.svelte.d.ts +6 -26
  28. package/dist/admin/components/ui/badge/badge.svelte.d.ts +7 -25
  29. package/dist/admin/components/ui/button/button.svelte.d.ts +15 -53
  30. package/dist/admin/components/ui/toggle/toggle.svelte.d.ts +6 -26
  31. package/dist/admin/generated/admin.css +529 -101
  32. package/dist/admin/theme-context.d.ts +7 -0
  33. package/dist/admin/theme-context.js +3 -0
  34. package/dist/admin/theme.d.ts +7 -0
  35. package/dist/admin/theme.js +14 -0
  36. package/dist/admin/types.d.ts +2 -1
  37. package/dist/admin/uploads.d.ts +8 -1
  38. package/dist/admin/uploads.js +94 -16
  39. package/dist/blueprints/files.js +1 -0
  40. package/dist/blueprints/load.js +7 -2
  41. package/dist/blueprints/types.d.ts +4 -1
  42. package/dist/cli/doctor.d.ts +3 -1
  43. package/dist/cli/doctor.js +85 -30
  44. package/dist/cli/files.d.ts +2 -6
  45. package/dist/cli/files.js +11 -2
  46. package/dist/cli/index.js +99 -31
  47. package/dist/cli/scaffold.js +8 -8
  48. package/dist/cli/setup.js +16 -26
  49. package/dist/cli/upgrade.js +21 -2
  50. package/dist/env.d.ts +32 -0
  51. package/dist/env.js +53 -3
  52. package/dist/server/admin-load.d.ts +13 -5
  53. package/dist/server/admin-load.js +6 -1
  54. package/dist/server/api-access.d.ts +4 -0
  55. package/dist/server/api-access.js +15 -2
  56. package/dist/server/api-pagination.d.ts +3 -0
  57. package/dist/server/api.js +5 -2
  58. package/dist/server/auth.d.ts +10 -9
  59. package/dist/server/cms.d.ts +65 -18
  60. package/dist/server/cms.js +62 -6
  61. package/dist/server/db/migration-data.js +4 -0
  62. package/dist/server/db/migrations/0009_local_media.sql +9 -0
  63. package/dist/server/db/migrations/meta/0009_snapshot.json +1763 -0
  64. package/dist/server/db/migrations/meta/_journal.json +7 -0
  65. package/dist/server/db/schema.d.ts +119 -2
  66. package/dist/server/db/schema.js +15 -3
  67. package/dist/server/hooks.js +155 -81
  68. package/dist/server/media/contracts.d.ts +115 -0
  69. package/dist/server/media/contracts.js +12 -0
  70. package/dist/server/media/deletions.d.ts +2 -1
  71. package/dist/server/media/deletions.js +3 -3
  72. package/dist/server/media/delivery.js +7 -11
  73. package/dist/server/media/import-r2.d.ts +56 -0
  74. package/dist/server/media/import-r2.js +342 -0
  75. package/dist/server/media/processor-child.d.ts +2 -0
  76. package/dist/server/media/processor-child.js +236 -0
  77. package/dist/server/media/processor.d.ts +51 -0
  78. package/dist/server/media/processor.js +135 -0
  79. package/dist/server/media/render-math.d.ts +24 -0
  80. package/dist/server/media/render-math.js +50 -0
  81. package/dist/server/media/runner.d.ts +30 -1
  82. package/dist/server/media/runner.js +418 -165
  83. package/dist/server/media/service.d.ts +56 -10
  84. package/dist/server/media/service.js +309 -98
  85. package/dist/server/media/storage.d.ts +5 -0
  86. package/dist/server/media/storage.js +279 -0
  87. package/dist/server/media/svg.d.ts +5 -0
  88. package/dist/server/media/svg.js +142 -0
  89. package/dist/server/media/upload-ticket.d.ts +12 -0
  90. package/dist/server/media/upload-ticket.js +35 -0
  91. package/dist/server/media/verify.d.ts +36 -0
  92. package/dist/server/media/verify.js +109 -0
  93. package/dist/server/platform/http.d.ts +27 -0
  94. package/dist/server/platform/http.js +77 -0
  95. package/dist/server/platform/index.d.ts +52 -0
  96. package/dist/server/platform/index.js +98 -0
  97. package/dist/server/platform/snapshots.d.ts +18 -0
  98. package/dist/server/platform/snapshots.js +110 -0
  99. package/dist/server/platform/volume.d.ts +20 -0
  100. package/dist/server/platform/volume.js +60 -0
  101. package/dist/worker/svg.d.ts +1 -5
  102. package/dist/worker/svg.js +2 -142
  103. package/docs/acceptance.md +6 -4
  104. package/docs/api.md +41 -3
  105. package/docs/cloudflare.md +48 -142
  106. package/docs/content.md +2 -2
  107. package/docs/deployment.md +159 -57
  108. package/docs/forms.md +1 -1
  109. package/docs/media.md +85 -21
  110. package/docs/package.md +21 -18
  111. package/docs/plans/0.7-self-hosted.md +264 -0
  112. package/docs/releases.md +17 -1
  113. package/docs/upgrades.md +35 -6
  114. package/package.json +36 -37
  115. package/templates/Dockerfile +28 -0
  116. package/templates/integration.ts +18 -2
  117. package/templates/railpack.json +1 -1
  118. package/templates/sandcms/blueprints/files/image.yaml +1 -1
  119. package/templates/sandcms/config.yaml +0 -1
  120. package/dist/cli/cloudflare.d.ts +0 -8
  121. package/dist/cli/cloudflare.js +0 -135
  122. package/templates/sandcms/worker/index.ts +0 -1
  123. package/templates/sandcms/worker/local.ts +0 -1
  124. package/templates/sandcms/worker/wrangler.jsonc +0 -6
@@ -0,0 +1,77 @@
1
+ export const HEALTH_PATH = '/_sandcms/health';
2
+ const isRead = (method) => method === 'GET' || method === 'HEAD';
3
+ const noStore = { 'cache-control': 'no-store' };
4
+ /** Lowercase, drop the protocol's default port and a trailing dot: `Example.COM.:443` → `example.com`. */
5
+ export function normalizeHost(host, protocol = 'https:') {
6
+ return host
7
+ .trim()
8
+ .toLowerCase()
9
+ .replace(protocol === 'http:' ? /:80$/ : /:443$/, '')
10
+ .replace(/\.(?=:\d+$|$)/, '');
11
+ }
12
+ /** The robots.txt body when the site is not indexed, otherwise the SEO module's (or null when SEO is off). */
13
+ export function robotsTxt(cms) {
14
+ return cms.options.indexing === false
15
+ ? 'User-agent: *\nDisallow: /\n'
16
+ : (cms.seo?.robots() ?? null);
17
+ }
18
+ /** Adds `X-Robots-Tag: noindex, nofollow` to every response when `indexing` is false. */
19
+ export function applyIndexingHeaders(cms, response) {
20
+ if (cms.options.indexing !== false)
21
+ return response;
22
+ try {
23
+ response.headers.set('x-robots-tag', 'noindex, nofollow');
24
+ return response;
25
+ }
26
+ catch {
27
+ // Immutable headers (e.g. a proxied fetch response).
28
+ const copy = new Response(response.body, response);
29
+ copy.headers.set('x-robots-tag', 'noindex, nofollow');
30
+ return copy;
31
+ }
32
+ }
33
+ /**
34
+ * Handles platform routes before anything else: `GET|HEAD /_sandcms/health` (liveness: the database opens),
35
+ * the canonical-host redirect, and the disallow-all robots.txt of an unindexed site. Returns null otherwise.
36
+ */
37
+ export function platformHandle(cms, event, { dev = process.env.NODE_ENV !== 'production' } = {}) {
38
+ const { method } = event.request, raw = new URL(event.request.url);
39
+ if (raw.pathname === HEALTH_PATH) {
40
+ if (!isRead(method))
41
+ return new Response(null, { status: 405, headers: { allow: 'GET, HEAD', ...noStore } });
42
+ let ok = false;
43
+ try {
44
+ cms.store.sqlite.query('SELECT 1').get();
45
+ ok = true;
46
+ }
47
+ catch {
48
+ // Reported as 503 below.
49
+ }
50
+ return new Response(method === 'HEAD' ? null : JSON.stringify({ status: ok ? 'ok' : 'error' }), {
51
+ status: ok ? 200 : 503,
52
+ headers: { 'content-type': 'application/json', ...noStore }
53
+ });
54
+ }
55
+ // The adapter has already applied HOST_HEADER/PROTOCOL_HEADER to request.url, so a proxy that rewrites
56
+ // Host (and forwards the public one in X-Forwarded-Host) is compared on the public hostname.
57
+ const origin = new URL(cms.options.origin);
58
+ if (!dev &&
59
+ cms.options.canonicalRedirect !== false &&
60
+ normalizeHost(raw.host, origin.protocol) !== normalizeHost(origin.host, origin.protocol))
61
+ return new Response(null, {
62
+ status: 308,
63
+ headers: { location: origin.origin + raw.pathname + raw.search, ...noStore }
64
+ });
65
+ if (cms.options.indexing === false && raw.pathname === '/robots.txt') {
66
+ if (!isRead(method))
67
+ return new Response(null, { status: 405, headers: { allow: 'GET, HEAD' } });
68
+ return new Response(method === 'HEAD' ? null : robotsTxt(cms), {
69
+ headers: {
70
+ 'content-type': 'text/plain; charset=utf-8',
71
+ 'x-robots-tag': 'noindex, nofollow',
72
+ ...noStore
73
+ }
74
+ });
75
+ }
76
+ return null;
77
+ }
@@ -0,0 +1,52 @@
1
+ import { type Store } from '../db/store.js';
2
+ export * from './volume.js';
3
+ export * from './snapshots.js';
4
+ export * from './http.js';
5
+ /** Lease name for the hourly snapshot (leases table). */
6
+ export declare const SNAPSHOT_LEASE = "snapshot";
7
+ export interface PrepareOptions {
8
+ /** Defaults to the database's directory. */
9
+ dataDir?: string;
10
+ /** `definition.config.name`; enables the site-id check. */
11
+ project?: string;
12
+ /** Reads NODE_ENV, SANDCMS_ALLOW_UNMOUNTED_DATA and SANDCMS_SITE_RENAME (default process.env). */
13
+ env?: Record<string, string | undefined>;
14
+ }
15
+ /**
16
+ * Check the data volume before the database is opened or migrated: the new-database mount check and site
17
+ * identity. Returns the data directory.
18
+ */
19
+ export declare function preparePlatform(database: string, options?: PrepareOptions): string;
20
+ /** Create the first admin with a one-time password when the database has no users. */
21
+ export declare function bootstrapAdmin(cms: {
22
+ store: Store;
23
+ }, email: string): Promise<{
24
+ email: string;
25
+ password: string;
26
+ } | null>;
27
+ /** Last successful snapshot and the last snapshot error since this process started. */
28
+ export declare function platformStatus(dataDir: string): {
29
+ lastSnapshot: Date | null;
30
+ lastError: string | null;
31
+ };
32
+ export interface StartOptions {
33
+ dataDir?: string;
34
+ bootstrapEmail?: string;
35
+ env?: Record<string, string | undefined>;
36
+ /** How often to check whether a snapshot is due (default 5 minutes). */
37
+ checkEvery?: number;
38
+ }
39
+ /**
40
+ * Start the server-only platform features for an opened CMS: the site-id check (via preparePlatform),
41
+ * first-admin bootstrap, migration-snapshot pruning, and hourly snapshots in a child process, with a
42
+ * catch-up check right after start (never on the request path). A database lease keeps two servers on one
43
+ * volume (an overlapping deploy) from snapshotting at once. Returns a stop function that clears the timers.
44
+ */
45
+ export declare function startPlatform(cms: {
46
+ store: Store;
47
+ definition: {
48
+ config: {
49
+ name: string;
50
+ };
51
+ };
52
+ }, options?: StartOptions): () => void;
@@ -0,0 +1,98 @@
1
+ // Platform features for a self-hosted site (docs/plans/0.7-self-hosted.md §5). Only the web server uses
2
+ // these; CLI commands never start snapshots. Overlapping deploys may run two servers on one volume:
3
+ // SQLite handles that on a local filesystem, and background work coordinates through database leases.
4
+ import { dirname, resolve } from 'node:path';
5
+ import { createUser } from '../auth.js';
6
+ import { pendingMigrations } from '../db/store.js';
7
+ import { user } from '../db/schema.js';
8
+ import { releaseLease, takeLease } from '../media/runner.js';
9
+ import { assertDataVolume, checkSiteId } from './volume.js';
10
+ import { lastSnapshot, pruneMigrationSnapshots, snapshotIfDue } from './snapshots.js';
11
+ export * from './volume.js';
12
+ export * from './snapshots.js';
13
+ export * from './http.js';
14
+ /** Lease name for the hourly snapshot (leases table). */
15
+ export const SNAPSHOT_LEASE = 'snapshot';
16
+ /**
17
+ * Check the data volume before the database is opened or migrated: the new-database mount check and site
18
+ * identity. Returns the data directory.
19
+ */
20
+ export function preparePlatform(database, options = {}) {
21
+ const dataDir = resolve(options.dataDir ?? dirname(resolve(database))), env = options.env ?? process.env;
22
+ assertDataVolume(resolve(database), dataDir, env);
23
+ if (options.project !== undefined)
24
+ checkSiteId(dataDir, options.project, { rename: env.SANDCMS_SITE_RENAME === 'true' });
25
+ return dataDir;
26
+ }
27
+ /** Create the first admin with a one-time password when the database has no users. */
28
+ export async function bootstrapAdmin(cms, email) {
29
+ if (pendingMigrations(cms.store).length)
30
+ return null;
31
+ if (cms.store.db.select({ id: user.id }).from(user).limit(1).get())
32
+ return null;
33
+ const password = crypto.randomUUID() + 'A!';
34
+ await createUser(cms.store, { email, name: 'Administrator', role: 'admin', password }, 'bootstrap');
35
+ console.info(`SandCMS created the first admin ${email}. One-time password (shown once): ${password}\nSign in at /admin, change it, then remove SANDCMS_BOOTSTRAP_EMAIL.`);
36
+ return { email, password };
37
+ }
38
+ const status = new Map();
39
+ /** Last successful snapshot and the last snapshot error since this process started. */
40
+ export function platformStatus(dataDir) {
41
+ return { lastSnapshot: lastSnapshot(dataDir), lastError: status.get(dataDir)?.lastError ?? null };
42
+ }
43
+ /**
44
+ * Start the server-only platform features for an opened CMS: the site-id check (via preparePlatform),
45
+ * first-admin bootstrap, migration-snapshot pruning, and hourly snapshots in a child process, with a
46
+ * catch-up check right after start (never on the request path). A database lease keeps two servers on one
47
+ * volume (an overlapping deploy) from snapshotting at once. Returns a stop function that clears the timers.
48
+ */
49
+ export function startPlatform(cms, options = {}) {
50
+ const bootstrap = () => options.bootstrapEmail &&
51
+ bootstrapAdmin(cms, options.bootstrapEmail).catch((e) => console.error('SandCMS admin bootstrap failed:', e));
52
+ if (cms.store.path === ':memory:') {
53
+ bootstrap();
54
+ return () => { };
55
+ }
56
+ const database = cms.store.path, dataDir = preparePlatform(database, {
57
+ dataDir: options.dataDir,
58
+ project: cms.definition.config.name,
59
+ env: options.env
60
+ }), state = { lastError: null };
61
+ status.set(dataDir, state);
62
+ bootstrap();
63
+ let running = false, stopped = false;
64
+ const owner = crypto.randomUUID();
65
+ const tick = async () => {
66
+ if (running || stopped)
67
+ return;
68
+ running = true;
69
+ // Ten minutes covers a large VACUUM INTO; an expired lease from a stopped server is simply retaken.
70
+ if (!takeLease(cms.store, SNAPSHOT_LEASE, owner, 10 * 60 * 1000)) {
71
+ running = false;
72
+ return;
73
+ }
74
+ try {
75
+ pruneMigrationSnapshots(database);
76
+ await snapshotIfDue(database, dataDir);
77
+ state.lastError = null;
78
+ }
79
+ catch (e) {
80
+ state.lastError = e instanceof Error ? e.message : String(e);
81
+ console.error('SandCMS snapshot failed:', e);
82
+ }
83
+ finally {
84
+ releaseLease(cms.store, SNAPSHOT_LEASE, owner);
85
+ running = false;
86
+ }
87
+ };
88
+ const first = setTimeout(tick, 0), timer = setInterval(tick, options.checkEvery ?? 5 * 60 * 1000);
89
+ first.unref();
90
+ timer.unref();
91
+ return () => {
92
+ if (stopped)
93
+ return;
94
+ stopped = true;
95
+ clearTimeout(first);
96
+ clearInterval(timer);
97
+ };
98
+ }
@@ -0,0 +1,18 @@
1
+ export declare const SNAPSHOT_INTERVAL: number;
2
+ export declare const KEEP_MIGRATION_SNAPSHOTS = 3;
3
+ export declare function snapshotPaths(dataDir: string): {
4
+ dir: string;
5
+ latest: string;
6
+ previous: string;
7
+ next: string;
8
+ };
9
+ /** Time of the last successful snapshot (its file time), or null when none exists. */
10
+ export declare function lastSnapshot(dataDir: string): Date | null;
11
+ /** Write a verified snapshot in this process, then rotate latest → previous. A failure leaves both untouched. */
12
+ export declare function takeSnapshot(database: string, dataDir: string): string;
13
+ /** Like takeSnapshot, but the copy and its integrity check run in a child process. */
14
+ export declare function takeSnapshotAsync(database: string, dataDir: string): Promise<string>;
15
+ /** Take a snapshot (in a child process) when none exists or the latest is older than SNAPSHOT_INTERVAL. */
16
+ export declare function snapshotIfDue(database: string, dataDir: string, now?: number): Promise<string | null>;
17
+ /** Keep the newest `keep` `<database>.before-migrate-<ms>-<id>.sqlite` snapshots (see db/auto-migrate.ts). */
18
+ export declare function pruneMigrationSnapshots(database: string, keep?: number): string[];
@@ -0,0 +1,110 @@
1
+ // Hourly verified database snapshots inside the data volume (plan D6), so any file-level volume backup
2
+ // contains a consistent database even when the live file is torn.
3
+ import { Database } from 'bun:sqlite';
4
+ import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync } from 'node:fs';
5
+ import { basename, dirname, join } from 'node:path';
6
+ import { backup } from '../../cli/backup.js';
7
+ import { pendingMigrations, SCHEMA_VERSION } from '../db/store.js';
8
+ export const SNAPSHOT_INTERVAL = 60 * 60 * 1000;
9
+ export const KEEP_MIGRATION_SNAPSHOTS = 3;
10
+ export function snapshotPaths(dataDir) {
11
+ const dir = join(dataDir, 'backups');
12
+ return {
13
+ dir,
14
+ latest: join(dir, 'latest.sqlite'),
15
+ previous: join(dir, 'previous.sqlite'),
16
+ next: join(dir, 'next.sqlite')
17
+ };
18
+ }
19
+ /** Time of the last successful snapshot (its file time), or null when none exists. */
20
+ export function lastSnapshot(dataDir) {
21
+ const { latest } = snapshotPaths(dataDir);
22
+ return existsSync(latest) ? statSync(latest).mtime : null;
23
+ }
24
+ function prepare(dataDir) {
25
+ const paths = snapshotPaths(dataDir);
26
+ mkdirSync(paths.dir, { recursive: true, mode: 0o700 });
27
+ // Leftovers of an interrupted run; backup() refuses existing outputs.
28
+ for (const name of readdirSync(paths.dir))
29
+ if (name.startsWith('next.sqlite'))
30
+ rmSync(join(paths.dir, name), { force: true });
31
+ return paths;
32
+ }
33
+ function rotate({ latest, previous }, verified) {
34
+ if (existsSync(latest))
35
+ renameSync(latest, previous);
36
+ renameSync(verified, latest);
37
+ return latest;
38
+ }
39
+ /** Write a verified snapshot in this process, then rotate latest → previous. A failure leaves both untouched. */
40
+ export function takeSnapshot(database, dataDir) {
41
+ const paths = prepare(dataDir);
42
+ backup(database, paths.next);
43
+ return rotate(paths, paths.next);
44
+ }
45
+ // Runs in a child process so VACUUM INTO and the integrity check never block the web server's event loop.
46
+ // It holds the same shared volume guard as backup() (db/store.ts volumeGuard), so restore cannot overlap.
47
+ const child = `
48
+ import { Database } from 'bun:sqlite';
49
+ import { chmodSync } from 'node:fs';
50
+ const { SANDCMS_SNAPSHOT_SOURCE: source, SANDCMS_SNAPSHOT_TARGET: target } = process.env;
51
+ const guard = new Database(source + '.guard.sqlite');
52
+ guard.exec('PRAGMA busy_timeout=1000; CREATE TABLE IF NOT EXISTS guard (id INTEGER PRIMARY KEY); BEGIN');
53
+ guard.query('SELECT * FROM guard').all();
54
+ const db = new Database(source);
55
+ db.exec('PRAGMA busy_timeout=5000');
56
+ db.query('VACUUM INTO ?').run(target);
57
+ db.close();
58
+ guard.close();
59
+ chmodSync(target, 0o600);
60
+ const copy = new Database(target, { readonly: true });
61
+ if (copy.query('PRAGMA integrity_check').get().integrity_check !== 'ok') throw new Error('Snapshot failed integrity check');
62
+ if (copy.query('PRAGMA foreign_key_check').all().length) throw new Error('Snapshot contains invalid references');
63
+ copy.close();
64
+ `;
65
+ /** Like takeSnapshot, but the copy and its integrity check run in a child process. */
66
+ export async function takeSnapshotAsync(database, dataDir) {
67
+ const paths = prepare(dataDir), temp = `${paths.next}.tmp-${crypto.randomUUID()}`;
68
+ try {
69
+ const proc = Bun.spawn([process.execPath, '-e', child], {
70
+ env: { ...process.env, SANDCMS_SNAPSHOT_SOURCE: database, SANDCMS_SNAPSHOT_TARGET: temp },
71
+ stdout: 'ignore',
72
+ stderr: 'pipe'
73
+ });
74
+ const [stderr, code] = await Promise.all([new Response(proc.stderr).text(), proc.exited]);
75
+ if (code)
76
+ throw new Error(`Snapshot process failed: ${stderr.trim()}`);
77
+ const copy = new Database(temp, { readonly: true });
78
+ try {
79
+ const { user_version } = copy.query('PRAGMA user_version').get();
80
+ if (user_version < 1 || user_version > SCHEMA_VERSION)
81
+ throw new Error('Incompatible snapshot schema');
82
+ pendingMigrations({ sqlite: copy }); // migration names and hashes
83
+ }
84
+ finally {
85
+ copy.close();
86
+ }
87
+ return rotate(paths, temp);
88
+ }
89
+ finally {
90
+ rmSync(temp, { force: true });
91
+ }
92
+ }
93
+ /** Take a snapshot (in a child process) when none exists or the latest is older than SNAPSHOT_INTERVAL. */
94
+ export async function snapshotIfDue(database, dataDir, now = Date.now()) {
95
+ const last = lastSnapshot(dataDir);
96
+ return last && now - last.getTime() < SNAPSHOT_INTERVAL
97
+ ? null
98
+ : takeSnapshotAsync(database, dataDir);
99
+ }
100
+ /** Keep the newest `keep` `<database>.before-migrate-<ms>-<id>.sqlite` snapshots (see db/auto-migrate.ts). */
101
+ export function pruneMigrationSnapshots(database, keep = KEEP_MIGRATION_SNAPSHOTS) {
102
+ const prefix = basename(database) + '.before-migrate-', dir = dirname(database);
103
+ const old = readdirSync(dir)
104
+ .filter((name) => name.startsWith(prefix) && /^\d+-[^.]+\.sqlite$/.test(name.slice(prefix.length)))
105
+ .sort((a, b) => parseInt(b.slice(prefix.length)) - parseInt(a.slice(prefix.length)))
106
+ .slice(keep);
107
+ for (const name of old)
108
+ rmSync(join(dir, name), { force: true });
109
+ return old;
110
+ }
@@ -0,0 +1,20 @@
1
+ /** True when `dir` is a mount point: a different device than its parent, or listed in mountinfo (bind mounts). */
2
+ export declare function isMountPoint(dir: string): boolean;
3
+ /** True when `dir` or one of its parents, other than `/`, is a mount point (e.g. /data for /data/db). */
4
+ export declare function onMountedVolume(dir: string, isMount?: typeof isMountPoint): boolean;
5
+ /**
6
+ * In production, refuse to create a new database outside a mounted volume: the data would vanish with the
7
+ * container. `SANDCMS_ALLOW_UNMOUNTED_DATA=true` overrides this for hosts without container volumes.
8
+ */
9
+ export declare function assertDataVolume(database: string, dataDir: string, env?: Record<string, string | undefined>, isMount?: typeof isMountPoint): void;
10
+ export interface SiteId {
11
+ id: string;
12
+ project: string;
13
+ }
14
+ /**
15
+ * Write `<dataDir>/site-id` on first start; afterwards refuse a volume that belongs to another project.
16
+ * With `rename` (SANDCMS_SITE_RENAME=true) a renamed project takes over the volume, keeping its site ID.
17
+ */
18
+ export declare function checkSiteId(dataDir: string, project: string, { rename }?: {
19
+ rename?: boolean | undefined;
20
+ }): SiteId;
@@ -0,0 +1,60 @@
1
+ // Data-volume protections (docs/plans/0.7-self-hosted.md §5): one site per volume, data on a mounted volume.
2
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ const unescapeMount = (path) => path.replace(/\\([0-7]{3})/g, (_, octal) => String.fromCharCode(parseInt(octal, 8)));
5
+ /** True when `dir` is a mount point: a different device than its parent, or listed in mountinfo (bind mounts). */
6
+ export function isMountPoint(dir) {
7
+ const real = realpathSync(dir);
8
+ if (real === dirname(real) || statSync(real).dev !== statSync(dirname(real)).dev)
9
+ return true;
10
+ try {
11
+ return readFileSync('/proc/self/mountinfo', 'utf8')
12
+ .split('\n')
13
+ .some((line) => line && unescapeMount(line.split(' ')[4] ?? '') === real);
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ /** True when `dir` or one of its parents, other than `/`, is a mount point (e.g. /data for /data/db). */
20
+ export function onMountedVolume(dir, isMount = isMountPoint) {
21
+ for (let current = realpathSync(dir); current !== dirname(current); current = dirname(current))
22
+ if (isMount(current))
23
+ return true;
24
+ return false;
25
+ }
26
+ /**
27
+ * In production, refuse to create a new database outside a mounted volume: the data would vanish with the
28
+ * container. `SANDCMS_ALLOW_UNMOUNTED_DATA=true` overrides this for hosts without container volumes.
29
+ */
30
+ export function assertDataVolume(database, dataDir, env = process.env, isMount = isMountPoint) {
31
+ if (env.NODE_ENV !== 'production' || env.SANDCMS_ALLOW_UNMOUNTED_DATA === 'true')
32
+ return;
33
+ if (existsSync(database) && statSync(database).size > 0)
34
+ return;
35
+ if (!onMountedVolume(dataDir, isMount))
36
+ throw new Error(`Refusing to create a new database in ${dataDir}: it is not on a mounted volume, so content would be lost when the container is replaced. Mount a persistent volume there (e.g. at /data), or set SANDCMS_ALLOW_UNMOUNTED_DATA=true if this directory is persistent.`);
37
+ }
38
+ function writeSiteId(file, site) {
39
+ const temp = `${file}.tmp-${process.pid}`;
40
+ writeFileSync(temp, JSON.stringify(site) + '\n', { mode: 0o600 });
41
+ renameSync(temp, file);
42
+ return site;
43
+ }
44
+ /**
45
+ * Write `<dataDir>/site-id` on first start; afterwards refuse a volume that belongs to another project.
46
+ * With `rename` (SANDCMS_SITE_RENAME=true) a renamed project takes over the volume, keeping its site ID.
47
+ */
48
+ export function checkSiteId(dataDir, project, { rename = false } = {}) {
49
+ const file = join(dataDir, 'site-id');
50
+ mkdirSync(dataDir, { recursive: true, mode: 0o700 });
51
+ if (!existsSync(file))
52
+ return writeSiteId(file, { id: crypto.randomUUID(), project });
53
+ const site = JSON.parse(readFileSync(file, 'utf8'));
54
+ if (site.project === project)
55
+ return site;
56
+ if (!rename)
57
+ throw new Error(`The data volume at ${dataDir} belongs to project ${JSON.stringify(site.project)} (site ${site.id}), not ${JSON.stringify(project)}. Each site needs its own volume; check the volume mount. If this project was renamed, start once with SANDCMS_SITE_RENAME=true, then remove it.`);
58
+ console.warn(`SandCMS site ${site.id} renamed from ${JSON.stringify(site.project)} to ${JSON.stringify(project)} (SANDCMS_SITE_RENAME). Remove SANDCMS_SITE_RENAME now.`);
59
+ return writeSiteId(file, { id: site.id, project });
60
+ }
@@ -1,5 +1 @@
1
- export declare function sanitizeSvg(input: string): string;
2
- export declare function svgDimensions(svg: string): {
3
- width: number;
4
- height: number;
5
- };
1
+ export { sanitizeSvg, svgDimensions } from '../server/media/svg.js';
@@ -1,142 +1,2 @@
1
- import { SaxesParser } from 'saxes';
2
- const elements = new Set([
3
- 'svg',
4
- 'g',
5
- 'defs',
6
- 'path',
7
- 'rect',
8
- 'circle',
9
- 'ellipse',
10
- 'line',
11
- 'polyline',
12
- 'polygon',
13
- 'text',
14
- 'tspan',
15
- 'title',
16
- 'desc',
17
- 'linearGradient',
18
- 'radialGradient',
19
- 'stop',
20
- 'clipPath',
21
- 'mask',
22
- 'use',
23
- 'symbol'
24
- ]);
25
- const attributes = new Set([
26
- 'id',
27
- 'viewBox',
28
- 'width',
29
- 'height',
30
- 'x',
31
- 'y',
32
- 'x1',
33
- 'x2',
34
- 'y1',
35
- 'y2',
36
- 'cx',
37
- 'cy',
38
- 'r',
39
- 'rx',
40
- 'ry',
41
- 'd',
42
- 'points',
43
- 'fill',
44
- 'fill-rule',
45
- 'fill-opacity',
46
- 'stroke',
47
- 'stroke-width',
48
- 'stroke-linecap',
49
- 'stroke-linejoin',
50
- 'stroke-dasharray',
51
- 'stroke-dashoffset',
52
- 'stroke-opacity',
53
- 'opacity',
54
- 'transform',
55
- 'gradientTransform',
56
- 'gradientUnits',
57
- 'offset',
58
- 'stop-color',
59
- 'stop-opacity',
60
- 'clip-path',
61
- 'clip-rule',
62
- 'mask',
63
- 'preserveAspectRatio',
64
- 'font-family',
65
- 'font-size',
66
- 'font-weight',
67
- 'text-anchor',
68
- 'dx',
69
- 'dy',
70
- 'href'
71
- ]);
72
- const escape = (s) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' })[c]);
73
- export function sanitizeSvg(input) {
74
- if (new TextEncoder().encode(input).length > 1_000_000)
75
- throw new Error('SVG limit is 1 MB');
76
- let result = '', depth = 0, skip = 0, count = 0, root = false;
77
- const parser = new SaxesParser({ xmlns: true });
78
- parser.on('doctype', () => {
79
- throw new Error('SVG document types and entities are not allowed');
80
- });
81
- parser.on('error', (e) => {
82
- throw e;
83
- });
84
- parser.on('opentag', (tag) => {
85
- depth++;
86
- if (depth > 64 || ++count > 10000)
87
- throw new Error('SVG is too complex');
88
- if (depth === 1) {
89
- if (tag.local !== 'svg' || tag.uri !== 'http://www.w3.org/2000/svg')
90
- throw new Error('Expected an SVG root and namespace');
91
- root = true;
92
- }
93
- if (skip || !elements.has(tag.local) || tag.uri !== 'http://www.w3.org/2000/svg') {
94
- skip++;
95
- return;
96
- }
97
- result += '<' + tag.local;
98
- if (depth === 1)
99
- result += ' xmlns="http://www.w3.org/2000/svg"';
100
- for (const attr of Object.values(tag.attributes)) {
101
- if (!attributes.has(attr.name) || attr.prefix || /[<>\u0000-\u001f]/.test(attr.value))
102
- continue;
103
- if (attr.name === 'href' && !/^#[a-zA-Z_][\w:.-]*$/.test(attr.value))
104
- continue;
105
- if (/url\s*\(/i.test(attr.value) && !/^url\(#[a-zA-Z_][\w:.-]*\)$/.test(attr.value))
106
- continue;
107
- if (/(?:javascript|data|https?):|\/\//i.test(attr.value))
108
- continue;
109
- result += ` ${attr.name}="${escape(attr.value)}"`;
110
- }
111
- result += '>';
112
- });
113
- parser.on('text', (text) => {
114
- if (!skip)
115
- result += escape(text);
116
- });
117
- parser.on('cdata', (text) => {
118
- if (!skip)
119
- result += escape(text);
120
- });
121
- parser.on('closetag', (tag) => {
122
- if (skip)
123
- skip--;
124
- else
125
- result += `</${tag.local}>`;
126
- depth--;
127
- });
128
- parser.write(input).close();
129
- if (!root)
130
- throw new Error('Empty SVG');
131
- return result;
132
- }
133
- export function svgDimensions(svg) {
134
- const root = /<svg\b[^>]*>/.exec(svg)?.[0] ?? '';
135
- const viewBox = /viewBox="([^"]+)"/.exec(root)?.[1].trim().split(/[ ,]+/).map(Number);
136
- const width = viewBox?.[2] ?? parseFloat(/\bwidth="([^"]+)"/.exec(root)?.[1] ?? '300');
137
- const height = viewBox?.[3] ?? parseFloat(/\bheight="([^"]+)"/.exec(root)?.[1] ?? '150');
138
- return {
139
- width: Number.isFinite(width) && width > 0 ? Math.round(width) : 300,
140
- height: Number.isFinite(height) && height > 0 ? Math.round(height) : 150
141
- };
142
- }
1
+ // Moved to the server media module in 0.7.0; the deprecated Worker keeps importing it from here.
2
+ export { sanitizeSvg, svgDimensions } from '../server/media/svg.js';
@@ -1,5 +1,7 @@
1
1
  # Local acceptance evidence
2
2
 
3
+ 0.7.0 note: the evidence below predates the move from Cloudflare to local media and was not rerun for it. 0.7.0 replaces the Worker checks with local processing, chunked upload, import and container checks; see the [0.7.0 test plan](plans/0.7-self-hosted.md#8-testing).
4
+
3
5
  Verification date: **26 September 2026** for type checking, packed installation checks, and the 31 core tests, including fresh database initialization, incompatible-baseline rejection, and migration replacement recovery. Browser, visual, doctor, and container evidence below was not rerun during this review. Scope: local implementation and verification, as requested. No Dokploy project, deployed Cloudflare staging resources, or private npm registry was used. No remote deployment or package publication was performed.
4
6
 
5
7
  ## Reproduce
@@ -14,7 +16,7 @@ bun run test:e2e
14
16
  bun run test:package
15
17
  ```
16
18
 
17
- Use Bun 1.4.0 and Node 26.8.1. Stop the development server before building. Browser tests start the production Bun output on port 5411 and local Wrangler on 8788, with temporary databases, R2 state, and fixture accounts. They clean up their resources. Test credentials are fixture-only.
19
+ Use Bun 1.4.4; Node is not needed. Stop the development server before building. Browser tests start the production Bun output on port 5411 with temporary databases, media directories and fixture accounts. They clean up their resources. Test credentials are fixture-only.
18
20
 
19
21
  ## Results
20
22
 
@@ -26,7 +28,7 @@ Use Bun 1.4.0 and Node 26.8.1. Stop the development server before building. Brow
26
28
  | Packed installation | The actual archive installs, type checks, and builds in a fresh site without Tailwind and in an existing site with a public route and JavaScript hook. Hook composition follows the generated report; reruns and customized upgrade checks preserve developer files. |
27
29
  | Visual and keyboard review | Desktop and 390px mobile login, overview, editor, navigation, media, dialogs, and galleries inspected. Shadcn selects support keyboard selection, clearing, persistence, and nested dialogs. Unsaved-dialog focus, Escape, and cancel restoration pass. Browser assertions check horizontal overflow. |
28
30
  | Local doctor | Bun pin, adapter/start command, integration routes/hook, YAML, writable SQLite, migrations, environment presence, and authenticated Worker protocol pass. |
29
- | Railpack image | Railpack 0.40.0 builds the application with Bun 1.4.0 and the pinned adapter. A real Docker named volume proves production bootstrap, authenticated editing, public rendering, persistence across container replacement, a live snapshot, refusal of in-use restore across containers, and successful offline restore. |
31
+ | Railpack image | Railpack 0.40.0 builds the application with Bun 1.4.4 and the pinned adapter. A real Docker named volume proves production bootstrap, authenticated editing, public rendering, persistence across container replacement, a live snapshot, refusal of in-use restore across containers, and successful offline restore. |
30
32
 
31
33
  Blueprints support validated Lucide icon names with defaults for every kind. Projects uses `icon: image`. Custom and default icons render in the sidebar, and the complete icon catalogue stays on the server. Desktop and mobile review also confirms the profile initial is centered after narrowing the role-label CSS selector.
32
34
 
@@ -52,7 +54,7 @@ The drill owns and removes its temporary containers and volume. It uses localhos
52
54
  ## External release checks still required
53
55
 
54
56
  1. **Dokploy:** deploy the Railpack image with HTTPS, the production volume, runtime secrets, and the actual reverse proxy configuration. Bootstrap against that mounted database, publish content, replace the container, verify session/cookie and proxy behavior, and perform the documented backup/offline-restore drill. The local Docker proof covers the application mechanics; Dokploy's operator access, mounting, restart policy, and routing remain unverified.
55
- 2. **Cloudflare staging:** complete the [staging and CDN verification](cloudflare.md#staging-verification) with authorized staging resources. This remains an external release check; local tests do not prove deployed cache behavior or image quality.
57
+ 2. **R2 import and CDN:** run `sandcms media import-r2` against a real 0.6 site's Worker and bucket, and, where a CDN is used, verify the [cache rules](cloudflare.md#optional-cdn-caching) on a staging hostname. Local tests use a fake Worker and do not prove deployed cache behavior.
56
58
  3. **Private npm:** publish `sandcms` with restricted access from an authorized organization account, and prove an authenticated pinned install in a clean CI environment. Validate secret handling in the real build host. Local archive installation is complete; registry authentication and publication remain unverified.
57
59
 
58
- The cloud provisioning implementation is present, but its live acceptance is pending. These checks are release gates, not prerequisites for continuing local development.
60
+ Live acceptance on a deployed host is pending. These checks are release gates, not prerequisites for continuing local development.