sandcms 0.7.0 → 0.8.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 (111) hide show
  1. package/README.md +4 -4
  2. package/dist/admin/Admin.svelte +7 -5
  3. package/dist/admin/AssetAttachment.svelte +8 -3
  4. package/dist/admin/AssetAttachment.svelte.d.ts +3 -0
  5. package/dist/admin/Editor.svelte +5 -9
  6. package/dist/admin/Fields.svelte +2 -1
  7. package/dist/admin/Gallery.svelte +221 -76
  8. package/dist/admin/Inbox.svelte +3 -2
  9. package/dist/admin/MediaPicker.svelte +36 -20
  10. package/dist/admin/Navigation.svelte +13 -2
  11. package/dist/admin/Pages.svelte +195 -0
  12. package/dist/admin/Pages.svelte.d.ts +7 -0
  13. package/dist/admin/Shell.svelte +27 -5
  14. package/dist/admin/SortableList.svelte +82 -61
  15. package/dist/admin/SortableList.svelte.d.ts +3 -1
  16. package/dist/admin/Users.svelte +8 -3
  17. package/dist/admin/generated/admin.css +300 -20
  18. package/dist/admin/navigation.d.ts +9 -0
  19. package/dist/admin/navigation.js +20 -1
  20. package/dist/admin/types.d.ts +1 -0
  21. package/dist/blueprints/labels.d.ts +6 -0
  22. package/dist/blueprints/labels.js +14 -0
  23. package/dist/blueprints/load.js +11 -2
  24. package/dist/blueprints/types.d.ts +2 -2
  25. package/dist/cli/admin.d.ts +39 -0
  26. package/dist/cli/admin.js +95 -0
  27. package/dist/cli/backup.js +4 -4
  28. package/dist/cli/doctor.d.ts +8 -1
  29. package/dist/cli/doctor.js +19 -9
  30. package/dist/cli/email-test.d.ts +3 -0
  31. package/dist/cli/email-test.js +20 -0
  32. package/dist/cli/files.js +2 -1
  33. package/dist/cli/index.js +373 -135
  34. package/dist/cli/rebaseline.d.ts +10 -0
  35. package/dist/cli/rebaseline.js +117 -0
  36. package/dist/cli/upgrade.js +17 -9
  37. package/dist/env.d.ts +0 -8
  38. package/dist/env.js +0 -8
  39. package/dist/notification-fields.js +2 -1
  40. package/dist/server/admin-load.d.ts +72 -0
  41. package/dist/server/admin-load.js +20 -0
  42. package/dist/server/api-keys.d.ts +96 -0
  43. package/dist/server/api-keys.js +115 -0
  44. package/dist/server/api.js +16 -61
  45. package/dist/server/cms.d.ts +0 -5
  46. package/dist/server/cms.js +4 -3
  47. package/dist/server/db/auto-migrate.d.ts +0 -4
  48. package/dist/server/db/auto-migrate.js +12 -3
  49. package/dist/server/db/legacy.d.ts +13 -0
  50. package/dist/server/db/legacy.js +60 -0
  51. package/dist/server/db/migration-data.js +2 -38
  52. package/dist/server/db/migrations/{0000_foundation.sql → 0000_baseline.sql} +120 -4
  53. package/dist/server/db/migrations/meta/0000_snapshot.json +578 -3
  54. package/dist/server/db/migrations/meta/_journal.json +2 -65
  55. package/dist/server/db/schema.js +8 -6
  56. package/dist/server/db/store.d.ts +25 -2
  57. package/dist/server/db/store.js +90 -26
  58. package/dist/server/forms.js +2 -1
  59. package/dist/server/media/runner.d.ts +1 -1
  60. package/dist/server/media/runner.js +1 -1
  61. package/dist/server/media/service.d.ts +0 -4
  62. package/dist/server/media/service.js +0 -2
  63. package/dist/server/media/verify.d.ts +28 -0
  64. package/dist/server/media/verify.js +94 -2
  65. package/dist/server/platform/snapshots.js +3 -3
  66. package/docs/acceptance.md +2 -2
  67. package/docs/api.md +15 -1
  68. package/docs/cloudflare.md +9 -41
  69. package/docs/content.md +18 -3
  70. package/docs/deployment.md +97 -34
  71. package/docs/email.md +6 -0
  72. package/docs/forms.md +1 -1
  73. package/docs/media.md +10 -1
  74. package/docs/package.md +4 -4
  75. package/docs/releases.md +21 -1
  76. package/docs/upgrades.md +41 -7
  77. package/package.json +4 -10
  78. package/templates/Dockerfile +6 -2
  79. package/templates/integration.ts +10 -5
  80. package/templates/openship.json +9 -0
  81. package/templates/sandcms/config.yaml +1 -0
  82. package/dist/server/db/migrations/0001_independent_password_resets.sql +0 -3
  83. package/dist/server/db/migrations/0002_email_failure_reason.sql +0 -1
  84. package/dist/server/db/migrations/0003_direct_r2_uploads.sql +0 -10
  85. package/dist/server/db/migrations/0004_agent_api_keys.sql +0 -38
  86. package/dist/server/db/migrations/0005_api_retention_and_pagination.sql +0 -3
  87. package/dist/server/db/migrations/0006_durable_media_deletion.sql +0 -7
  88. package/dist/server/db/migrations/0007_content_and_job_indexes.sql +0 -2
  89. package/dist/server/db/migrations/0008_search_text_cache.sql +0 -45
  90. package/dist/server/db/migrations/0009_local_media.sql +0 -9
  91. package/dist/server/db/migrations/meta/0001_snapshot.json +0 -1197
  92. package/dist/server/db/migrations/meta/0002_snapshot.json +0 -1204
  93. package/dist/server/db/migrations/meta/0003_snapshot.json +0 -1281
  94. package/dist/server/db/migrations/meta/0004_snapshot.json +0 -1546
  95. package/dist/server/db/migrations/meta/0005_snapshot.json +0 -1572
  96. package/dist/server/db/migrations/meta/0006_snapshot.json +0 -1627
  97. package/dist/server/db/migrations/meta/0007_snapshot.json +0 -1643
  98. package/dist/server/db/migrations/meta/0008_snapshot.json +0 -1711
  99. package/dist/server/db/migrations/meta/0009_snapshot.json +0 -1763
  100. package/dist/server/media/import-r2.d.ts +0 -56
  101. package/dist/server/media/import-r2.js +0 -342
  102. package/dist/worker/index.d.ts +0 -10
  103. package/dist/worker/index.js +0 -460
  104. package/dist/worker/local.d.ts +0 -5
  105. package/dist/worker/local.js +0 -57
  106. package/dist/worker/source.d.ts +0 -2
  107. package/dist/worker/source.js +0 -31
  108. package/dist/worker/svg.d.ts +0 -1
  109. package/dist/worker/svg.js +0 -2
  110. package/dist/worker/uploads.d.ts +0 -22
  111. package/dist/worker/uploads.js +0 -48
@@ -0,0 +1,117 @@
1
+ import { Database } from 'bun:sqlite';
2
+ import { chmodSync, existsSync, renameSync, unlinkSync } from 'node:fs';
3
+ import { applyMigrations, databasePath, schemaHistory, volumeGuard } from '../server/db/store.js';
4
+ import { legacyHistory } from '../server/db/legacy.js';
5
+ // Derived rows: the media insert trigger recreates them while media is copied.
6
+ const DERIVED = new Set(['media_document_links']);
7
+ const quote = (name) => `"${name.replaceAll('"', '""')}"`;
8
+ /**
9
+ * Convert a SandCMS 0.7.x database (the retired 0000–0009 migration history) into a fresh database built
10
+ * from the 0.8.0 baseline, copying every row. Media files are untouched. The website must be stopped; a
11
+ * verified safety copy of the old database is kept next to it.
12
+ */
13
+ export function rebaseline(database, confirmed = false) {
14
+ const target = databasePath(database);
15
+ if (!confirmed)
16
+ throw new Error(`Rebaseline requires explicit confirmation for ${target}`);
17
+ if (!existsSync(target))
18
+ throw new Error('Database does not exist');
19
+ const guard = volumeGuard(target, true);
20
+ const safety = `${target}.before-rebaseline-${Date.now()}.sqlite`, staged = `${target}.rebaseline-${crypto.randomUUID()}`;
21
+ try {
22
+ const legacy = new Database(target);
23
+ try {
24
+ legacy.exec('PRAGMA busy_timeout=0; PRAGMA wal_checkpoint(TRUNCATE);');
25
+ const state = legacyHistory(legacy);
26
+ if (state !== 'complete')
27
+ throw new Error(state === 'outdated'
28
+ ? 'Database was created by SandCMS 0.6 or older. Upgrade it with SandCMS 0.7.x first, then run sandcms rebaseline.'
29
+ : 'Database does not have the SandCMS 0.7 migration history; nothing to rebaseline.');
30
+ assertHealthy(legacy, 'Database');
31
+ legacy.query('VACUUM INTO ?').run(safety);
32
+ chmodSync(safety, 0o600);
33
+ }
34
+ finally {
35
+ legacy.close();
36
+ }
37
+ const copied = copyInto(staged, safety);
38
+ for (const suffix of ['-wal', '-shm'])
39
+ if (existsSync(target + suffix))
40
+ unlinkSync(target + suffix);
41
+ renameSync(staged, target);
42
+ return { target, safety, copied };
43
+ }
44
+ catch (cause) {
45
+ if (existsSync(staged))
46
+ unlinkSync(staged);
47
+ throw cause;
48
+ }
49
+ finally {
50
+ guard?.close();
51
+ }
52
+ }
53
+ function assertHealthy(db, label) {
54
+ const integrity = db.query('PRAGMA integrity_check').get();
55
+ if (integrity.integrity_check !== 'ok')
56
+ throw new Error(`${label} failed integrity check`);
57
+ if (db.query('PRAGMA foreign_key_check').all().length)
58
+ throw new Error(`${label} contains invalid references`);
59
+ }
60
+ function tables(db, schema) {
61
+ return db
62
+ .query(`SELECT name FROM ${schema}.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name != 'schema_migrations' ORDER BY name`)
63
+ .all().map((t) => t.name);
64
+ }
65
+ function columns(db, schema, table) {
66
+ return db.query(`PRAGMA ${schema}.table_info(${quote(table)})`).all().map((c) => c.name);
67
+ }
68
+ function count(db, sql) {
69
+ return db.query(`SELECT count(*) AS n FROM (${sql})`).get().n;
70
+ }
71
+ /** Build the baseline in `staged`, copy every legacy row, verify, and return row counts per table. */
72
+ function copyInto(staged, source) {
73
+ const db = new Database(staged, { create: true });
74
+ try {
75
+ chmodSync(staged, 0o600);
76
+ applyMigrations({ sqlite: db });
77
+ db.exec('PRAGMA foreign_keys=OFF');
78
+ db.query('ATTACH DATABASE ? AS legacy').run(source);
79
+ const copied = {};
80
+ db.transaction(() => {
81
+ const current = tables(db, 'main');
82
+ for (const table of tables(db, 'legacy'))
83
+ if (!current.includes(table) && count(db, `SELECT 1 FROM legacy.${quote(table)}`))
84
+ throw new Error(`Table ${table} has rows but no place in the new schema`);
85
+ for (const table of current) {
86
+ if (!tables(db, 'legacy').includes(table))
87
+ continue;
88
+ const target = columns(db, 'main', table), source = columns(db, 'legacy', table);
89
+ const lost = source.filter((c) => !target.includes(c));
90
+ if (lost.length)
91
+ throw new Error(`Columns ${table}.${lost.join(', ')} have no place`);
92
+ const list = source.map(quote).join(', '), name = quote(table);
93
+ db.exec(`INSERT ${DERIVED.has(table) ? 'OR IGNORE ' : ''}INTO main.${name} (${list}) SELECT ${list} FROM legacy.${name}`);
94
+ const legacyRows = `SELECT ${list} FROM legacy.${name}`, newRows = `SELECT ${list} FROM main.${name}`;
95
+ if (count(db, `${legacyRows} EXCEPT ${newRows}`))
96
+ throw new Error(`Rows of ${table} were not copied exactly`);
97
+ if (!DERIVED.has(table) && count(db, `${newRows} EXCEPT ${legacyRows}`))
98
+ throw new Error(`Rows of ${table} differ after copying`);
99
+ copied[table] = count(db, `SELECT 1 FROM main.${name}`);
100
+ if (!DERIVED.has(table) && copied[table] !== count(db, legacyRows))
101
+ throw new Error(`Row count of ${table} differs after copying`);
102
+ }
103
+ if (db.query('PRAGMA main.foreign_key_check').all().length)
104
+ throw new Error('Copied rows contain invalid references');
105
+ })();
106
+ db.exec('DETACH DATABASE legacy');
107
+ db.exec('PRAGMA foreign_keys=ON');
108
+ assertHealthy(db, 'Rebaselined database');
109
+ const history = schemaHistory(db);
110
+ if (history.pending.length || history.ahead.length)
111
+ throw new Error('Rebaselined database is not at the current schema');
112
+ return copied;
113
+ }
114
+ finally {
115
+ db.close();
116
+ }
117
+ }
@@ -14,12 +14,12 @@ export async function upgrade(root, check = false, database) {
14
14
  `Installed integration: ${manifest.version}. Blueprints are valid.`,
15
15
  'The website now validates SandCMS environment variables on start through src/env.ts. Ensure SANDCMS_ORIGIN and a 32-character SANDCMS_SECRET are set in every environment. See docs/upgrades.md#validated-environment-variables.',
16
16
  'Include @better-auth/core in ssr.noExternal in your Vite configuration, then rebuild and restart the website to fix concurrent image preview failures. Developer-owned configuration is preserved. See docs/deployment.md#server-build-configuration.',
17
- 'From 0.5.0, database changes use incremental migrations. Back up with the installed package before updating, then run sandcms migrate. Changed pre-0.5.0 baselines still require a fresh database. See docs/upgrades.md.',
17
+ '0.8.0 replaces the 0.7 migration history with a new baseline. A 0.7.x database is converted once with sandcms rebaseline while the site is stopped; older databases are first upgraded with 0.7.x. See docs/upgrades.md#080-upgrade-checklist.',
18
18
  '0.7.0 stores media on the site volume instead of Cloudflare. Before deploying: check that no uploads are pending, take a backup, and make sure the volume has free space of at least 3 × the current media. See docs/upgrades.md.',
19
19
  'Confirm cmsHandle runs first in sequence() in src/hooks.server.ts: it enforces request size limits and handles health checks, host redirects, uploads and media before other hooks.',
20
20
  'Add sharp to ssr.external next to bun:sqlite in your Vite configuration. Remove paths.origin: the site now derives its origin from the request and redirects other hostnames to SANDCMS_ORIGIN.',
21
- 'Set BODY_SIZE_LIMIT=10M. Overlapping (zero-downtime) and stop-then-start deploys both work. The generated Dockerfile includes a HEALTHCHECK on /_sandcms/health; railpack.json remains supported.',
22
- 'Deploy with SANDCMS_WORKER_URL and SANDCMS_WORKER_TOKEN still set, run sandcms media import-r2 once, check the site, then remove the Worker variables. The Worker and its R2 bucket can be deleted after a restore from backup has been verified to contain the originals.'
21
+ 'Set BODY_SIZE_LIMIT=10M. Deploys overlap: the new container migrates on its first health check and takes traffic once healthy. OpenShip, Dokploy and Coolify each need a few settings; see docs/deployment.md#platform-settings. railpack.json remains supported.',
22
+ '0.8.0 removes the Cloudflare Worker support deprecated in 0.7.0: sandcms media import-r2, the sandcms/worker exports, the createCMS workerUrl and workerToken options and the SANDCMS_WORKER_URL and SANDCMS_WORKER_TOKEN variables. Finish the R2 import with 0.7.x before upgrading. media.workerUrl in config.yaml is ignored and can be removed.'
23
23
  ];
24
24
  const vite = ['vite.config.ts', 'vite.config.js']
25
25
  .map((file) => join(root, file))
@@ -33,14 +33,22 @@ export async function upgrade(root, check = false, database) {
33
33
  if (!plan.some((p) => p.path === 'Dockerfile'))
34
34
  notes.push(`A Dockerfile with a HEALTHCHECK on /_sandcms/health is available at node_modules/${PACKAGE_NAME}/templates/Dockerfile. It was not added because this site builds with Railpack, and hosts that detect a Dockerfile switch builders. To switch, copy it to the project root; later upgrades then keep it current.`);
35
35
  if (plan.some((p) => /^src\/lib\/server\/sandcms\/index\.[jt]s$/.test(p.path) && p.status === 'conflict'))
36
- notes.push('Your src/lib/server/sandcms/index.ts is customized. Pass server: true to createCMS and call media.start() before storing the instance (close and rethrow on failure), so the data-volume lock is taken before the database opens. Pass SANDCMS_CANONICAL_REDIRECT as canonicalRedirect. See the proposed diff below.');
36
+ notes.push('Your src/lib/server/sandcms/index.ts is customized. Pass server: true to createCMS and call media.start() before storing the instance (close and rethrow on failure), so the data-volume lock is taken before the database opens. Pass SANDCMS_CANONICAL_REDIRECT as canonicalRedirect, and add the sveltekit:shutdown listener that stops background work, closes the CMS and exits. See the proposed diff below.');
37
+ if (['src/lib/server/sandcms/index.ts', 'src/lib/server/sandcms/index.js'].some((file) => existsSync(join(root, file)) &&
38
+ /SANDCMS_WORKER_|workerUrl|workerToken/.test(readFileSync(join(root, file), 'utf8'))))
39
+ notes.push('Your src/lib/server/sandcms/index file still passes workerUrl or workerToken, or reads SANDCMS_WORKER_* variables. Remove those lines: 0.8.0 no longer declares the variables, so the build fails while they are read.');
37
40
  if (existsSync(join(root, 'sandcms/worker')))
38
- notes.push('sandcms/worker/ is no longer used by SandCMS. Keep it until sandcms media import-r2 has been verified, then remove it together with the Cloudflare Worker.');
41
+ notes.push('sandcms/worker/ is no longer used by SandCMS and the sandcms/worker exports it imports are gone. Remove it, together with the Cloudflare Worker, once the R2 import has been verified with 0.7.x.');
39
42
  if (database)
40
- notes.push('Pending DB migrations: ' +
41
- (inspectMigrations(database)
42
- .map((m) => m.name)
43
- .join(', ') || 'none'));
43
+ try {
44
+ notes.push('Pending DB migrations: ' +
45
+ (inspectMigrations(database)
46
+ .map((m) => m.name)
47
+ .join(', ') || 'none'));
48
+ }
49
+ catch (cause) {
50
+ notes.push(`Database: ${cause instanceof Error ? cause.message : String(cause)}`);
51
+ }
44
52
  const conflicts = plan.filter((p) => p.status === 'conflict'), accepted = new Set();
45
53
  const diffs = conflicts.map((item) => createTwoFilesPatch(item.path, item.path + ' (proposed)', readFileSync(join(root, item.path), 'utf8'), item.content));
46
54
  let cancelled;
package/dist/env.d.ts CHANGED
@@ -60,14 +60,6 @@ export declare function sandcmsEnvVars({ building }?: SandcmsEnvOptions): {
60
60
  description: string;
61
61
  schema: (value: string | undefined) => boolean;
62
62
  };
63
- SANDCMS_WORKER_TOKEN: {
64
- description: string;
65
- schema: (value: string | undefined) => string | undefined;
66
- };
67
- SANDCMS_WORKER_URL: {
68
- description: string;
69
- schema: (value: string | undefined) => string | undefined;
70
- };
71
63
  SANDCMS_TRUSTED_PROXY_HEADER: {
72
64
  description: string;
73
65
  schema: (value: string | undefined) => string | undefined;
package/dist/env.js CHANGED
@@ -106,14 +106,6 @@ export function sandcmsEnvVars({ building = false } = {}) {
106
106
  description: 'Allow a production database outside a mounted volume (the directory must persist).',
107
107
  schema: (value) => boolean(value) === 'true'
108
108
  },
109
- SANDCMS_WORKER_TOKEN: {
110
- description: 'Deprecated: legacy Cloudflare media Worker token, used only by sandcms media import-r2.',
111
- schema: optional
112
- },
113
- SANDCMS_WORKER_URL: {
114
- description: 'Deprecated: legacy Cloudflare media Worker URL, used only by sandcms media import-r2.',
115
- schema: (value) => (optional(value) ? url(value) : undefined)
116
- },
117
109
  SANDCMS_TRUSTED_PROXY_HEADER: {
118
110
  description: 'Client IP header set by a trusted reverse proxy (e.g. x-real-ip); see docs/deployment.md.',
119
111
  schema: (value) => {
@@ -1,7 +1,8 @@
1
+ import { fieldLabel } from './blueprints/labels.js';
1
2
  /** Groups are expanded so selecting one field never includes unrelated nested answers. */
2
3
  export function notificationFields(fields, prefix = '', label = '') {
3
4
  return Object.entries(fields).flatMap(([key, field]) => {
4
- const value = prefix + key, title = label + (field.label ?? key);
5
+ const value = prefix + key, title = label + fieldLabel(key, field);
5
6
  if (field.type === 'group')
6
7
  return notificationFields(field.fields ?? {}, value + '.', title + ' / ');
7
8
  // Repeated groups and rich content can contain additional unselected data.
@@ -11,6 +11,21 @@ type Usages = Record<string, {
11
11
  }[]>;
12
12
  /** Label options for every non-form blueprint, newest first. Empty blueprints map to []. */
13
13
  export declare function relationLabels(cms: CMS): Relations;
14
+ /** The newest document of every page blueprint, without creating missing singletons. */
15
+ export declare function pageEntries(cms: CMS): {
16
+ id: string;
17
+ blueprint: string;
18
+ singleton: string | null;
19
+ draft: import("../index.ts").Payload;
20
+ published: import("../index.ts").Payload | null;
21
+ draftSlug: string | null;
22
+ publishedSlug: string | null;
23
+ version: number;
24
+ publishedAt: number | null;
25
+ updatedAt: number;
26
+ createdAt: number;
27
+ searchText: string | null;
28
+ }[];
14
29
  /** Content references grouped by media id; every requested asset id gets an array. */
15
30
  export declare function mediaUsages(cms: CMS, assetIds: string[]): Usages;
16
31
  /** Dashboard entries (8 most recent) and counts, computed in SQL. */
@@ -54,6 +69,7 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
54
69
  twoFactorEnabled: boolean | null | undefined;
55
70
  };
56
71
  site: string;
72
+ logo: string | false | undefined;
57
73
  blueprints: {
58
74
  navigationIcon: import("@lucide/svelte").LucideIconData;
59
75
  id: string;
@@ -152,6 +168,59 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
152
168
  twoFactorEnabled: boolean | null | undefined;
153
169
  };
154
170
  site: string;
171
+ logo: string | false | undefined;
172
+ blueprints: {
173
+ navigationIcon: import("@lucide/svelte").LucideIconData;
174
+ id: string;
175
+ label: string;
176
+ kind: "page" | "site" | "collection" | "form";
177
+ icon?: string;
178
+ navigation?: {
179
+ group: string | false;
180
+ };
181
+ description?: string;
182
+ preview?: string;
183
+ fields: Record<string, import("../index.ts").Field>;
184
+ tabs?: Record<string, import("../index.ts").BlueprintTab>;
185
+ columns?: string[];
186
+ export?: string[];
187
+ }[];
188
+ emailEnabled: boolean;
189
+ mediaVersion: string;
190
+ fileBlueprints: import("../index.ts").FileBlueprint[];
191
+ defaultFileBlueprint: string;
192
+ next?: undefined;
193
+ } | {
194
+ theme: "system" | "light" | "dark";
195
+ entries: {
196
+ id: string;
197
+ blueprint: string;
198
+ singleton: string | null;
199
+ draft: import("../index.ts").Payload;
200
+ published: import("../index.ts").Payload | null;
201
+ draftSlug: string | null;
202
+ publishedSlug: string | null;
203
+ version: number;
204
+ publishedAt: number | null;
205
+ updatedAt: number;
206
+ createdAt: number;
207
+ searchText: string | null;
208
+ }[];
209
+ screen: string;
210
+ user: {
211
+ id: string;
212
+ createdAt: Date;
213
+ updatedAt: Date;
214
+ email: string;
215
+ emailVerified: boolean;
216
+ name: string;
217
+ image?: string | null | undefined | undefined;
218
+ role: string;
219
+ mustChangePassword: boolean;
220
+ twoFactorEnabled: boolean | null | undefined;
221
+ };
222
+ site: string;
223
+ logo: string | false | undefined;
155
224
  blueprints: {
156
225
  navigationIcon: import("@lucide/svelte").LucideIconData;
157
226
  id: string;
@@ -212,6 +281,7 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
212
281
  twoFactorEnabled: boolean | null | undefined;
213
282
  };
214
283
  site: string;
284
+ logo: string | false | undefined;
215
285
  blueprints: {
216
286
  navigationIcon: import("@lucide/svelte").LucideIconData;
217
287
  id: string;
@@ -270,6 +340,7 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
270
340
  twoFactorEnabled: boolean | null | undefined;
271
341
  };
272
342
  site: string;
343
+ logo: string | false | undefined;
273
344
  blueprints: {
274
345
  navigationIcon: import("@lucide/svelte").LucideIconData;
275
346
  id: string;
@@ -322,6 +393,7 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
322
393
  twoFactorEnabled: boolean | null | undefined;
323
394
  };
324
395
  site: string;
396
+ logo: string | false | undefined;
325
397
  blueprints: {
326
398
  navigationIcon: import("@lucide/svelte").LucideIconData;
327
399
  id: string;
@@ -38,6 +38,20 @@ export function relationLabels(cms) {
38
38
  relations[row.blueprint].push({ id: row.id, label: titleLabel(row) });
39
39
  return relations;
40
40
  }
41
+ /** The newest document of every page blueprint, without creating missing singletons. */
42
+ export function pageEntries(cms) {
43
+ const ids = cms.definition.blueprints.filter((b) => b.kind === 'page').map((b) => b.id);
44
+ if (!ids.length)
45
+ return [];
46
+ const seen = new Set();
47
+ return cms.store.db
48
+ .select()
49
+ .from(documents)
50
+ .where(inArray(documents.blueprint, ids))
51
+ .orderBy(desc(documents.updatedAt), asc(documents.id))
52
+ .all()
53
+ .filter((entry) => !seen.has(entry.blueprint) && !!seen.add(entry.blueprint));
54
+ }
41
55
  /** Content references grouped by media id; every requested asset id gets an array. */
42
56
  export function mediaUsages(cms, assetIds) {
43
57
  const usages = Object.fromEntries(assetIds.map((id) => [id, []]));
@@ -130,6 +144,7 @@ async function screenLoad(cms, event) {
130
144
  screen: screen || 'dashboard',
131
145
  user: session.user,
132
146
  site: cms.definition.config.name,
147
+ logo: cms.definition.config.logo,
133
148
  blueprints: cms.definition.blueprints.map((blueprint) => ({
134
149
  ...blueprint,
135
150
  navigationIcon: blueprintIcon(blueprint)
@@ -164,6 +179,11 @@ async function screenLoad(cms, event) {
164
179
  relations
165
180
  };
166
181
  }
182
+ if (screen === 'pages') {
183
+ if (key)
184
+ error(404, 'Page not found');
185
+ return { ...base, entries: pageEntries(cms) };
186
+ }
167
187
  if (screen === 'media')
168
188
  return {
169
189
  ...base,
@@ -0,0 +1,96 @@
1
+ import type { Auth } from './auth.js';
2
+ import type { Store } from './db/store.js';
3
+ export type KeyScope = 'read' | 'write';
4
+ /** An invalid key request; HTTP callers map it to 400. */
5
+ export declare class KeyRequestError extends Error {
6
+ }
7
+ /** Validates a key request; the lifetime defaults to 7 days for write keys and 30 for read keys. */
8
+ export declare function keyRequest(input: {
9
+ name?: unknown;
10
+ scope?: unknown;
11
+ expiresIn?: unknown;
12
+ }): {
13
+ name: string;
14
+ scope: KeyScope;
15
+ expiresIn: number;
16
+ };
17
+ export declare function issueApiKey(auth: Auth, userId: string, request: {
18
+ name: string;
19
+ scope: KeyScope;
20
+ expiresIn: number;
21
+ }): Promise<{
22
+ key: string;
23
+ metadata: any;
24
+ permissions: any;
25
+ id: string;
26
+ configId: string;
27
+ name: string | null;
28
+ start: string | null;
29
+ prefix: string | null;
30
+ referenceId: string;
31
+ refillInterval: number | null;
32
+ refillAmount: number | null;
33
+ lastRefillAt: Date | null;
34
+ enabled: boolean;
35
+ rateLimitEnabled: boolean;
36
+ rateLimitTimeWindow: number | null;
37
+ rateLimitMax: number | null;
38
+ requestCount: number;
39
+ remaining: number | null;
40
+ lastRequest: Date | null;
41
+ expiresAt: Date | null;
42
+ createdAt: Date;
43
+ updatedAt: Date;
44
+ }>;
45
+ /** Sanitized keys of every account, newest first. Secrets are never stored in plain text. */
46
+ export declare function listApiKeys(store: Store): {
47
+ permissions: {
48
+ cms?: string[];
49
+ } | null;
50
+ id: string;
51
+ name: string | null;
52
+ start: string | null;
53
+ prefix: string | null;
54
+ expiresAt: Date | null;
55
+ lastRequest: Date | null;
56
+ enabled: boolean | null;
57
+ referenceId: string;
58
+ owner: string;
59
+ }[];
60
+ /** Deletes a key and audits the revocation. Returns false when no such key exists. */
61
+ export declare function revokeApiKey(store: Store, id: string, actor: string): boolean;
62
+ /**
63
+ * Operator path for `sandcms key create`: issues a key for an existing admin or editor without a
64
+ * browser session. Anyone who can run the CLI against the database can already reset passwords.
65
+ */
66
+ export declare function createOperatorKey(auth: Auth, store: Store, input: {
67
+ email: string;
68
+ name: unknown;
69
+ scope: unknown;
70
+ days?: unknown;
71
+ }): Promise<{
72
+ scope: KeyScope;
73
+ owner: string;
74
+ key: string;
75
+ metadata: any;
76
+ permissions: any;
77
+ id: string;
78
+ configId: string;
79
+ name: string | null;
80
+ start: string | null;
81
+ prefix: string | null;
82
+ referenceId: string;
83
+ refillInterval: number | null;
84
+ refillAmount: number | null;
85
+ lastRefillAt: Date | null;
86
+ enabled: boolean;
87
+ rateLimitEnabled: boolean;
88
+ rateLimitTimeWindow: number | null;
89
+ rateLimitMax: number | null;
90
+ requestCount: number;
91
+ remaining: number | null;
92
+ lastRequest: Date | null;
93
+ expiresAt: Date | null;
94
+ createdAt: Date;
95
+ updatedAt: Date;
96
+ }>;
@@ -0,0 +1,115 @@
1
+ import { desc, eq } from 'drizzle-orm';
2
+ import { apikey, audit, user } from './db/schema.js';
3
+ /** An invalid key request; HTTP callers map it to 400. */
4
+ export class KeyRequestError extends Error {
5
+ }
6
+ const day = 60 * 60 * 24;
7
+ /** Validates a key request; the lifetime defaults to 7 days for write keys and 30 for read keys. */
8
+ export function keyRequest(input) {
9
+ const { name, scope } = input;
10
+ if (scope !== 'read' && scope !== 'write')
11
+ throw new KeyRequestError('Scope must be read or write');
12
+ if (typeof name !== 'string' || !name.trim() || name.length > 100)
13
+ throw new KeyRequestError('Use a key name with 1–100 characters');
14
+ const expiresIn = input.expiresIn ?? day * (scope === 'write' ? 7 : 30);
15
+ if (typeof expiresIn !== 'number' ||
16
+ !Number.isInteger(expiresIn) ||
17
+ expiresIn < day ||
18
+ expiresIn > day * 365)
19
+ throw new KeyRequestError('expiresIn must be between 1 and 365 days, in seconds');
20
+ return { name: name.trim(), scope: scope, expiresIn };
21
+ }
22
+ export function issueApiKey(auth, userId, request) {
23
+ return auth.api.createApiKey({
24
+ body: {
25
+ userId,
26
+ name: request.name,
27
+ expiresIn: request.expiresIn,
28
+ permissions: { cms: request.scope === 'write' ? ['read', 'write'] : ['read'] }
29
+ }
30
+ });
31
+ }
32
+ /** Sanitized keys of every account, newest first. Secrets are never stored in plain text. */
33
+ export function listApiKeys(store) {
34
+ return store.db
35
+ .select({
36
+ id: apikey.id,
37
+ name: apikey.name,
38
+ start: apikey.start,
39
+ prefix: apikey.prefix,
40
+ expiresAt: apikey.expiresAt,
41
+ lastRequest: apikey.lastRequest,
42
+ enabled: apikey.enabled,
43
+ referenceId: apikey.referenceId,
44
+ owner: user.email,
45
+ permissions: apikey.permissions
46
+ })
47
+ .from(apikey)
48
+ .innerJoin(user, eq(user.id, apikey.referenceId))
49
+ .orderBy(desc(apikey.createdAt), desc(apikey.id))
50
+ .all()
51
+ .map((key) => ({
52
+ ...key,
53
+ permissions: (key.permissions ? JSON.parse(key.permissions) : null)
54
+ }));
55
+ }
56
+ /** Deletes a key and audits the revocation. Returns false when no such key exists. */
57
+ export function revokeApiKey(store, id, actor) {
58
+ return store.db.transaction((tx) => {
59
+ const revoked = tx
60
+ .delete(apikey)
61
+ .where(eq(apikey.id, id))
62
+ .returning({ referenceId: apikey.referenceId })
63
+ .get();
64
+ if (!revoked)
65
+ return false;
66
+ tx.insert(audit)
67
+ .values({
68
+ id: crypto.randomUUID(),
69
+ actor,
70
+ action: 'apikey.revoke',
71
+ detail: { keyId: id, ownerId: revoked.referenceId },
72
+ createdAt: Date.now()
73
+ })
74
+ .run();
75
+ return true;
76
+ });
77
+ }
78
+ /**
79
+ * Operator path for `sandcms key create`: issues a key for an existing admin or editor without a
80
+ * browser session. Anyone who can run the CLI against the database can already reset passwords.
81
+ */
82
+ export async function createOperatorKey(auth, store, input) {
83
+ const days = input.days === undefined ? undefined : Number(input.days);
84
+ if (days !== undefined && !Number.isInteger(days))
85
+ throw new KeyRequestError('--days must be a whole number from 1 to 365');
86
+ const request = keyRequest({
87
+ name: input.name,
88
+ scope: input.scope,
89
+ expiresIn: days === undefined ? undefined : days * day
90
+ });
91
+ const owner = store.db
92
+ .select()
93
+ .from(user)
94
+ .where(eq(user.email, input.email.trim().toLowerCase()))
95
+ .get();
96
+ if (!owner)
97
+ throw new Error('User not found');
98
+ if (!['admin', 'editor'].includes(owner.role ?? ''))
99
+ throw new Error('Key owners must be admins or editors');
100
+ // The API rejects keys whose owner still has a temporary password; fail before issuing one.
101
+ if (owner.mustChangePassword)
102
+ throw new Error('This account still has a temporary password. Sign in and change it before creating a key.');
103
+ const created = await issueApiKey(auth, owner.id, request);
104
+ store.db
105
+ .insert(audit)
106
+ .values({
107
+ id: crypto.randomUUID(),
108
+ actor: 'operator',
109
+ action: 'apikey.create',
110
+ detail: { keyId: created.id, ownerId: owner.id, scope: request.scope },
111
+ createdAt: Date.now()
112
+ })
113
+ .run();
114
+ return { ...created, scope: request.scope, owner: owner.email };
115
+ }