sandcms 0.5.3 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +5 -3
  2. package/dist/admin/Account.svelte +4 -1
  3. package/dist/admin/ApiKeys.svelte +159 -0
  4. package/dist/admin/ApiKeys.svelte.d.ts +3 -0
  5. package/dist/admin/AssetAttachment.svelte +6 -4
  6. package/dist/admin/BlueprintFields.svelte +86 -0
  7. package/dist/admin/BlueprintFields.svelte.d.ts +15 -0
  8. package/dist/admin/Collection.svelte +40 -7
  9. package/dist/admin/Editor.svelte +57 -17
  10. package/dist/admin/Fields.svelte +217 -144
  11. package/dist/admin/Fields.svelte.d.ts +1 -0
  12. package/dist/admin/FocusPicker.svelte +136 -0
  13. package/dist/admin/FocusPicker.svelte.d.ts +11 -0
  14. package/dist/admin/Gallery.svelte +40 -34
  15. package/dist/admin/GlobalSearch.svelte +56 -0
  16. package/dist/admin/GlobalSearch.svelte.d.ts +3 -0
  17. package/dist/admin/Inbox.svelte +8 -5
  18. package/dist/admin/LinkField.svelte +116 -0
  19. package/dist/admin/LinkField.svelte.d.ts +17 -0
  20. package/dist/admin/MediaLibrary.svelte +41 -14
  21. package/dist/admin/MediaPicker.svelte +12 -2
  22. package/dist/admin/NotificationSettings.svelte +2 -2
  23. package/dist/admin/SearchList.svelte +55 -0
  24. package/dist/admin/SearchList.svelte.d.ts +42 -0
  25. package/dist/admin/SelectField.svelte +3 -1
  26. package/dist/admin/SelectField.svelte.d.ts +1 -0
  27. package/dist/admin/Shell.svelte +4 -2
  28. package/dist/admin/UnsavedChanges.svelte +1 -1
  29. package/dist/admin/Users.svelte +11 -5
  30. package/dist/admin/client.js +2 -1
  31. package/dist/admin/generated/admin.css +109 -0
  32. package/dist/admin/types.d.ts +5 -1
  33. package/dist/admin/uploads.js +27 -6
  34. package/dist/blueprints/conditions.d.ts +2 -0
  35. package/dist/blueprints/conditions.js +4 -0
  36. package/dist/blueprints/extends.d.ts +5 -0
  37. package/dist/blueprints/extends.js +76 -0
  38. package/dist/blueprints/files.d.ts +3 -1
  39. package/dist/blueprints/files.js +35 -2
  40. package/dist/blueprints/layout.d.ts +4 -0
  41. package/dist/blueprints/layout.js +12 -0
  42. package/dist/blueprints/load.d.ts +1 -1
  43. package/dist/blueprints/load.js +123 -12
  44. package/dist/blueprints/types.d.ts +35 -1
  45. package/dist/blueprints/validate.js +30 -6
  46. package/dist/cli/cloudflare.js +17 -5
  47. package/dist/cli/doctor.js +6 -3
  48. package/dist/cli/files.js +1 -1
  49. package/dist/cli/scaffold.js +8 -6
  50. package/dist/cli/setup.js +9 -2
  51. package/dist/cli/upgrade.js +2 -1
  52. package/dist/email-failure.d.ts +17 -0
  53. package/dist/email-failure.js +22 -0
  54. package/dist/index.d.ts +2 -1
  55. package/dist/index.js +1 -0
  56. package/dist/link.d.ts +17 -0
  57. package/dist/link.js +44 -0
  58. package/dist/notification-fields.js +1 -1
  59. package/dist/search.d.ts +8 -0
  60. package/dist/search.js +1 -0
  61. package/dist/server/access.d.ts +2 -0
  62. package/dist/server/access.js +59 -23
  63. package/dist/server/admin-load.d.ts +11 -2
  64. package/dist/server/admin-load.js +4 -2
  65. package/dist/server/api-access.d.ts +31 -0
  66. package/dist/server/api-access.js +52 -0
  67. package/dist/server/api-pagination.d.ts +34 -0
  68. package/dist/server/api-pagination.js +87 -0
  69. package/dist/server/api.js +224 -32
  70. package/dist/server/auth.d.ts +1150 -0
  71. package/dist/server/auth.js +11 -1
  72. package/dist/server/cms.d.ts +1210 -4
  73. package/dist/server/cms.js +12 -0
  74. package/dist/server/content.d.ts +17 -2
  75. package/dist/server/content.js +89 -14
  76. package/dist/server/db/auto-migrate.d.ts +12 -0
  77. package/dist/server/db/auto-migrate.js +23 -0
  78. package/dist/server/db/migration-data.js +24 -0
  79. package/dist/server/db/migrations/0001_independent_password_resets.sql +3 -0
  80. package/dist/server/db/migrations/0002_email_failure_reason.sql +1 -0
  81. package/dist/server/db/migrations/0003_direct_r2_uploads.sql +10 -0
  82. package/dist/server/db/migrations/0004_agent_api_keys.sql +38 -0
  83. package/dist/server/db/migrations/0005_api_retention_and_pagination.sql +3 -0
  84. package/dist/server/db/migrations/0006_durable_media_deletion.sql +7 -0
  85. package/dist/server/db/migrations/meta/0001_snapshot.json +1197 -0
  86. package/dist/server/db/migrations/meta/0002_snapshot.json +1204 -0
  87. package/dist/server/db/migrations/meta/0003_snapshot.json +1281 -0
  88. package/dist/server/db/migrations/meta/0004_snapshot.json +1546 -0
  89. package/dist/server/db/migrations/meta/0005_snapshot.json +1572 -0
  90. package/dist/server/db/migrations/meta/0006_snapshot.json +1627 -0
  91. package/dist/server/db/migrations/meta/_journal.json +42 -0
  92. package/dist/server/db/schema.d.ts +742 -2
  93. package/dist/server/db/schema.js +77 -5
  94. package/dist/server/db/store.js +24 -9
  95. package/dist/server/email/index.d.ts +11 -1
  96. package/dist/server/email/index.js +69 -6
  97. package/dist/server/forms.js +12 -2
  98. package/dist/server/hooks.d.ts +1 -1
  99. package/dist/server/hooks.js +37 -14
  100. package/dist/server/index.d.ts +2 -1
  101. package/dist/server/index.js +2 -1
  102. package/dist/server/links.d.ts +5 -0
  103. package/dist/server/links.js +44 -0
  104. package/dist/server/media/deletions.d.ts +2 -0
  105. package/dist/server/media/deletions.js +58 -0
  106. package/dist/server/media/presets.d.ts +10 -2
  107. package/dist/server/media/presets.js +14 -2
  108. package/dist/server/media/runner.d.ts +1 -1
  109. package/dist/server/media/runner.js +105 -8
  110. package/dist/server/media/service.d.ts +41 -3
  111. package/dist/server/media/service.js +146 -33
  112. package/dist/server/notifications.d.ts +1 -0
  113. package/dist/server/notifications.js +4 -2
  114. package/dist/server/request.d.ts +2 -0
  115. package/dist/server/request.js +5 -0
  116. package/dist/server/search.d.ts +13 -0
  117. package/dist/server/search.js +97 -0
  118. package/dist/worker/index.d.ts +4 -4
  119. package/dist/worker/index.js +208 -67
  120. package/dist/worker/local.d.ts +5 -0
  121. package/dist/worker/local.js +57 -0
  122. package/dist/worker/source.d.ts +1 -1
  123. package/dist/worker/source.js +2 -2
  124. package/dist/worker/uploads.d.ts +22 -0
  125. package/dist/worker/uploads.js +48 -0
  126. package/docs/api.md +73 -0
  127. package/docs/cloudflare.md +37 -10
  128. package/docs/content.md +162 -4
  129. package/docs/deployment.md +33 -4
  130. package/docs/email.md +11 -7
  131. package/docs/forms.md +3 -1
  132. package/docs/media.md +33 -4
  133. package/docs/package.md +6 -4
  134. package/docs/releases.md +54 -1
  135. package/docs/upgrades.md +91 -3
  136. package/package.json +19 -10
  137. package/templates/hooks.server.ts +2 -2
  138. package/templates/integration.ts +3 -2
  139. package/templates/routes/admin/+page.server.ts +1 -1
  140. package/templates/routes/api/+server.ts +1 -1
  141. package/templates/sandcms/blueprints/collections/projects.yaml +16 -8
  142. package/templates/sandcms/blueprints/fields/seo.yaml +5 -0
  143. package/templates/sandcms/blueprints/files/image.yaml +1 -0
  144. package/templates/sandcms/blueprints/pages/home.yaml +1 -0
  145. package/templates/sandcms/config.yaml +1 -0
  146. package/templates/sandcms/worker/local.ts +1 -0
  147. package/templates/sandcms/worker/wrangler.jsonc +1 -2
@@ -1,3 +1,4 @@
1
+ import { sql } from 'drizzle-orm';
1
2
  import { sqliteTable, text, integer, index, uniqueIndex, blob } from 'drizzle-orm/sqlite-core';
2
3
  const timestamp = (name) => integer(name, { mode: 'timestamp_ms' });
3
4
  export const user = sqliteTable('user', {
@@ -62,6 +63,47 @@ export const twoFactor = sqliteTable('twoFactor', {
62
63
  failedVerificationCount: integer().default(0),
63
64
  lockedUntil: timestamp('lockedUntil')
64
65
  }, (t) => [index('twofactor_user').on(t.userId), index('twofactor_secret').on(t.secret)]);
66
+ // Better Auth API Key plugin storage. Secrets are hashed by the plugin.
67
+ export const apikey = sqliteTable('apikey', {
68
+ id: text().primaryKey(),
69
+ configId: text().notNull().default('default'),
70
+ name: text(),
71
+ start: text(),
72
+ prefix: text(),
73
+ key: text().notNull(),
74
+ referenceId: text()
75
+ .notNull()
76
+ .references(() => user.id, { onDelete: 'cascade' }),
77
+ refillInterval: integer(),
78
+ refillAmount: integer(),
79
+ lastRefillAt: timestamp('lastRefillAt'),
80
+ enabled: integer({ mode: 'boolean' }).default(true),
81
+ rateLimitEnabled: integer({ mode: 'boolean' }).default(true),
82
+ rateLimitTimeWindow: integer().default(60000),
83
+ rateLimitMax: integer().default(120),
84
+ requestCount: integer().default(0),
85
+ remaining: integer(),
86
+ lastRequest: timestamp('lastRequest'),
87
+ expiresAt: timestamp('expiresAt'),
88
+ createdAt: timestamp('createdAt').notNull(),
89
+ updatedAt: timestamp('updatedAt').notNull(),
90
+ permissions: text(),
91
+ metadata: text()
92
+ }, (t) => [
93
+ index('apikey_owner').on(t.referenceId),
94
+ index('apikey_config').on(t.configId),
95
+ uniqueIndex('apikey_hash').on(t.key)
96
+ ]);
97
+ // Successful content mutations and their responses commit in the same transaction.
98
+ export const apiRequests = sqliteTable('api_requests', {
99
+ id: text().primaryKey(),
100
+ userId: text()
101
+ .notNull()
102
+ .references(() => user.id, { onDelete: 'cascade' }),
103
+ fingerprint: text().notNull(),
104
+ response: text({ mode: 'json' }).$type().notNull(),
105
+ createdAt: integer().notNull()
106
+ }, (t) => [index('api_requests_created').on(t.createdAt)]);
65
107
  export const documents = sqliteTable('documents', {
66
108
  id: text().primaryKey(),
67
109
  blueprint: text().notNull(),
@@ -77,7 +119,8 @@ export const documents = sqliteTable('documents', {
77
119
  }, (t) => [
78
120
  uniqueIndex('draft_slug').on(t.blueprint, t.draftSlug),
79
121
  uniqueIndex('published_slug').on(t.blueprint, t.publishedSlug),
80
- index('documents_blueprint').on(t.blueprint)
122
+ index('documents_blueprint').on(t.blueprint),
123
+ index('documents_api_page').on(t.blueprint, t.updatedAt, t.id)
81
124
  ]);
82
125
  export const references = sqliteTable('content_references', {
83
126
  id: text().primaryKey(),
@@ -95,13 +138,13 @@ export const media = sqliteTable('media', {
95
138
  filename: text().notNull(),
96
139
  mime: text().notNull(),
97
140
  bytes: integer().notNull(),
98
- status: text({ enum: ['processing', 'ready', 'failed'] }).notNull(),
141
+ status: text({ enum: ['processing', 'ready', 'failed', 'deleting'] }).notNull(),
99
142
  activeVersion: text(),
100
143
  targetVersion: text().notNull(),
101
144
  variants: text({ mode: 'json' }).$type().notNull().default([]),
102
145
  error: text(),
103
146
  createdAt: integer().notNull()
104
- });
147
+ }, (t) => [index('media_api_page').on(t.createdAt, t.id)]);
105
148
  export const jobs = sqliteTable('jobs', {
106
149
  id: text().primaryKey(),
107
150
  mediaId: text()
@@ -141,7 +184,7 @@ export const audit = sqliteTable('audit', {
141
184
  detail: text({ mode: 'json' }).$type().notNull(),
142
185
  createdAt: integer().notNull()
143
186
  });
144
- // Temporary durable upload spool; removed after the Worker confirms the private original.
187
+ // Legacy durable spool retained for pending uploads from earlier releases. New uploads use R2.
145
188
  export const uploads = sqliteTable('uploads', {
146
189
  mediaId: text()
147
190
  .primaryKey()
@@ -163,9 +206,38 @@ export const accessLinks = sqliteTable('access_links', {
163
206
  credentialHash: text(),
164
207
  expiresAt: integer().notNull(),
165
208
  status: text({ enum: ['sending', 'accepted', 'failed'] }).notNull(),
209
+ failureReason: text().$type(),
166
210
  createdAt: integer().notNull()
167
- }, (t) => [uniqueIndex('access_link_recipient').on(t.kind, t.email)]);
211
+ }, (t) => [
212
+ index('access_link_recipient').on(t.kind, t.email),
213
+ uniqueIndex('access_invite_recipient')
214
+ .on(t.kind, t.email)
215
+ .where(sql `${t.kind} = 'invite'`)
216
+ ]);
168
217
  export const formNotifications = sqliteTable('form_notifications', {
169
218
  formId: text().primaryKey(),
170
219
  settings: text({ mode: 'json' }).$type().notNull()
171
220
  });
221
+ // Metadata only: browser transfers go directly to private R2 staging.
222
+ export const uploadSessions = sqliteTable('upload_sessions', {
223
+ mediaId: text()
224
+ .primaryKey()
225
+ .references(() => media.id, { onDelete: 'cascade' }),
226
+ attempt: text().notNull(),
227
+ expiresAt: integer().notNull(),
228
+ status: text({ enum: ['uploading', 'pending', 'expired'] })
229
+ .notNull()
230
+ .default('uploading'),
231
+ attempts: integer().notNull().default(0),
232
+ nextAttempt: integer().notNull().default(0),
233
+ leaseUntil: integer().notNull().default(0)
234
+ });
235
+ // Retain deletion intent until storage cleanup succeeds, including across restarts.
236
+ export const mediaDeletions = sqliteTable('media_deletions', {
237
+ mediaId: text()
238
+ .primaryKey()
239
+ .references(() => media.id, { onDelete: 'cascade' }),
240
+ attempts: integer().notNull().default(0),
241
+ nextAttempt: integer().notNull().default(0),
242
+ leaseUntil: integer().notNull().default(0)
243
+ });
@@ -71,15 +71,19 @@ export function openStore(path, { migrate = false, guard = true } = {}) {
71
71
  }
72
72
  }
73
73
  export function pendingMigrations(store) {
74
- const version = store.sqlite.query('PRAGMA user_version').get();
75
- if (version.user_version > SCHEMA_VERSION)
76
- throw new Error(`Database schema is incompatible with this package. ${resetGuidance}`);
77
- const exists = store.sqlite
78
- .query("SELECT name FROM sqlite_master WHERE name='schema_migrations'")
74
+ // Each statement reads one snapshot, so a concurrent migration cannot mix version and history.
75
+ const state = store.sqlite
76
+ .query("SELECT user_version, EXISTS (SELECT 1 FROM sqlite_master WHERE name='schema_migrations') AS tracked FROM pragma_user_version")
79
77
  .get();
80
- const applied = exists
81
- ? store.sqlite.query('SELECT name, hash FROM schema_migrations ORDER BY name').all()
78
+ const rows = state.tracked
79
+ ? store.sqlite
80
+ .query('SELECT NULL AS name, NULL AS hash, user_version FROM pragma_user_version UNION ALL SELECT name, hash, NULL FROM schema_migrations ORDER BY name')
81
+ .all()
82
82
  : [];
83
+ const version = { user_version: rows[0]?.user_version ?? state.user_version };
84
+ const applied = rows.slice(1);
85
+ if (version.user_version > SCHEMA_VERSION)
86
+ throw new Error(`Database schema is incompatible with this package. ${resetGuidance}`);
83
87
  const available = migrations();
84
88
  for (const old of applied) {
85
89
  const m = available.find((m) => m.name === old.name);
@@ -101,16 +105,27 @@ export function applyMigrations(store) {
101
105
  const completed = [];
102
106
  for (const m of pending) {
103
107
  try {
104
- store.sqlite
108
+ const applied = store.sqlite
105
109
  .transaction(() => {
110
+ // Another process starting concurrently may have applied it after the pending check.
111
+ const recorded = store.sqlite
112
+ .query('SELECT hash FROM schema_migrations WHERE name = ?')
113
+ .get(m.name);
114
+ if (recorded) {
115
+ if (recorded.hash !== m.hash)
116
+ throw new Error(`Incompatible or modified migration ${m.name}. ${resetGuidance}`);
117
+ return false;
118
+ }
106
119
  store.sqlite.exec(m.sql);
107
120
  store.sqlite
108
121
  .query('INSERT INTO schema_migrations VALUES (?, ?, ?)')
109
122
  .run(m.name, m.hash, Date.now());
110
123
  store.sqlite.exec(`PRAGMA user_version=${migrations().findIndex((item) => item.name === m.name) + 1}`);
124
+ return true;
111
125
  })
112
126
  .immediate();
113
- completed.push(m.name);
127
+ if (applied)
128
+ completed.push(m.name);
114
129
  }
115
130
  catch (cause) {
116
131
  throw new Error(`Migration ${m.name} failed. Applied in this run: ${completed.join(', ') || 'none'}. ${String(cause)}`, { cause });
@@ -1,3 +1,5 @@
1
+ import { type EmailFailureReason } from '../../email-failure.js';
2
+ export { emailFailureMessage, type EmailFailureReason } from '../../email-failure.js';
1
3
  export interface EmailMessage {
2
4
  /** One bare email address. */
3
5
  to: string;
@@ -28,6 +30,8 @@ export interface SmtpOptions {
28
30
  export type EmailOptions = {
29
31
  from: string;
30
32
  replyTo?: string;
33
+ /** Maximum sends waiting in memory, excluding the two active sends. Defaults to 100. */
34
+ maxPendingSends?: number;
31
35
  } & ({
32
36
  smtp: SmtpOptions;
33
37
  adapter?: never;
@@ -38,10 +42,16 @@ export type EmailOptions = {
38
42
  export type EmailErrorCode = 'NOT_CONFIGURED' | 'CONFIGURATION' | 'INVALID_MESSAGE' | 'SEND_FAILED';
39
43
  export declare class EmailError extends Error {
40
44
  readonly code: EmailErrorCode;
41
- constructor(code: EmailErrorCode, message: string);
45
+ readonly reason?: EmailFailureReason | undefined;
46
+ constructor(code: EmailErrorCode, message: string, reason?: EmailFailureReason | undefined);
42
47
  }
48
+ /** Normalize typed failures without retaining arbitrary adapter messages or causes. */
49
+ export declare function emailFailureReason(error: unknown): EmailFailureReason;
50
+ /** Classify Nodemailer metadata only; raw messages and SMTP responses are discarded. */
51
+ export declare function smtpFailureReason(error: unknown): EmailFailureReason;
43
52
  export declare function address(value: unknown, displayName?: boolean): value is string;
44
53
  export declare function createSmtpAdapter(options: SmtpOptions): EmailAdapter;
54
+ /** Create an email service with two active sends and a bounded FIFO waiting queue. */
45
55
  export declare function createEmail(options?: EmailOptions): {
46
56
  enabled: boolean;
47
57
  send(message: EmailMessage): Promise<EmailResult>;
@@ -1,12 +1,53 @@
1
1
  import nodemailer from 'nodemailer';
2
+ import { safeEmailFailureReason } from '../../email-failure.js';
3
+ export { emailFailureMessage } from '../../email-failure.js';
2
4
  export class EmailError extends Error {
3
5
  code;
4
- constructor(code, message) {
6
+ reason;
7
+ constructor(code, message, reason) {
5
8
  super(message);
6
9
  this.code = code;
10
+ this.reason = reason;
7
11
  this.name = 'EmailError';
8
12
  }
9
13
  }
14
+ /** Normalize typed failures without retaining arbitrary adapter messages or causes. */
15
+ export function emailFailureReason(error) {
16
+ if (!(error instanceof EmailError))
17
+ return 'unknown';
18
+ if (error.reason !== undefined)
19
+ return safeEmailFailureReason(error.reason);
20
+ return safeEmailFailureReason({
21
+ NOT_CONFIGURED: 'not_configured',
22
+ CONFIGURATION: 'configuration',
23
+ INVALID_MESSAGE: 'invalid_message',
24
+ SEND_FAILED: 'unknown'
25
+ }[error.code]);
26
+ }
27
+ /** Classify Nodemailer metadata only; raw messages and SMTP responses are discarded. */
28
+ export function smtpFailureReason(error) {
29
+ if (!error || typeof error !== 'object')
30
+ return 'unknown';
31
+ const { code, command } = error;
32
+ if (code === 'ETIMEDOUT')
33
+ return 'timeout';
34
+ if (code === 'EDNS' || code === 'ENOTFOUND' || code === 'EAI_AGAIN')
35
+ return 'dns';
36
+ if (code === 'EAUTH')
37
+ return 'authentication';
38
+ if (code === 'ETLS' || (code === 'ESOCKET' && command === 'STARTTLS'))
39
+ return 'tls';
40
+ if (code === 'EENVELOPE' && command === 'RCPT TO')
41
+ return 'recipient_rejected';
42
+ if (code === 'EENVELOPE' || code === 'EMESSAGE')
43
+ return 'message_rejected';
44
+ if (code === 'ECONNECTION' ||
45
+ code === 'ECONNREFUSED' ||
46
+ code === 'ECONNRESET' ||
47
+ code === 'ESOCKET')
48
+ return 'connection';
49
+ return 'unknown';
50
+ }
10
51
  const controls = /[\x00-\x1f\x7f]/;
11
52
  const mailbox = /^[^\s@<>(),;:"\\]+@[^\s@<>(),;:"\\]+\.[^\s@<>(),;:"\\]+$/;
12
53
  export function address(value, displayName = false) {
@@ -75,17 +116,21 @@ export function createSmtpAdapter(options) {
75
116
  replyTo: message.replyTo
76
117
  });
77
118
  if (result.accepted.length !== 1 || result.rejected.length || !result.messageId)
78
- throw new Error('SMTP did not accept the recipient');
119
+ throw new EmailError('SEND_FAILED', 'Email could not be sent', 'recipient_rejected');
79
120
  return { accepted: true, messageId: result.messageId };
80
121
  }
81
- catch {
122
+ catch (error) {
82
123
  // SMTP responses and errors may contain credentials, recipients or message content.
83
- throw new EmailError('SEND_FAILED', 'Email could not be sent');
124
+ throw new EmailError('SEND_FAILED', 'Email could not be sent', error instanceof EmailError ? emailFailureReason(error) : smtpFailureReason(error));
84
125
  }
85
126
  }
86
127
  };
87
128
  }
129
+ /** Create an email service with two active sends and a bounded FIFO waiting queue. */
88
130
  export function createEmail(options) {
131
+ const maxPendingSends = options?.maxPendingSends ?? 100;
132
+ if (!Number.isSafeInteger(maxPendingSends) || maxPendingSends < 0)
133
+ configuration('maxPendingSends must be a non-negative safe integer');
89
134
  let adapter;
90
135
  if (options) {
91
136
  if (!address(options.from, true))
@@ -100,6 +145,10 @@ export function createEmail(options) {
100
145
  }
101
146
  const from = options?.from;
102
147
  const defaultReplyTo = options?.replyTo;
148
+ // Share the limit across recipients and workflows using this email service,
149
+ // including custom adapters. Waiting sends live only in process memory.
150
+ let active = 0;
151
+ const waiting = [];
103
152
  return {
104
153
  enabled: !!adapter,
105
154
  async send(message) {
@@ -116,6 +165,13 @@ export function createEmail(options) {
116
165
  (message.html !== undefined && typeof message.html !== 'string') ||
117
166
  (message.replyTo !== undefined && !address(message.replyTo)))
118
167
  throw new EmailError('INVALID_MESSAGE', 'Invalid email recipient, subject, body or reply-to');
168
+ if (active >= 2) {
169
+ if (waiting.length >= maxPendingSends)
170
+ throw new EmailError('SEND_FAILED', 'Email waiting queue is full');
171
+ await new Promise((resolve) => waiting.push(resolve));
172
+ }
173
+ else
174
+ active++;
119
175
  try {
120
176
  const result = await adapter.send({
121
177
  from: from,
@@ -129,8 +185,15 @@ export function createEmail(options) {
129
185
  throw new Error('Invalid adapter result');
130
186
  return { accepted: true, messageId: result.messageId };
131
187
  }
132
- catch {
133
- throw new EmailError('SEND_FAILED', 'Email could not be sent');
188
+ catch (error) {
189
+ throw new EmailError('SEND_FAILED', 'Email could not be sent', emailFailureReason(error));
190
+ }
191
+ finally {
192
+ const next = waiting.shift();
193
+ if (next)
194
+ next();
195
+ else
196
+ active--;
134
197
  }
135
198
  }
136
199
  };
@@ -40,8 +40,14 @@ export function createForms(store, definition, notify) {
40
40
  createdAt: Date.now()
41
41
  })
42
42
  .run();
43
+ // Notification delivery is best effort; storage determines submission success.
43
44
  if (notify)
44
- await notify(id);
45
+ void Promise.resolve()
46
+ .then(() => notify(id))
47
+ .catch(() => {
48
+ // Do not expose provider errors, recipients or submitted content in logs.
49
+ console.error('Form notification failed', { submissionId: id });
50
+ });
45
51
  return { accepted: true };
46
52
  },
47
53
  list: (formId) => store.db
@@ -79,6 +85,10 @@ function csvValue(v) {
79
85
  return v === undefined || v === null ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v);
80
86
  }
81
87
  export function csvCell(value) {
82
- const safe = /^[\s\u0000-\u001f]*[=+\-@]/.test(value) || /^[\t\r\n]/.test(value) ? "'" + value : value;
88
+ // Require the entire cell to be numeric, including no trailing line break.
89
+ const numeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?(?![\s\S])/.test(value);
90
+ const safe = !numeric && (/^[\s\u0000-\u001f]*[=+\-@]/.test(value) || /^[\t\r\n]/.test(value))
91
+ ? "'" + value
92
+ : value;
83
93
  return '"' + safe.replaceAll('"', '""') + '"';
84
94
  }
@@ -1,3 +1,3 @@
1
- import { type Handle } from '@sveltejs/kit';
1
+ import type { Handle } from '@sveltejs/kit/hooks';
2
2
  import type { CMS } from './cms.js';
3
3
  export declare function cmsHandle(getCMS: () => CMS, building?: boolean): Handle;
@@ -2,9 +2,10 @@ import { error } from '@sveltejs/kit';
2
2
  import { svelteKitHandler } from 'better-auth/svelte-kit';
3
3
  import { eq } from 'drizzle-orm';
4
4
  import { createHash } from 'node:crypto';
5
- import { user } from './db/schema.js';
5
+ import { user, apikey, audit } from './db/schema.js';
6
6
  import { rateLimit } from './forms.js';
7
- import { boundedJson } from './request.js';
7
+ import { boundedJson, clientAddress } from './request.js';
8
+ import { apiKeyRoute } from './api-access.js';
8
9
  import { mediaDelivery } from './media/delivery.js';
9
10
  const authPaths = new Set([
10
11
  '/sign-in/email',
@@ -25,8 +26,16 @@ export function cmsHandle(getCMS, building = false) {
25
26
  const cms = getCMS(), path = event.url.pathname, isCms = path === '/admin' || path.startsWith('/admin/') || path.startsWith('/api/cms/');
26
27
  if (isCms &&
27
28
  !['GET', 'HEAD', 'OPTIONS'].includes(event.request.method) &&
28
- event.request.headers.get('origin') !== cms.options.origin)
29
+ event.request.headers.get('origin') !== cms.options.origin &&
30
+ !(event.request.headers.has('x-api-key') &&
31
+ path.startsWith('/api/cms/') &&
32
+ apiKeyRoute(path.slice('/api/cms/'.length), event.request.method)))
29
33
  error(403, 'Invalid request origin');
34
+ if (isCms &&
35
+ event.request.headers.has('x-api-key') &&
36
+ !(path.startsWith('/api/cms/') &&
37
+ apiKeyRoute(path.slice('/api/cms/'.length), event.request.method)))
38
+ error(403, 'API keys can only access content and media');
30
39
  if (cms.seo && (path === '/robots.txt' || path === '/sitemap.xml')) {
31
40
  if (!['GET', 'HEAD'].includes(event.request.method))
32
41
  return new Response(null, { status: 405, headers: { allow: 'GET, HEAD' } });
@@ -40,7 +49,9 @@ export function cmsHandle(getCMS, building = false) {
40
49
  }
41
50
  if (path.startsWith('/_sandcms/media/'))
42
51
  return mediaDelivery(cms, event, false);
43
- if (path.startsWith('/api/cms/media/') && ['GET', 'HEAD'].includes(event.request.method))
52
+ if (path.startsWith('/api/cms/media/') &&
53
+ path !== '/api/cms/media/list' &&
54
+ ['GET', 'HEAD'].includes(event.request.method))
44
55
  return mediaDelivery(cms, event, true);
45
56
  if (path.startsWith('/api/cms/auth/')) {
46
57
  const endpoint = path.slice('/api/cms/auth'.length);
@@ -49,10 +60,7 @@ export function cmsHandle(getCMS, building = false) {
49
60
  if (endpoint === '/sign-in/email') {
50
61
  const body = await boundedJson(event.request.clone(), 8192);
51
62
  const email = typeof body.email === 'string' ? body.email.toLowerCase() : '';
52
- // Header-derived addresses are used only when the deployment explicitly opts in.
53
- const client = cms.options.trustedProxyHeader
54
- ? (event.request.headers.get(cms.options.trustedProxyHeader) ?? 'unknown')
55
- : event.getClientAddress();
63
+ const client = clientAddress(event, cms.options.trustedProxyHeader);
56
64
  try {
57
65
  rateLimit(cms.store, 'login-ip:' + createHash('sha256').update(client).digest('hex'), 40);
58
66
  rateLimit(cms.store, 'login-email:' + createHash('sha256').update(email).digest('hex'), 8);
@@ -66,18 +74,33 @@ export function cmsHandle(getCMS, building = false) {
66
74
  : null;
67
75
  const response = await svelteKitHandler({ event, resolve, auth: cms.auth, building });
68
76
  if (endpoint === '/change-password' && response.ok && current)
69
- cms.store.db
70
- .update(user)
71
- .set({ mustChangePassword: false })
72
- .where(eq(user.id, current.user.id))
73
- .run();
77
+ cms.store.db.transaction((tx) => {
78
+ tx.update(user)
79
+ .set({ mustChangePassword: false })
80
+ .where(eq(user.id, current.user.id))
81
+ .run();
82
+ const revoked = tx
83
+ .delete(apikey)
84
+ .where(eq(apikey.referenceId, current.user.id))
85
+ .returning({ id: apikey.id })
86
+ .all();
87
+ tx.insert(audit)
88
+ .values({
89
+ id: crypto.randomUUID(),
90
+ actor: current.user.id,
91
+ action: 'password.change',
92
+ detail: { revokedKeys: revoked.length },
93
+ createdAt: Date.now()
94
+ })
95
+ .run();
96
+ });
74
97
  response.headers.set('cache-control', 'private, no-store');
75
98
  return response;
76
99
  }
77
100
  const response = await resolve(event);
78
101
  if (isCms || event.url.searchParams.has('cmsPreview')) {
79
102
  response.headers.set('cache-control', 'private, no-store');
80
- response.headers.set('vary', 'Cookie');
103
+ response.headers.set('vary', 'Cookie, x-api-key');
81
104
  response.headers.set('x-robots-tag', 'noindex, nofollow');
82
105
  }
83
106
  return response;
@@ -2,7 +2,8 @@ export { createCMS, type CMS, type CmsOptions } from './cms.js';
2
2
  export { cmsHandle, adminLoad, apiHandler } from './http.js';
3
3
  export { createUser, recoverUser } from './auth.js';
4
4
  export { openStore, applyMigrations, pendingMigrations } from './db/store.js';
5
+ export { autoMigrate } from './db/auto-migrate.js';
5
6
  export { loadDefinition } from '../blueprints/load.js';
6
7
  export { honeypotName } from './forms.js';
7
- export { createEmail, createSmtpAdapter, emailOptionsFromEnv, EmailError, type EmailMessage, type EmailResult, type EmailAdapter, type EmailOptions, type SmtpOptions, type EmailErrorCode } from './email/index.js';
8
+ export { createEmail, createSmtpAdapter, emailOptionsFromEnv, EmailError, type EmailMessage, type EmailResult, type EmailAdapter, type EmailOptions, type SmtpOptions, emailFailureMessage, type EmailFailureReason, type EmailErrorCode } from './email/index.js';
8
9
  export type { SeoOptions } from './seo.js';
@@ -2,6 +2,7 @@ export { createCMS } from './cms.js';
2
2
  export { cmsHandle, adminLoad, apiHandler } from './http.js';
3
3
  export { createUser, recoverUser } from './auth.js';
4
4
  export { openStore, applyMigrations, pendingMigrations } from './db/store.js';
5
+ export { autoMigrate } from './db/auto-migrate.js';
5
6
  export { loadDefinition } from '../blueprints/load.js';
6
7
  export { honeypotName } from './forms.js';
7
- export { createEmail, createSmtpAdapter, emailOptionsFromEnv, EmailError } from './email/index.js';
8
+ export { createEmail, createSmtpAdapter, emailOptionsFromEnv, EmailError, emailFailureMessage } from './email/index.js';
@@ -0,0 +1,5 @@
1
+ import { type ResolvedLink } from '../link.js';
2
+ import type { SiteDefinition } from '../blueprints/types.js';
3
+ import type { Content } from './content.js';
4
+ import type { PublicMedia } from '../media.js';
5
+ export declare function createLinkResolver(definition: SiteDefinition, content: Content, publicAsset: (id: string) => PublicMedia | null, routes?: Record<string, string>): (value: unknown) => ResolvedLink | null;
@@ -0,0 +1,44 @@
1
+ import { isLinkValue, linkHref } from '../link.js';
2
+ export function createLinkResolver(definition, content, publicAsset, routes = {}) {
3
+ return (value) => {
4
+ if (!isLinkValue(value) || !value.value)
5
+ return null;
6
+ let href = null;
7
+ let label = value.value;
8
+ if (value.type === 'entry') {
9
+ const entry = content.get(value.value);
10
+ if (!entry?.published)
11
+ return null;
12
+ const blueprint = definition.blueprints.find((b) => b.id === entry.blueprint);
13
+ const route = routes[entry.blueprint] ?? blueprint?.preview;
14
+ if (!route)
15
+ return null;
16
+ let missing = false;
17
+ const path = route.replace(/\{([^}]+)\}/g, (_, key) => {
18
+ const part = key === 'id' ? entry.id : entry.published[key];
19
+ if (typeof part !== 'string' || !part || part === '.' || part === '..')
20
+ missing = true;
21
+ return encodeURIComponent(String(part ?? ''));
22
+ });
23
+ if (missing || !/^\/(?!\/)/.test(path))
24
+ return null;
25
+ href = linkHref('url', path);
26
+ label = String(entry.published.title ?? blueprint?.label ?? label);
27
+ }
28
+ else if (value.type === 'file') {
29
+ const asset = publicAsset(value.value);
30
+ const variant = asset?.variants.slice().sort((a, b) => b.width - a.width)[0];
31
+ href = variant ? linkHref('url', variant.url) : null;
32
+ label = asset?.alt || label;
33
+ }
34
+ else
35
+ href = linkHref(value.type, value.value);
36
+ if (!href)
37
+ return null;
38
+ return {
39
+ href,
40
+ label: value.label || label,
41
+ ...(value.newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {})
42
+ };
43
+ };
44
+ }
@@ -0,0 +1,2 @@
1
+ import type { Store } from '../db/store.js';
2
+ export declare function createDeletionRunner(store: Store, worker: (path: string, init?: RequestInit) => Promise<Response>): (id?: string) => Promise<boolean>;
@@ -0,0 +1,58 @@
1
+ import { and, eq, gt, lte, notExists } from 'drizzle-orm';
2
+ import { jobs, media, mediaDeletions, uploads, uploadSessions } from '../db/schema.js';
3
+ export function createDeletionRunner(store, worker) {
4
+ const { db } = store;
5
+ return async (id) => {
6
+ const now = Date.now();
7
+ const deletion = db.transaction(() => {
8
+ const pending = db
9
+ .select()
10
+ .from(mediaDeletions)
11
+ .where(and(id === undefined ? undefined : eq(mediaDeletions.mediaId, id), lte(mediaDeletions.nextAttempt, now), lte(mediaDeletions.leaseUntil, now),
12
+ // A remote write already in progress must finish before its objects are removed.
13
+ notExists(db
14
+ .select()
15
+ .from(jobs)
16
+ .where(and(eq(jobs.mediaId, mediaDeletions.mediaId), gt(jobs.leaseUntil, now)))), notExists(db
17
+ .select()
18
+ .from(uploads)
19
+ .where(and(eq(uploads.mediaId, mediaDeletions.mediaId), gt(uploads.leaseUntil, now)))), notExists(db
20
+ .select()
21
+ .from(uploadSessions)
22
+ .where(and(eq(uploadSessions.mediaId, mediaDeletions.mediaId), gt(uploadSessions.leaseUntil, now))))))
23
+ .get();
24
+ if (!pending)
25
+ return null;
26
+ db.update(mediaDeletions)
27
+ .set({ leaseUntil: now + 90_000, attempts: pending.attempts + 1 })
28
+ .where(eq(mediaDeletions.mediaId, pending.mediaId))
29
+ .run();
30
+ return pending;
31
+ });
32
+ if (!deletion)
33
+ return false;
34
+ try {
35
+ await worker('assets/' + deletion.mediaId, { method: 'DELETE' });
36
+ // Cascades remove the queue entry and processing records only after storage succeeds.
37
+ db.delete(media)
38
+ .where(and(eq(media.id, deletion.mediaId), eq(media.status, 'deleting')))
39
+ .run();
40
+ }
41
+ catch {
42
+ db.transaction(() => {
43
+ db.update(mediaDeletions)
44
+ .set({
45
+ leaseUntil: 0,
46
+ nextAttempt: Date.now() + Math.min(60_000, 2 ** Math.min(deletion.attempts, 5) * 2000)
47
+ })
48
+ .where(eq(mediaDeletions.mediaId, deletion.mediaId))
49
+ .run();
50
+ db.update(media)
51
+ .set({ error: 'Deletion pending. Storage cleanup will retry automatically.' })
52
+ .where(and(eq(media.id, deletion.mediaId), eq(media.status, 'deleting')))
53
+ .run();
54
+ });
55
+ }
56
+ return true;
57
+ };
58
+ }
@@ -1,2 +1,10 @@
1
- import type { SiteDefinition } from '../../blueprints/types.js';
2
- export declare function presetVersion(definition: SiteDefinition): string;
1
+ import type { Payload, SiteDefinition } from '../../blueprints/types.js';
2
+ export declare function presetVersion(definition: SiteDefinition, focus?: {
3
+ x: number;
4
+ y: number;
5
+ }): string;
6
+ export declare function assetPresetVersion(definition: SiteDefinition, asset: {
7
+ mime: string;
8
+ blueprint: string;
9
+ metadata: Payload;
10
+ }): string;
@@ -1,8 +1,20 @@
1
1
  import { createHash } from 'node:crypto';
2
- export function presetVersion(definition) {
2
+ import { fileFocus, getFileBlueprint } from '../../blueprints/files.js';
3
+ export function presetVersion(definition, focus) {
3
4
  return createHash('sha256')
4
- .update('remote-transform-v1:')
5
+ .update('remote-transform-v2:')
6
+ .update(focus ? JSON.stringify(focus) : '')
7
+ .update(JSON.stringify((definition.fileBlueprints ?? [])
8
+ .filter((b) => Object.values(b.fields).some((f) => f.type === 'focus'))
9
+ .map((b) => b.id)
10
+ .sort()))
5
11
  .update(JSON.stringify(definition.config.media.presets))
6
12
  .digest('hex')
7
13
  .slice(0, 16);
8
14
  }
15
+ export function assetPresetVersion(definition, asset) {
16
+ return presetVersion(definition, asset.mime !== 'image/svg+xml' &&
17
+ Object.values(definition.config.media.presets).some((p) => p.aspectRatio)
18
+ ? fileFocus(getFileBlueprint(definition, asset.blueprint), asset.metadata)
19
+ : undefined);
20
+ }
@@ -1,2 +1,2 @@
1
1
  import type { Store } from '../db/store.js';
2
- export declare function createRunner(store: Store, worker: (path: string, init?: RequestInit) => Promise<Response>, enqueue: (id: string, mime: string) => void): () => Promise<boolean>;
2
+ export declare function createRunner(store: Store, worker: (path: string, init?: RequestInit) => Promise<Response>, enqueue: (id: string, mime: string) => void, deletePending: () => Promise<boolean>): () => Promise<boolean>;