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
package/dist/cli/index.js CHANGED
@@ -1,70 +1,209 @@
1
1
  #!/usr/bin/env bun
2
2
  import { config as loadEnv } from 'dotenv';
3
3
  import { parseArgs } from 'node:util';
4
- import { resolve, join } from 'node:path';
4
+ import { resolve, join, dirname } from 'node:path';
5
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
5
6
  import { setup } from './setup.js';
6
7
  import { upgrade } from './upgrade.js';
7
8
  import { backup, restore } from './backup.js';
9
+ import { rebaseline } from './rebaseline.js';
8
10
  import { openStore, applyMigrations, pendingMigrations, inspectMigrations } from '../server/db/store.js';
9
11
  import { createCMS } from '../server/cms.js';
10
- import { createUser, recoverUser } from '../server/auth.js';
12
+ import { createAuth, createUser, recoverUser } from '../server/auth.js';
13
+ import { createOperatorKey, listApiKeys, revokeApiKey } from '../server/api-keys.js';
14
+ import { createForms } from '../server/forms.js';
11
15
  import { user } from '../server/db/schema.js';
12
16
  import { loadDefinition } from '../blueprints/load.js';
13
17
  import { text, password, confirm } from './prompts.js';
14
18
  import { doctor } from './doctor.js';
15
- import { importFromR2 } from '../server/media/import-r2.js';
16
- import { forceRebuild, verifyMedia } from '../server/media/verify.js';
17
- const { values, positionals } = parseArgs({
18
- args: process.argv.slice(2),
19
- allowPositionals: true,
20
- options: {
21
- cwd: { type: 'string' },
22
- name: { type: 'string' },
23
- email: { type: 'string' },
24
- role: { type: 'string' },
25
- database: { type: 'string' },
26
- output: { type: 'string' },
27
- from: { type: 'string' },
28
- package: { type: 'string' },
29
- 'worker-url': { type: 'string' },
30
- check: { type: 'boolean' },
31
- 'dry-run': { type: 'boolean' },
32
- 'skip-install': { type: 'boolean' },
33
- 'password-stdin': { type: 'boolean' },
34
- 'worker-token-stdin': { type: 'boolean' },
35
- force: { type: 'boolean' },
36
- repair: { type: 'boolean' },
37
- yes: { type: 'boolean' },
38
- help: { type: 'boolean' }
19
+ import { PACKAGE_VERSION } from './files.js';
20
+ import { listUsers, removeUser, setRole, signOut, revokeOwnerKeys } from './admin.js';
21
+ import { sendTestEmail } from './email-test.js';
22
+ import { forceRebuild, verifyMedia, pruneMedia } from '../server/media/verify.js';
23
+ const HELP = {
24
+ setup: `sandcms setup [--name NAME] [--dry-run] [--yes] [--skip-install] [--package SPEC] [--email EMAIL]
25
+ Create a new site or add SandCMS to an existing SvelteKit app. Runs interactively without a command.`,
26
+ validate: `sandcms validate
27
+ Check the YAML blueprints and media presets in sandcms/.`,
28
+ doctor: `sandcms doctor [--json]
29
+ Check configuration, environment, database, data volume and media storage. Exits 1 on any FAIL.`,
30
+ upgrade: `sandcms upgrade [--check]
31
+ Update generated integration files; --check only prints the report.`,
32
+ migrate: `sandcms migrate [--check] [--json]
33
+ Apply pending database migrations; --check only lists them.`,
34
+ backup: `sandcms backup --output PATH
35
+ Write a verified snapshot of the database. Media files are not included.`,
36
+ restore: `sandcms restore --from PATH [--yes]
37
+ Replace the database with a verified backup, keeping a safety copy. Stop the website first.`,
38
+ rebaseline: `sandcms rebaseline [--yes]
39
+ Convert a SandCMS 0.7.x database to the 0.8.0 migration baseline once, copying every row and keeping
40
+ a safety copy. Stop the website first. Media files are not touched.`,
41
+ user: `sandcms user list [--json]
42
+ sandcms user bootstrap --email EMAIL [--name NAME]
43
+ sandcms user add --email EMAIL [--name NAME] [--role admin|editor] [--password-stdin]
44
+ sandcms user set-role --email EMAIL --role admin|editor
45
+ sandcms user remove --email EMAIL [--yes]
46
+ sandcms user reset-password --email EMAIL [--password-stdin]
47
+ sandcms user reset-2fa --email EMAIL
48
+ sandcms user sign-out (--email EMAIL | --all [--yes])
49
+ Manage admin accounts. Removing a user also removes their sessions and API keys; the last admin is kept.`,
50
+ key: `sandcms key create --email EMAIL --name NAME --scope read|write [--days N]
51
+ sandcms key list [--json]
52
+ sandcms key revoke (--id ID | --email EMAIL)
53
+ Manage agent API keys. create prints only the secret on stdout; --email revokes every key of that user.`,
54
+ email: `sandcms email test --to ADDRESS
55
+ Send a test message with the SANDCMS_EMAIL_* and SANDCMS_SMTP_* settings.`,
56
+ forms: `sandcms forms export FORM --output PATH [--force]
57
+ Write a form's submissions as CSV, the same file the admin exports.`,
58
+ media: `sandcms media rebuild [--force]
59
+ sandcms media verify [--repair]
60
+ sandcms media prune [--delete] [--yes] [--json]
61
+ rebuild renders missing or outdated variants (--force re-renders all); verify finds missing files;
62
+ prune lists files no asset uses (deleted assets, old variant versions) and --delete removes them.`
63
+ };
64
+ const USAGE = `SandCMS ${PACKAGE_VERSION}
65
+
66
+ Usage: sandcms <command> [options]
67
+
68
+ Commands:
69
+ setup Create or integrate a site
70
+ validate Check blueprints and presets
71
+ doctor Check configuration and deployment
72
+ upgrade Update generated integration files
73
+ migrate Apply database migrations
74
+ backup Write a verified database snapshot
75
+ restore Restore a database snapshot
76
+ rebaseline Convert a 0.7.x database to the 0.8.0 baseline
77
+ user Manage users and sessions
78
+ key Create, list or revoke agent API keys
79
+ email Send a test email
80
+ forms Export form submissions
81
+ media Rebuild, verify, prune or import media
82
+
83
+ Global options:
84
+ --cwd PATH Project directory (default: current directory)
85
+ --database PATH Database (default: SANDCMS_DATABASE or ./data/sandcms.sqlite)
86
+ --version Print the version
87
+ --help Show help; sandcms <command> --help shows a command
88
+
89
+ Secrets are never accepted as arguments.`;
90
+ function parse(args) {
91
+ try {
92
+ return parseArgs({
93
+ args,
94
+ allowPositionals: true,
95
+ options: {
96
+ cwd: { type: 'string' },
97
+ name: { type: 'string' },
98
+ email: { type: 'string' },
99
+ role: { type: 'string' },
100
+ scope: { type: 'string' },
101
+ days: { type: 'string' },
102
+ id: { type: 'string' },
103
+ to: { type: 'string' },
104
+ database: { type: 'string' },
105
+ output: { type: 'string' },
106
+ from: { type: 'string' },
107
+ package: { type: 'string' },
108
+ check: { type: 'boolean' },
109
+ json: { type: 'boolean' },
110
+ all: { type: 'boolean' },
111
+ delete: { type: 'boolean' },
112
+ 'dry-run': { type: 'boolean' },
113
+ 'skip-install': { type: 'boolean' },
114
+ 'password-stdin': { type: 'boolean' },
115
+ force: { type: 'boolean' },
116
+ repair: { type: 'boolean' },
117
+ yes: { type: 'boolean' },
118
+ version: { type: 'boolean' },
119
+ help: { type: 'boolean' }
120
+ }
121
+ });
122
+ }
123
+ catch (error) {
124
+ // Node's messages explain `--` positionals at length; the first sentence is the useful part.
125
+ const message = error instanceof Error ? error.message.split('. ')[0] : String(error);
126
+ throw new Error(`${message}. Run sandcms --help`);
39
127
  }
40
- });
41
- const root = resolve(values.cwd ?? '.');
42
- loadEnv({ path: [join(root, '.env.local'), join(root, '.env')], override: false, quiet: true });
43
- const database = resolve(root, values.database ?? process.env.SANDCMS_DATABASE ?? './data/sandcms.sqlite');
44
- async function suppliedPassword() {
45
- return values['password-stdin']
46
- ? (await Bun.stdin.text()).replace(/\r?\n$/, '')
47
- : await password();
48
128
  }
129
+ const SUBCOMMANDS = {
130
+ user: [
131
+ 'list',
132
+ 'bootstrap',
133
+ 'add',
134
+ 'set-role',
135
+ 'remove',
136
+ 'reset-password',
137
+ 'reset-2fa',
138
+ 'sign-out'
139
+ ],
140
+ key: ['create', 'list', 'revoke'],
141
+ email: ['test'],
142
+ forms: ['export'],
143
+ media: ['rebuild', 'verify', 'prune']
144
+ };
145
+ const date = (value) => (value ? value.slice(0, 10) : '-');
146
+ function table(rows) {
147
+ const widths = rows[0].map((_, i) => Math.max(...rows.map((row) => row[i].length)));
148
+ for (const row of rows)
149
+ console.log(row.map((cell, i) => cell.padEnd(widths[i])).join(' '));
150
+ }
151
+ const mb = (bytes) => `${(bytes / 1024 ** 2).toFixed(1)} MB`;
49
152
  async function main() {
153
+ const { values, positionals } = parse(process.argv.slice(2));
50
154
  const [command, subcommand] = positionals;
51
- if (values.help) {
52
- console.log('sandcms setup | validate | doctor | upgrade [--check] | migrate [--check] | media rebuild [--force] | media verify [--repair] | media import-r2 [--worker-url URL] [--worker-token-stdin] | backup --output PATH | restore --from PATH | user bootstrap/add/reset-password/reset-2fa\nUse --database PATH to select the target database. Secrets are never accepted as arguments.');
155
+ if (values.version)
156
+ return console.log(PACKAGE_VERSION);
157
+ if (command === 'help' || values.help) {
158
+ const topic = command === 'help' ? subcommand : command;
159
+ console.log(topic && HELP[topic] ? HELP[topic] : USAGE);
53
160
  return;
54
161
  }
162
+ const root = resolve(values.cwd ?? '.');
163
+ loadEnv({ path: [join(root, '.env.local'), join(root, '.env')], override: false, quiet: true });
164
+ const database = resolve(root, values.database ?? process.env.SANDCMS_DATABASE ?? './data/sandcms.sqlite');
55
165
  if (!command) {
56
166
  if (!process.stdin.isTTY)
57
167
  throw new Error('Choose a command; use --help');
58
168
  return setup({ root });
59
169
  }
60
- console.log(`Project: ${root}\nDatabase: ${database}\nRuntime: Bun ${Bun.version}`);
170
+ if (!HELP[command])
171
+ throw new Error(`Unknown command ${command}. Run sandcms --help`);
172
+ if (SUBCOMMANDS[command] && !SUBCOMMANDS[command].includes(subcommand))
173
+ throw new Error(`${subcommand ? `Unknown command ${command} ${subcommand}` : `Choose a ${command} command`}. Use one of: ${SUBCOMMANDS[command].join(', ')}. Run sandcms ${command} --help`);
174
+ // Machine-readable output stays alone on stdout: `key create` prints only the secret there.
175
+ if (!values.json)
176
+ (command === 'key' ? console.error : console.log)(`Project: ${root}\nDatabase: ${database}\nRuntime: Bun ${Bun.version}`);
177
+ const suppliedPassword = async () => values['password-stdin'] ? (await Bun.stdin.text()).replace(/\r?\n$/, '') : await password();
178
+ // Destructive commands ask first; scripts and non-interactive shells pass --yes.
179
+ const approve = async (message) => {
180
+ if (values.yes)
181
+ return;
182
+ if (!process.stdin.isTTY)
183
+ throw new Error('Pass --yes to confirm in a non-interactive shell');
184
+ if (!(await confirm(message)))
185
+ throw new Error('Cancelled');
186
+ };
187
+ const emailOption = async () => values.email ?? (await text('Email address'));
188
+ // CLI media commands never call media.start(): no background tasks, schedulers or snapshots.
189
+ const openCMS = () => {
190
+ const mediaDir = process.env.SANDCMS_MEDIA_DIR;
191
+ return createCMS({
192
+ database,
193
+ root: join(root, 'sandcms'),
194
+ origin: process.env.SANDCMS_ORIGIN ?? 'http://localhost:5410',
195
+ secret: process.env.SANDCMS_SECRET ?? '',
196
+ ...(mediaDir ? { mediaDir: resolve(root, mediaDir) } : {})
197
+ });
198
+ };
61
199
  if (command === 'validate') {
62
200
  const definition = loadDefinition(join(root, 'sandcms'));
63
201
  console.log(`Validated ${definition.blueprints.length} blueprints and media presets.`);
64
202
  return;
65
203
  }
66
204
  if (command === 'migrate' && values.check) {
67
- console.log(inspectMigrations(database).map((m) => m.name));
205
+ const pending = inspectMigrations(database).map((m) => m.name);
206
+ console.log(values.json ? JSON.stringify({ pending }) : pending);
68
207
  return;
69
208
  }
70
209
  if (command === 'setup')
@@ -79,7 +218,7 @@ async function main() {
79
218
  database: values.database
80
219
  });
81
220
  if (command === 'upgrade')
82
- return upgrade(root, values.check, database);
221
+ return void (await upgrade(root, values.check, database));
83
222
  if (command === 'backup') {
84
223
  if (!values.output)
85
224
  throw new Error('Use --output PATH');
@@ -94,110 +233,202 @@ async function main() {
94
233
  console.log(restore(database, values.from, approved));
95
234
  return;
96
235
  }
236
+ if (command === 'rebaseline') {
237
+ const approved = values.yes ||
238
+ (await confirm(`Convert ${database} to the SandCMS 0.8.0 migration baseline? Stop all website processes first. A safety copy will be retained.`));
239
+ const result = rebaseline(database, approved);
240
+ console.log(`Rebaselined ${result.target}. Safety copy: ${result.safety}\nRows: ${Object.entries(result.copied)
241
+ .map(([table, n]) => `${table} ${n}`)
242
+ .join(', ')}`);
243
+ return;
244
+ }
97
245
  if (command === 'doctor')
98
- return doctor(root, database);
99
- if (command === 'media')
100
- return mediaCommand(subcommand);
246
+ return void (await doctor(root, database, process.env, values));
247
+ if (command === 'email') {
248
+ const to = values.to ?? (await text('Send the test to'));
249
+ const result = await sendTestEmail(to);
250
+ console.log(`Accepted by the mail server (message ID ${result.messageId}). Check the inbox and spam folder of ${to}.`);
251
+ return;
252
+ }
253
+ if (command === 'media') {
254
+ const cms = openCMS();
255
+ try {
256
+ return await mediaCommand(cms, subcommand);
257
+ }
258
+ finally {
259
+ cms.close();
260
+ }
261
+ }
262
+ // migrate initializes a new database; the other commands need an existing one.
263
+ if (command !== 'migrate' && !existsSync(database))
264
+ throw new Error(`Database ${database} does not exist. Check --database or SANDCMS_DATABASE.`);
101
265
  const store = openStore(database);
102
266
  try {
103
267
  if (command === 'migrate') {
104
- if (values.check)
105
- console.log(pendingMigrations(store).map((m) => m.name));
106
- else
107
- console.log('Applied:', applyMigrations(store));
268
+ console.log('Applied:', applyMigrations(store));
108
269
  return;
109
270
  }
110
- if (command === 'user') {
111
- if (pendingMigrations(store).length)
112
- throw new Error('Run sandcms migrate first');
113
- const email = values.email ?? (await text('Email address'));
114
- if (subcommand === 'bootstrap') {
115
- if (store.db.select().from(user).limit(1).get())
116
- throw new Error('Bootstrap is only available on an empty user database');
117
- const generated = crypto.randomUUID() + 'A!';
118
- await createUser(store, {
119
- email,
120
- name: values.name ?? 'Administrator',
121
- role: 'admin',
122
- password: generated
271
+ if (pendingMigrations(store).length)
272
+ throw new Error('Run sandcms migrate first');
273
+ if (command === 'forms') {
274
+ const formId = positionals[2];
275
+ if (!formId)
276
+ throw new Error('Name the form: sandcms forms export FORM --output PATH');
277
+ if (!values.output)
278
+ throw new Error('Use --output PATH');
279
+ const definition = loadDefinition(join(root, 'sandcms'));
280
+ const forms = definition.blueprints.filter((b) => b.kind === 'form').map((b) => b.id);
281
+ if (!forms.includes(formId))
282
+ throw new Error(`No form blueprint ${formId}. Forms: ${forms.join(', ') || 'none'}`);
283
+ const output = resolve(values.output);
284
+ if (existsSync(output) && !values.force)
285
+ throw new Error(`${output} exists; choose a new path or pass --force`);
286
+ mkdirSync(dirname(output), { recursive: true });
287
+ writeFileSync(output, createForms(store, definition).csv(formId), { mode: 0o600 });
288
+ console.log(`Wrote ${formId} submissions to ${output}. It contains personal data.`);
289
+ return;
290
+ }
291
+ if (command === 'key') {
292
+ if (subcommand === 'create') {
293
+ const auth = createAuth(store, {
294
+ origin: process.env.SANDCMS_ORIGIN ?? 'http://localhost:5410',
295
+ secret: process.env.SANDCMS_SECRET ?? ''
123
296
  });
124
- console.log(`One-time bootstrap password: ${generated}\nChange it at first sign-in. This account exists only in ${database}.`);
125
- return;
126
- }
127
- if (subcommand === 'add') {
128
- const role = values.role ?? 'editor';
129
- if (role !== 'admin' && role !== 'editor')
130
- throw new Error('Role must be admin or editor');
131
- await createUser(store, {
132
- email,
133
- name: values.name ?? (await text('Display name')),
134
- role,
135
- password: await suppliedPassword()
297
+ const key = await createOperatorKey(auth, store, {
298
+ email: values.email ?? (await text('Owner email address')),
299
+ name: values.name ?? (await text('Key name')),
300
+ scope: values.scope ?? (await text('Scope (read or write)')),
301
+ days: values.days
136
302
  });
137
- console.log('User created; deliver the supplied password privately.');
303
+ console.error(`Created ${key.scope} key ${key.id} for ${key.owner}, expires ${key.expiresAt?.toISOString()}.\nThe secret below is shown once; send it as the x-api-key header. Revoke with: sandcms key revoke --id ${key.id}`);
304
+ console.log(key.key);
138
305
  return;
139
306
  }
140
- if (subcommand === 'reset-password') {
141
- await recoverUser(store, email, 'password', await suppliedPassword());
142
- console.log('Password reset; sessions invalidated; recovery audited.');
307
+ if (subcommand === 'list') {
308
+ const keys = listApiKeys(store).map((k) => ({
309
+ id: k.id,
310
+ name: k.name,
311
+ start: k.start,
312
+ owner: k.owner,
313
+ scope: k.permissions?.cms?.includes('write') ? 'write' : 'read',
314
+ enabled: k.enabled !== false,
315
+ expiresAt: k.expiresAt?.toISOString() ?? null,
316
+ expired: Boolean(k.expiresAt && k.expiresAt.getTime() <= Date.now()),
317
+ lastRequest: k.lastRequest?.toISOString() ?? null
318
+ }));
319
+ if (values.json)
320
+ return console.log(JSON.stringify(keys, null, 2));
321
+ if (!keys.length)
322
+ return console.log('No API keys.');
323
+ table([
324
+ ['ID', 'Name', 'Owner', 'Scope', 'Expires', 'Last used'],
325
+ ...keys.map((k) => [
326
+ k.id,
327
+ `${k.name ?? ''} (${k.start ?? ''}…)`,
328
+ k.owner,
329
+ k.scope,
330
+ k.expired ? 'expired' : date(k.expiresAt),
331
+ date(k.lastRequest)
332
+ ])
333
+ ]);
143
334
  return;
144
335
  }
145
- if (subcommand === 'reset-2fa') {
146
- await recoverUser(store, email, '2fa');
147
- console.log('Two-factor reset; sessions invalidated; recovery audited.');
336
+ if (values.id && values.email)
337
+ throw new Error('Use either --id ID or --email EMAIL');
338
+ if (values.email) {
339
+ const revoked = revokeOwnerKeys(store, values.email);
340
+ console.log(`Revoked ${revoked} API key${revoked === 1 ? '' : 's'} of ${values.email}; revocations audited.`);
148
341
  return;
149
342
  }
343
+ const id = values.id ?? (await text('Key ID'));
344
+ if (!revokeApiKey(store, id, 'operator'))
345
+ throw new Error('API key not found');
346
+ console.log('Key revoked; revocation audited.');
347
+ return;
150
348
  }
151
- throw new Error('Unknown command. Run sandcms --help');
152
- }
153
- finally {
154
- store.close();
155
- }
156
- }
157
- // CLI media commands never call media.start(): no background tasks, schedulers or snapshots.
158
- function openCMS() {
159
- const mediaDir = process.env.SANDCMS_MEDIA_DIR;
160
- return createCMS({
161
- database,
162
- root: join(root, 'sandcms'),
163
- origin: process.env.SANDCMS_ORIGIN ?? 'http://localhost:5410',
164
- secret: process.env.SANDCMS_SECRET ?? '',
165
- ...(mediaDir ? { mediaDir: resolve(root, mediaDir) } : {})
166
- });
167
- }
168
- async function mediaCommand(subcommand) {
169
- if (subcommand === 'import-r2') {
170
- const token = values['worker-token-stdin']
171
- ? (await Bun.stdin.text()).trim()
172
- : (process.env.SANDCMS_WORKER_TOKEN ?? '');
173
- const cms = openCMS();
174
- try {
175
- const summary = await importFromR2(cms, {
176
- workerUrl: values['worker-url'] ??
177
- process.env.SANDCMS_WORKER_URL ??
178
- cms.definition.config.media.workerUrl ??
179
- '',
180
- workerToken: token
349
+ // command === 'user'
350
+ if (subcommand === 'list') {
351
+ const users = listUsers(store);
352
+ if (values.json)
353
+ return console.log(JSON.stringify(users, null, 2));
354
+ if (!users.length)
355
+ return console.log('No users. Run sandcms user bootstrap.');
356
+ table([
357
+ ['Email', 'Name', 'Role', '2FA', 'Sessions', 'Created'],
358
+ ...users.map((u) => [
359
+ u.email + (u.mustChangePassword ? ' (temporary password)' : ''),
360
+ u.name,
361
+ u.role,
362
+ u.twoFactor ? 'yes' : 'no',
363
+ String(u.activeSessions),
364
+ date(u.createdAt)
365
+ ])
366
+ ]);
367
+ return;
368
+ }
369
+ if (subcommand === 'sign-out') {
370
+ if (!!values.all === !!values.email)
371
+ throw new Error('Use either --email EMAIL or --all');
372
+ if (values.all)
373
+ await approve('Sign out every user, including you? Content and API keys are kept.');
374
+ const ended = signOut(store, values.email);
375
+ console.log(`Ended ${ended} session${ended === 1 ? '' : 's'}; recorded in the audit log.`);
376
+ return;
377
+ }
378
+ const email = await emailOption();
379
+ if (subcommand === 'bootstrap') {
380
+ if (store.db.select().from(user).limit(1).get())
381
+ throw new Error('Bootstrap is only available on an empty user database');
382
+ const generated = crypto.randomUUID() + 'A!';
383
+ await createUser(store, {
384
+ email,
385
+ name: values.name ?? 'Administrator',
386
+ role: 'admin',
387
+ password: generated
181
388
  });
182
- for (const s of summary.skipped)
183
- console.log(`Skipped ${s.id}: ${s.reason}`);
184
- for (const f of summary.failures)
185
- console.error(`Failed ${f.id}${f.key ? ` ${f.key}` : ''}: ${f.error}`);
186
- console.log(`Assets: ${summary.assets}. Originals: ${summary.originals.imported} imported, ${summary.originals.present} already present. ` +
187
- `Variants: ${summary.variants.imported} imported, ${summary.variants.present} already present. ` +
188
- `Dimensions filled: ${summary.dimensions}. Verified ${summary.verified.originals} originals and ${summary.verified.variants} variants.`);
189
- if (!summary.ok)
190
- throw new Error(`${summary.failures.length} files failed. Fix the cause and run media import-r2 again; finished files are kept.`);
191
- console.log('Import complete. Check the site, then remove the Worker settings.');
389
+ console.log(`One-time bootstrap password: ${generated}\nChange it at first sign-in. This account exists only in ${database}.`);
390
+ return;
192
391
  }
193
- finally {
194
- cms.close();
392
+ if (subcommand === 'add') {
393
+ const role = values.role ?? 'editor';
394
+ if (role !== 'admin' && role !== 'editor')
395
+ throw new Error('Role must be admin or editor');
396
+ await createUser(store, {
397
+ email,
398
+ name: values.name ?? (await text('Display name')),
399
+ role,
400
+ password: await suppliedPassword()
401
+ });
402
+ console.log('User created; deliver the supplied password privately.');
403
+ return;
195
404
  }
196
- return;
405
+ if (subcommand === 'set-role') {
406
+ if (!values.role)
407
+ throw new Error('Use --role admin or --role editor');
408
+ console.log(setRole(store, email, values.role)
409
+ ? `${email} is now ${values.role === 'admin' ? 'an admin' : 'an editor'}.`
410
+ : `${email} already has the ${values.role} role.`);
411
+ return;
412
+ }
413
+ if (subcommand === 'remove') {
414
+ await approve(`Remove ${email}? Their sessions and API keys are deleted. Content is kept.`);
415
+ removeUser(store, email);
416
+ console.log('User removed; recorded in the audit log.');
417
+ return;
418
+ }
419
+ if (subcommand === 'reset-password') {
420
+ await recoverUser(store, email, 'password', await suppliedPassword());
421
+ console.log('Password reset; sessions invalidated; recovery audited.');
422
+ return;
423
+ }
424
+ await recoverUser(store, email, '2fa');
425
+ console.log('Two-factor reset; sessions invalidated; recovery audited.');
197
426
  }
198
- if (subcommand === 'verify') {
199
- const cms = openCMS();
200
- try {
427
+ finally {
428
+ store.close();
429
+ }
430
+ async function mediaCommand(cms, subcommand) {
431
+ if (subcommand === 'verify') {
201
432
  const report = verifyMedia(cms, { repair: values.repair });
202
433
  for (const id of report.missingOriginals)
203
434
  console.error(`Original missing: ${id}`);
@@ -211,16 +442,26 @@ async function mediaCommand(subcommand) {
211
442
  : ''));
212
443
  if (!values.repair && (report.missingOriginals.length || report.missingVariants.length))
213
444
  throw new Error('Media files are missing; run media verify --repair');
445
+ return;
214
446
  }
215
- finally {
216
- cms.close();
447
+ if (subcommand === 'prune') {
448
+ const found = pruneMedia(cms);
449
+ let report = found;
450
+ if (values.delete && found.items.length) {
451
+ await approve(`Permanently delete ${found.items.length} unused media folders and files (${mb(found.bytes)})? ` +
452
+ 'An older database backup that still uses them would need media verify --repair after a restore.');
453
+ report = pruneMedia(cms, { remove: true });
454
+ }
455
+ if (values.json)
456
+ return console.log(JSON.stringify(report, null, 2));
457
+ for (const item of report.items)
458
+ console.log(`${report.removed ? 'Removed' : 'Unused'}: ${item.path} (${mb(item.bytes)}, ${item.reason === 'old-version' ? 'old variant version' : 'no asset'})`);
459
+ console.log(report.removed
460
+ ? `Removed ${report.items.length} entries, freeing ${mb(report.bytes)}.`
461
+ : `${report.items.length} unused entries use ${mb(report.bytes)}.` +
462
+ (report.items.length ? ' Run media prune --delete to remove them.' : ''));
463
+ return;
217
464
  }
218
- return;
219
- }
220
- if (subcommand !== 'rebuild')
221
- throw new Error('Unknown command. Run sandcms --help');
222
- const cms = openCMS();
223
- try {
224
465
  if (values.force)
225
466
  console.log(`Re-rendering ${forceRebuild(cms)} assets with the local processor.`);
226
467
  cms.media.rebuild();
@@ -240,9 +481,6 @@ async function mediaCommand(subcommand) {
240
481
  if (counts().failed)
241
482
  throw new Error('Some images failed; retry with media rebuild');
242
483
  }
243
- finally {
244
- cms.close();
245
- }
246
484
  }
247
485
  main().catch((e) => {
248
486
  console.error(e instanceof Error ? e.message : e);
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Convert a SandCMS 0.7.x database (the retired 0000–0009 migration history) into a fresh database built
3
+ * from the 0.8.0 baseline, copying every row. Media files are untouched. The website must be stopped; a
4
+ * verified safety copy of the old database is kept next to it.
5
+ */
6
+ export declare function rebaseline(database: string, confirmed?: boolean): {
7
+ target: string;
8
+ safety: string;
9
+ copied: Record<string, number>;
10
+ };