sandcms 0.5.2 → 0.6.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 (151) hide show
  1. package/README.md +6 -4
  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/Navigation.svelte +62 -0
  23. package/dist/admin/Navigation.svelte.d.ts +7 -0
  24. package/dist/admin/NotificationSettings.svelte +2 -2
  25. package/dist/admin/SearchList.svelte +55 -0
  26. package/dist/admin/SearchList.svelte.d.ts +42 -0
  27. package/dist/admin/SelectField.svelte +3 -1
  28. package/dist/admin/SelectField.svelte.d.ts +1 -0
  29. package/dist/admin/Shell.svelte +16 -24
  30. package/dist/admin/UnsavedChanges.svelte +1 -1
  31. package/dist/admin/Users.svelte +11 -5
  32. package/dist/admin/client.js +2 -1
  33. package/dist/admin/generated/admin.css +145 -0
  34. package/dist/admin/navigation.d.ts +7 -0
  35. package/dist/admin/navigation.js +25 -0
  36. package/dist/admin/types.d.ts +5 -1
  37. package/dist/admin/uploads.js +27 -6
  38. package/dist/blueprints/conditions.d.ts +2 -0
  39. package/dist/blueprints/conditions.js +4 -0
  40. package/dist/blueprints/extends.d.ts +5 -0
  41. package/dist/blueprints/extends.js +76 -0
  42. package/dist/blueprints/files.d.ts +3 -1
  43. package/dist/blueprints/files.js +35 -2
  44. package/dist/blueprints/layout.d.ts +4 -0
  45. package/dist/blueprints/layout.js +12 -0
  46. package/dist/blueprints/load.d.ts +1 -1
  47. package/dist/blueprints/load.js +127 -12
  48. package/dist/blueprints/types.d.ts +38 -1
  49. package/dist/blueprints/validate.js +30 -6
  50. package/dist/cli/cloudflare.js +15 -3
  51. package/dist/cli/doctor.js +6 -3
  52. package/dist/cli/files.js +1 -1
  53. package/dist/cli/scaffold.js +8 -6
  54. package/dist/cli/setup.js +9 -2
  55. package/dist/cli/upgrade.js +2 -1
  56. package/dist/email-failure.d.ts +17 -0
  57. package/dist/email-failure.js +22 -0
  58. package/dist/index.d.ts +2 -1
  59. package/dist/index.js +1 -0
  60. package/dist/link.d.ts +17 -0
  61. package/dist/link.js +44 -0
  62. package/dist/notification-fields.js +1 -1
  63. package/dist/search.d.ts +8 -0
  64. package/dist/search.js +1 -0
  65. package/dist/server/access.d.ts +2 -0
  66. package/dist/server/access.js +59 -23
  67. package/dist/server/admin-load.d.ts +29 -2
  68. package/dist/server/admin-load.js +4 -2
  69. package/dist/server/api-access.d.ts +31 -0
  70. package/dist/server/api-access.js +52 -0
  71. package/dist/server/api-pagination.d.ts +34 -0
  72. package/dist/server/api-pagination.js +87 -0
  73. package/dist/server/api.js +224 -32
  74. package/dist/server/auth.d.ts +1150 -0
  75. package/dist/server/auth.js +11 -1
  76. package/dist/server/cms.d.ts +1208 -4
  77. package/dist/server/cms.js +2 -0
  78. package/dist/server/content.d.ts +17 -2
  79. package/dist/server/content.js +89 -14
  80. package/dist/server/db/migration-data.js +24 -0
  81. package/dist/server/db/migrations/0001_independent_password_resets.sql +3 -0
  82. package/dist/server/db/migrations/0002_email_failure_reason.sql +1 -0
  83. package/dist/server/db/migrations/0003_direct_r2_uploads.sql +10 -0
  84. package/dist/server/db/migrations/0004_agent_api_keys.sql +38 -0
  85. package/dist/server/db/migrations/0005_api_retention_and_pagination.sql +3 -0
  86. package/dist/server/db/migrations/0006_durable_media_deletion.sql +7 -0
  87. package/dist/server/db/migrations/meta/0001_snapshot.json +1197 -0
  88. package/dist/server/db/migrations/meta/0002_snapshot.json +1204 -0
  89. package/dist/server/db/migrations/meta/0003_snapshot.json +1281 -0
  90. package/dist/server/db/migrations/meta/0004_snapshot.json +1546 -0
  91. package/dist/server/db/migrations/meta/0005_snapshot.json +1572 -0
  92. package/dist/server/db/migrations/meta/0006_snapshot.json +1627 -0
  93. package/dist/server/db/migrations/meta/_journal.json +42 -0
  94. package/dist/server/db/schema.d.ts +742 -2
  95. package/dist/server/db/schema.js +77 -5
  96. package/dist/server/email/index.d.ts +11 -1
  97. package/dist/server/email/index.js +69 -6
  98. package/dist/server/forms.js +12 -2
  99. package/dist/server/hooks.d.ts +1 -1
  100. package/dist/server/hooks.js +37 -14
  101. package/dist/server/index.d.ts +1 -1
  102. package/dist/server/index.js +1 -1
  103. package/dist/server/links.d.ts +5 -0
  104. package/dist/server/links.js +44 -0
  105. package/dist/server/media/deletions.d.ts +2 -0
  106. package/dist/server/media/deletions.js +58 -0
  107. package/dist/server/media/presets.d.ts +10 -2
  108. package/dist/server/media/presets.js +14 -2
  109. package/dist/server/media/runner.d.ts +1 -1
  110. package/dist/server/media/runner.js +105 -8
  111. package/dist/server/media/service.d.ts +41 -3
  112. package/dist/server/media/service.js +146 -33
  113. package/dist/server/notifications.d.ts +1 -0
  114. package/dist/server/notifications.js +4 -2
  115. package/dist/server/request.d.ts +2 -0
  116. package/dist/server/request.js +5 -0
  117. package/dist/server/search.d.ts +13 -0
  118. package/dist/server/search.js +97 -0
  119. package/dist/worker/index.d.ts +3 -3
  120. package/dist/worker/index.js +205 -64
  121. package/dist/worker/local.d.ts +5 -0
  122. package/dist/worker/local.js +57 -0
  123. package/dist/worker/source.d.ts +1 -1
  124. package/dist/worker/source.js +2 -2
  125. package/dist/worker/uploads.d.ts +22 -0
  126. package/dist/worker/uploads.js +46 -0
  127. package/docs/acceptance.md +1 -1
  128. package/docs/api.md +73 -0
  129. package/docs/cloudflare.md +35 -8
  130. package/docs/content.md +181 -5
  131. package/docs/deployment.md +29 -4
  132. package/docs/email.md +14 -10
  133. package/docs/forms.md +3 -1
  134. package/docs/media.md +34 -5
  135. package/docs/package.md +7 -5
  136. package/docs/releases.md +56 -1
  137. package/docs/upgrades.md +59 -3
  138. package/package.json +19 -10
  139. package/templates/hooks.server.ts +3 -3
  140. package/templates/integration.ts +2 -2
  141. package/templates/routes/admin/+page.server.ts +2 -2
  142. package/templates/routes/admin/+page.svelte +1 -1
  143. package/templates/routes/api/+server.ts +2 -2
  144. package/templates/sandcms/blueprints/collections/projects.yaml +16 -8
  145. package/templates/sandcms/blueprints/fields/seo.yaml +5 -0
  146. package/templates/sandcms/blueprints/files/image.yaml +1 -0
  147. package/templates/sandcms/blueprints/pages/home.yaml +3 -0
  148. package/templates/sandcms/config.yaml +1 -0
  149. package/templates/sandcms/worker/index.ts +1 -1
  150. package/templates/sandcms/worker/local.ts +1 -0
  151. package/templates/sandcms/worker/wrangler.jsonc +1 -2
package/dist/cli/setup.js CHANGED
@@ -25,9 +25,11 @@ export async function setup(options) {
25
25
  if (fresh)
26
26
  assertFreshDirectory(root);
27
27
  const notes = [
28
+ 'SvelteKit 3 is required. Migrate developer-owned Vite configuration, package imports, and tsconfig before applying generated integrations; see docs/upgrades.md#sveltekit-3.',
28
29
  'Public website routes remain developer-owned.',
29
30
  'Run sandcms user bootstrap against the production database after deployment.',
30
- 'Existing adapters are preserved. Configure svelte-adapter-bun as shown in docs/deployment.md.',
31
+ 'Existing adapters are preserved. Configure @sveltejs/adapter-bun as shown in docs/deployment.md.',
32
+ 'Setup adds commented proxy settings to .env.local. For Dokploy + Cloudflare, secure origin ingress, then set SANDCMS_TRUSTED_PROXY_HEADER=cf-connecting-ip and ADDRESS_HEADER=cf-connecting-ip in Dokploy runtime variables; see docs/deployment.md#client-ip-behind-dokploy-and-cloudflare.',
31
33
  'Existing Vite configuration is preserved. Include @better-auth/core in ssr.noExternal to retain native async request storage in Bun production builds. See docs/deployment.md#server-build-configuration.',
32
34
  'If .dockerignore is customized, merge the template exclusions before building: environment files, credentials, data/, and local Worker state must stay outside the image.'
33
35
  ];
@@ -60,7 +62,7 @@ export async function setup(options) {
60
62
  const env = join(root, '.env.local'), previous = existsSync(env) ? readFileSync(env, 'utf8') : '';
61
63
  const previousSettings = parseEnv(previous);
62
64
  const settings = {
63
- BODY_SIZE_LIMIT: '101M',
65
+ BODY_SIZE_LIMIT: '1M',
64
66
  SANDCMS_DATABASE: options.database ?? './data/sandcms.sqlite',
65
67
  SANDCMS_ORIGIN: 'http://localhost:5410',
66
68
  SANDCMS_SECRET: crypto.randomUUID() + crypto.randomUUID()
@@ -68,6 +70,11 @@ export async function setup(options) {
68
70
  const additions = Object.entries(settings)
69
71
  .filter(([key]) => !previousSettings[key])
70
72
  .map(([key, v]) => `${key}=${v}`);
73
+ const proxyExamples = ['SANDCMS_TRUSTED_PROXY_HEADER', 'ADDRESS_HEADER']
74
+ .filter((key) => !new RegExp(`^\\s*#?\\s*${key}\\s*=`, 'm').test(previous))
75
+ .map((key) => `# ${key}=cf-connecting-ip`);
76
+ if (proxyExamples.length)
77
+ additions.push('# Dokploy + Cloudflare: enable both settings in Dokploy runtime variables only after', '# restricting website ingress to Cloudflare and keeping the container port private.', '# See docs/deployment.md#client-ip-behind-dokploy-and-cloudflare.', ...proxyExamples);
71
78
  appendFileSync(env, '\n' + additions.join('\n') + '\n', { mode: 0o600 });
72
79
  chmodSync(env, 0o600);
73
80
  if (!options.skipInstall) {
@@ -10,10 +10,11 @@ export async function upgrade(root, check = false, database) {
10
10
  if (routeConflicts(root).length)
11
11
  throw new Error('Unowned routes conflict with /admin or /api/cms. Move them before upgrading.');
12
12
  const notes = [
13
+ 'SvelteKit 3 is required. Migrate developer-owned Vite configuration, package imports, and tsconfig before applying generated integrations; see docs/upgrades.md#sveltekit-3.',
13
14
  `Installed integration: ${manifest.version}. Blueprints are valid.`,
14
15
  '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.',
15
16
  '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.',
16
- 'Worker compatibility range: protocol 3. Deploy with sandcms worker update before upgrading website processes; expect temporary media downtime. Set media.uploadLimit to 100000000 and BODY_SIZE_LIMIT=101M to enable larger uploads; keep IMAGES for metadata inspection and verify remote transformations in staging. Purge old /media/* caches and keep R2 public access disabled. See docs/media.md.'
17
+ 'Worker compatibility range: protocol 5 (Worker also accepts protocols 3 and 4 for existing website processes). Deploy with sandcms worker update before upgrading website processes; expect temporary media downtime. Configure Worker R2 signing credentials, bucket CORS and staging lifecycle rules for direct uploads; run the incremental database migration; metadata inspection and encoding use remote transformations; verify both in staging. Purge old /media/* caches and keep R2 public access disabled. See docs/media.md.'
17
18
  ];
18
19
  if (database)
19
20
  notes.push('Pending DB migrations: ' +
@@ -0,0 +1,17 @@
1
+ /** Safe failure categories shared by the server and admin. Never store provider text. */
2
+ export declare const emailFailureMessages: {
3
+ readonly timeout: "SMTP operation timed out; check host, port, and outbound firewall.";
4
+ readonly dns: "SMTP host could not be resolved; check the hostname and DNS.";
5
+ readonly connection: "SMTP connection failed; check host, port, and outbound firewall.";
6
+ readonly authentication: "SMTP authentication failed; check the configured credentials.";
7
+ readonly tls: "SMTP TLS negotiation failed; check port, TLS settings, and certificate.";
8
+ readonly recipient_rejected: "The mail server rejected the recipient; check the recipient address and provider policy.";
9
+ readonly message_rejected: "The mail server rejected the message; check sender permissions and provider policy.";
10
+ readonly not_configured: "Email is not configured.";
11
+ readonly configuration: "Email configuration is invalid.";
12
+ readonly invalid_message: "Email recipient, subject, body, or reply-to is invalid.";
13
+ readonly unknown: "Email could not be sent; check the mail provider and configuration.";
14
+ };
15
+ export type EmailFailureReason = keyof typeof emailFailureMessages;
16
+ export declare function safeEmailFailureReason(value: unknown): EmailFailureReason;
17
+ export declare function emailFailureMessage(reason: unknown): string;
@@ -0,0 +1,22 @@
1
+ /** Safe failure categories shared by the server and admin. Never store provider text. */
2
+ export const emailFailureMessages = {
3
+ timeout: 'SMTP operation timed out; check host, port, and outbound firewall.',
4
+ dns: 'SMTP host could not be resolved; check the hostname and DNS.',
5
+ connection: 'SMTP connection failed; check host, port, and outbound firewall.',
6
+ authentication: 'SMTP authentication failed; check the configured credentials.',
7
+ tls: 'SMTP TLS negotiation failed; check port, TLS settings, and certificate.',
8
+ recipient_rejected: 'The mail server rejected the recipient; check the recipient address and provider policy.',
9
+ message_rejected: 'The mail server rejected the message; check sender permissions and provider policy.',
10
+ not_configured: 'Email is not configured.',
11
+ configuration: 'Email configuration is invalid.',
12
+ invalid_message: 'Email recipient, subject, body, or reply-to is invalid.',
13
+ unknown: 'Email could not be sent; check the mail provider and configuration.'
14
+ };
15
+ export function safeEmailFailureReason(value) {
16
+ return typeof value === 'string' && Object.hasOwn(emailFailureMessages, value)
17
+ ? value
18
+ : 'unknown';
19
+ }
20
+ export function emailFailureMessage(reason) {
21
+ return emailFailureMessages[safeEmailFailureReason(reason)];
22
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- export type { Blueprint, FileBlueprint, Field, Json, Payload, SiteConfig, SiteDefinition } from './blueprints/types.js';
1
+ export type { Blueprint, BlueprintTab, BlueprintColumn, BlueprintSection, FieldWidth, FileBlueprint, Field, Json, Payload, SiteConfig, SiteDefinition } from './blueprints/types.js';
2
2
  export { renderRichText } from './richtext.js';
3
3
  export { imageSources, type PublicMedia, type PublicMediaVariant } from './media.js';
4
4
  export { default as Image, type ImageProps } from './Image.svelte';
5
5
  export { default as Seo, type SeoProps } from './Seo.svelte';
6
+ export { linkHref, isLinkValue, type LinkValue, type LinkType, type ResolvedLink } from './link.js';
package/dist/index.js CHANGED
@@ -2,3 +2,4 @@ export { renderRichText } from './richtext.js';
2
2
  export { imageSources } from './media.js';
3
3
  export { default as Image } from './Image.svelte';
4
4
  export { default as Seo } from './Seo.svelte';
5
+ export { linkHref, isLinkValue } from './link.js';
package/dist/link.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ /** Link destinations stay structured so entry URLs can follow published slug changes. */
2
+ export declare const linkTypes: readonly ["url", "entry", "file", "email", "phone"];
3
+ export type LinkType = (typeof linkTypes)[number];
4
+ export type LinkValue = {
5
+ type: LinkType;
6
+ value: string;
7
+ label?: string;
8
+ newTab?: boolean;
9
+ };
10
+ export interface ResolvedLink {
11
+ href: string;
12
+ label: string;
13
+ target?: '_blank';
14
+ rel?: 'noopener noreferrer';
15
+ }
16
+ export declare function linkHref(type: LinkType, value: string): string | null;
17
+ export declare function isLinkValue(value: unknown): value is LinkValue;
package/dist/link.js ADDED
@@ -0,0 +1,44 @@
1
+ /** Link destinations stay structured so entry URLs can follow published slug changes. */
2
+ export const linkTypes = ['url', 'entry', 'file', 'email', 'phone'];
3
+ export function linkHref(type, value) {
4
+ if (!value || /[\u0000-\u001f\u007f\\]/.test(value))
5
+ return null;
6
+ if (type === 'phone')
7
+ return /^\+?[0-9][0-9 ().-]*$/.test(value) ? `tel:${value.replace(/[ ().-]/g, '')}` : null;
8
+ if (/[\u0000-\u0020\u007f\\]/.test(value))
9
+ return null;
10
+ if (type === 'url') {
11
+ if (/^\/(?!\/)/.test(value) || /^#[^\s]*$/.test(value))
12
+ return value;
13
+ try {
14
+ const url = new URL(value);
15
+ if (!/^https?:\/\//i.test(value) ||
16
+ !/^https?:$/.test(url.protocol) ||
17
+ !url.hostname ||
18
+ url.username ||
19
+ url.password)
20
+ return null;
21
+ return value;
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
27
+ if (type === 'email' && /^[^@\s:?&#]+@[^@\s:?&#]+\.[^@\s:?&#]+$/.test(value))
28
+ return `mailto:${value}`;
29
+ return null;
30
+ }
31
+ export function isLinkValue(value) {
32
+ if (!value || typeof value !== 'object' || Array.isArray(value))
33
+ return false;
34
+ const link = value;
35
+ return (linkTypes.includes(link.type) &&
36
+ typeof link.value === 'string' &&
37
+ (link.label === undefined || typeof link.label === 'string') &&
38
+ (link.newTab === undefined || typeof link.newTab === 'boolean') &&
39
+ Object.keys(value).every((key) => ['type', 'value', 'label', 'newTab'].includes(key)) &&
40
+ (link.value === '' ||
41
+ (['entry', 'file'].includes(link.type)
42
+ ? /^[a-zA-Z0-9_-]+$/.test(link.value)
43
+ : linkHref(link.type, link.value) !== null)));
44
+ }
@@ -5,7 +5,7 @@ export function notificationFields(fields, prefix = '', label = '') {
5
5
  if (field.type === 'group')
6
6
  return notificationFields(field.fields ?? {}, value + '.', title + ' / ');
7
7
  // Repeated groups and rich content can contain additional unselected data.
8
- if (['repeatable', 'richtext', 'gallery', 'media', 'media-list'].includes(field.type))
8
+ if (['repeatable', 'richtext', 'gallery', 'media', 'media-list', 'link'].includes(field.type))
9
9
  return [];
10
10
  return [{ value, label: title, type: field.type }];
11
11
  });
@@ -0,0 +1,8 @@
1
+ export interface SearchResult {
2
+ id: string;
3
+ kind: 'page' | 'content' | 'media';
4
+ title: string;
5
+ label: string;
6
+ href: string;
7
+ excerpt: string;
8
+ }
package/dist/search.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -1,5 +1,6 @@
1
1
  import type { Store } from './db/store.js';
2
2
  import { type createEmail } from './email/index.js';
3
+ /** Manage invitation and reset links, recording privacy-safe email outcomes. */
3
4
  export declare function createAccess(store: Store, email: ReturnType<typeof createEmail>, origin: string): {
4
5
  list: () => {
5
6
  id: string;
@@ -7,6 +8,7 @@ export declare function createAccess(store: Store, email: ReturnType<typeof crea
7
8
  role: "admin" | "editor";
8
9
  expiresAt: number;
9
10
  status: "failed" | "sending" | "accepted";
11
+ failureReason: "timeout" | "dns" | "connection" | "authentication" | "tls" | "recipient_rejected" | "message_rejected" | "not_configured" | "configuration" | "invalid_message" | "unknown" | null;
10
12
  }[];
11
13
  invite: (recipient: string, role: "admin" | "editor", actor: string) => Promise<void>;
12
14
  resend: (id: string, actor: string) => Promise<void>;
@@ -1,11 +1,12 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
- import { and, eq } from 'drizzle-orm';
2
+ import { and, eq, lte, ne, or, sql } from 'drizzle-orm';
3
3
  import { hashPassword } from 'better-auth/crypto';
4
- import { accessLinks, account, user, session, audit } from './db/schema.js';
5
- import { address } from './email/index.js';
4
+ import { accessLinks, account, user, session, apikey, audit } from './db/schema.js';
5
+ import { address, emailFailureReason } from './email/index.js';
6
6
  import { emailTemplate } from './email/template.js';
7
7
  import { rateLimit } from './forms.js';
8
8
  const digest = (value) => createHash('sha256').update(value).digest('hex');
9
+ /** Manage invitation and reset links, recording privacy-safe email outcomes. */
9
10
  export function createAccess(store, email, origin) {
10
11
  const findUser = (value) => store.db.select().from(user).where(eq(user.email, value)).get();
11
12
  const credential = (id) => store.db
@@ -13,10 +14,16 @@ export function createAccess(store, email, origin) {
13
14
  .from(account)
14
15
  .where(and(eq(account.userId, id), eq(account.providerId, 'credential')))
15
16
  .get();
16
- function auditEvent(action, actor, id) {
17
+ function auditEvent(action, actor, id, detail = {}) {
17
18
  store.db
18
19
  .insert(audit)
19
- .values({ id: crypto.randomUUID(), action, actor, detail: { id }, createdAt: Date.now() })
20
+ .values({
21
+ id: crypto.randomUUID(),
22
+ action,
23
+ actor,
24
+ detail: { id, ...detail },
25
+ createdAt: Date.now()
26
+ })
20
27
  .run();
21
28
  }
22
29
  async function send(kind, recipient, role, actor) {
@@ -41,21 +48,39 @@ export function createAccess(store, email, origin) {
41
48
  role,
42
49
  tokenHash,
43
50
  credentialHash: kind === 'reset' ? digest(password) : null,
44
- expiresAt: now + (kind === 'invite' ? 7 * 24 : 1) * 60 * 60 * 1000,
51
+ expiresAt: now + (kind === 'invite' ? 7 * 24 * 60 : 15) * 60 * 1000,
45
52
  status: 'sending',
53
+ failureReason: null,
46
54
  createdAt: now
47
55
  };
48
- store.db.transaction(() => {
49
- store.db
50
- .insert(accessLinks)
51
- .values(row)
52
- .onConflictDoUpdate({
53
- target: [accessLinks.kind, accessLinks.email],
54
- set: row
55
- })
56
- .run();
56
+ const persisted = store.db.transaction(() => {
57
+ if (kind === 'reset') {
58
+ const recipient = and(eq(accessLinks.kind, 'reset'), eq(accessLinks.email, normalized));
59
+ store.db
60
+ .delete(accessLinks)
61
+ .where(and(recipient, or(lte(accessLinks.expiresAt, now), ne(accessLinks.credentialHash, row.credentialHash))))
62
+ .run();
63
+ // Never evict a usable link to make room for an unauthenticated request.
64
+ if (store.db.select().from(accessLinks).where(recipient).all().length >= 3)
65
+ return false;
66
+ store.db.insert(accessLinks).values(row).run();
67
+ }
68
+ else {
69
+ store.db
70
+ .insert(accessLinks)
71
+ .values(row)
72
+ .onConflictDoUpdate({
73
+ target: [accessLinks.kind, accessLinks.email],
74
+ targetWhere: sql `${accessLinks.kind} = 'invite'`,
75
+ set: row
76
+ })
77
+ .run();
78
+ }
57
79
  auditEvent(`${kind}.send`, actor, row.id);
80
+ return true;
58
81
  });
82
+ if (!persisted)
83
+ return;
59
84
  try {
60
85
  await email.send({
61
86
  to: normalized,
@@ -69,22 +94,22 @@ export function createAccess(store, email, origin) {
69
94
  url: `${origin}/admin/${kind === 'invite' ? 'invite' : 'reset-password'}#${token}`,
70
95
  footer: kind === 'invite'
71
96
  ? 'This link expires in seven days and can be used once.'
72
- : 'This link expires in one hour and can be used once. If you did not request this, ignore this email.'
97
+ : 'This link expires in 15 minutes and can be used once. If you did not request this, ignore this email.'
73
98
  }),
74
99
  text: kind === 'invite'
75
100
  ? `You have been invited as ${role}. Choose your name and password:\n\n${origin}/admin/invite#${token}\n\nThis link expires in seven days and can be used once.`
76
- : `Choose a new password:\n\n${origin}/admin/reset-password#${token}\n\nThis link expires in one hour and can be used once. If you did not request this, ignore this email.`
101
+ : `Choose a new password:\n\n${origin}/admin/reset-password#${token}\n\nThis link expires in 15 minutes and can be used once. If you did not request this, ignore this email.`
77
102
  });
78
103
  store.db
79
104
  .update(accessLinks)
80
- .set({ status: 'accepted' })
105
+ .set({ status: 'accepted', failureReason: null })
81
106
  .where(eq(accessLinks.tokenHash, tokenHash))
82
107
  .run();
83
108
  }
84
- catch {
109
+ catch (error) {
85
110
  store.db
86
111
  .update(accessLinks)
87
- .set({ status: 'failed' })
112
+ .set({ status: 'failed', failureReason: emailFailureReason(error) })
88
113
  .where(eq(accessLinks.tokenHash, tokenHash))
89
114
  .run();
90
115
  }
@@ -96,7 +121,8 @@ export function createAccess(store, email, origin) {
96
121
  email: accessLinks.email,
97
122
  role: accessLinks.role,
98
123
  expiresAt: accessLinks.expiresAt,
99
- status: accessLinks.status
124
+ status: accessLinks.status,
125
+ failureReason: accessLinks.failureReason
100
126
  })
101
127
  .from(accessLinks)
102
128
  .where(eq(accessLinks.kind, 'invite'))
@@ -207,9 +233,19 @@ export function createAccess(store, email, origin) {
207
233
  .where(eq(user.id, existing.id))
208
234
  .run();
209
235
  store.db.delete(session).where(eq(session.userId, existing.id)).run();
210
- auditEvent('password.reset', existing.id, row.id);
236
+ const revoked = store.db
237
+ .delete(apikey)
238
+ .where(eq(apikey.referenceId, existing.id))
239
+ .returning({ id: apikey.id })
240
+ .all();
241
+ auditEvent('password.reset', existing.id, row.id, { revokedKeys: revoked.length });
211
242
  }
212
- store.db.delete(accessLinks).where(eq(accessLinks.id, row.id)).run();
243
+ store.db
244
+ .delete(accessLinks)
245
+ .where(kind === 'reset'
246
+ ? and(eq(accessLinks.kind, 'reset'), eq(accessLinks.email, row.email))
247
+ : eq(accessLinks.id, row.id))
248
+ .run();
213
249
  });
214
250
  }
215
251
  };
@@ -21,9 +21,13 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
21
21
  label: string;
22
22
  kind: "page" | "site" | "collection" | "form";
23
23
  icon?: string;
24
+ navigation?: {
25
+ group: string | false;
26
+ };
24
27
  description?: string;
25
28
  preview?: string;
26
29
  fields: Record<string, import("../index.ts").Field>;
30
+ tabs?: Record<string, import("../index.ts").BlueprintTab>;
27
31
  columns?: string[];
28
32
  export?: string[];
29
33
  }[];
@@ -72,13 +76,14 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
72
76
  }[];
73
77
  editing: boolean;
74
78
  assets: {
79
+ expectedVersion: string;
75
80
  blueprint: string;
76
81
  metadata: import("../index.ts").Payload;
77
82
  id: string;
78
83
  filename: string;
79
84
  mime: string;
80
85
  bytes: number;
81
- status: "processing" | "ready" | "failed";
86
+ status: "processing" | "ready" | "failed" | "deleting";
82
87
  activeVersion: string | null;
83
88
  targetVersion: string;
84
89
  variants: import("./db/schema.js").Variant[];
@@ -111,9 +116,13 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
111
116
  label: string;
112
117
  kind: "page" | "site" | "collection" | "form";
113
118
  icon?: string;
119
+ navigation?: {
120
+ group: string | false;
121
+ };
114
122
  description?: string;
115
123
  preview?: string;
116
124
  fields: Record<string, import("../index.ts").Field>;
125
+ tabs?: Record<string, import("../index.ts").BlueprintTab>;
117
126
  columns?: string[];
118
127
  export?: string[];
119
128
  }[];
@@ -125,13 +134,14 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
125
134
  next?: undefined;
126
135
  } | {
127
136
  assets: {
137
+ expectedVersion: string;
128
138
  blueprint: string;
129
139
  metadata: import("../index.ts").Payload;
130
140
  id: string;
131
141
  filename: string;
132
142
  mime: string;
133
143
  bytes: number;
134
- status: "processing" | "ready" | "failed";
144
+ status: "processing" | "ready" | "failed" | "deleting";
135
145
  activeVersion: string | null;
136
146
  targetVersion: string;
137
147
  variants: import("./db/schema.js").Variant[];
@@ -173,9 +183,13 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
173
183
  label: string;
174
184
  kind: "page" | "site" | "collection" | "form";
175
185
  icon?: string;
186
+ navigation?: {
187
+ group: string | false;
188
+ };
176
189
  description?: string;
177
190
  preview?: string;
178
191
  fields: Record<string, import("../index.ts").Field>;
192
+ tabs?: Record<string, import("../index.ts").BlueprintTab>;
179
193
  columns?: string[];
180
194
  export?: string[];
181
195
  }[];
@@ -227,9 +241,13 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
227
241
  label: string;
228
242
  kind: "page" | "site" | "collection" | "form";
229
243
  icon?: string;
244
+ navigation?: {
245
+ group: string | false;
246
+ };
230
247
  description?: string;
231
248
  preview?: string;
232
249
  fields: Record<string, import("../index.ts").Field>;
250
+ tabs?: Record<string, import("../index.ts").BlueprintTab>;
233
251
  columns?: string[];
234
252
  export?: string[];
235
253
  }[];
@@ -246,6 +264,7 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
246
264
  role: "admin" | "editor";
247
265
  expiresAt: number;
248
266
  status: "failed" | "sending" | "accepted";
267
+ failureReason: "timeout" | "dns" | "connection" | "authentication" | "tls" | "recipient_rejected" | "message_rejected" | "not_configured" | "configuration" | "invalid_message" | "unknown" | null;
249
268
  }[];
250
269
  users: {
251
270
  id: string;
@@ -274,9 +293,13 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
274
293
  label: string;
275
294
  kind: "page" | "site" | "collection" | "form";
276
295
  icon?: string;
296
+ navigation?: {
297
+ group: string | false;
298
+ };
277
299
  description?: string;
278
300
  preview?: string;
279
301
  fields: Record<string, import("../index.ts").Field>;
302
+ tabs?: Record<string, import("../index.ts").BlueprintTab>;
280
303
  columns?: string[];
281
304
  export?: string[];
282
305
  }[];
@@ -327,9 +350,13 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
327
350
  label: string;
328
351
  kind: "page" | "site" | "collection" | "form";
329
352
  icon?: string;
353
+ navigation?: {
354
+ group: string | false;
355
+ };
330
356
  description?: string;
331
357
  preview?: string;
332
358
  fields: Record<string, import("../index.ts").Field>;
359
+ tabs?: Record<string, import("../index.ts").BlueprintTab>;
333
360
  columns?: string[];
334
361
  export?: string[];
335
362
  }[];
@@ -43,8 +43,10 @@ export async function adminLoad(cms, event) {
43
43
  if (screen === 'account')
44
44
  return base;
45
45
  requireUser(session.user);
46
- const assets = cms.media.list(), relations = Object.fromEntries(cms.definition.blueprints
47
- .filter((b) => b.kind === 'collection')
46
+ const assets = cms.media
47
+ .list()
48
+ .map((asset) => ({ ...asset, expectedVersion: cms.media.versionForAsset(asset) })), relations = Object.fromEntries(cms.definition.blueprints
49
+ .filter((b) => b.kind !== 'form')
48
50
  .map((b) => [
49
51
  b.id,
50
52
  cms.content.list(b.id).map((d) => ({ id: d.id, label: String(d.draft.title ?? d.id) }))
@@ -0,0 +1,31 @@
1
+ import type { CMS } from './cms.js';
2
+ export declare function apiKeyRoute(path: string, method: string): boolean;
3
+ export declare function apiPrincipal(cms: CMS, request: Request, path: string): Promise<{
4
+ user: {
5
+ id: string;
6
+ name: string;
7
+ email: string;
8
+ emailVerified: boolean;
9
+ image: string | null;
10
+ createdAt: Date;
11
+ updatedAt: Date;
12
+ role: "admin" | "editor";
13
+ mustChangePassword: boolean;
14
+ twoFactorEnabled: boolean | null;
15
+ };
16
+ keyId: string;
17
+ } | {
18
+ user: {
19
+ id: string;
20
+ createdAt: Date;
21
+ updatedAt: Date;
22
+ email: string;
23
+ emailVerified: boolean;
24
+ name: string;
25
+ image?: string | null | undefined | undefined;
26
+ role: string;
27
+ mustChangePassword: boolean;
28
+ twoFactorEnabled: boolean | null | undefined;
29
+ };
30
+ keyId: null;
31
+ }>;
@@ -0,0 +1,52 @@
1
+ import { error } from '@sveltejs/kit';
2
+ import { eq } from 'drizzle-orm';
3
+ import { user } from './db/schema.js';
4
+ const reads = new Set(['schema', 'content/list', 'content/get', 'media/list']);
5
+ const writes = new Set([
6
+ 'content/save',
7
+ 'content/duplicate',
8
+ 'content/publish',
9
+ 'content/unpublish',
10
+ 'content/delete',
11
+ 'media/upload',
12
+ 'media/upload/complete',
13
+ 'media/update',
14
+ 'media/retry',
15
+ 'media/delete'
16
+ ]);
17
+ export function apiKeyRoute(path, method) {
18
+ return (method === 'GET' && reads.has(path)) || (method === 'POST' && writes.has(path));
19
+ }
20
+ export async function apiPrincipal(cms, request, path) {
21
+ // An explicitly supplied credential never falls back to a browser cookie.
22
+ if (request.headers.has('x-api-key')) {
23
+ const result = await cms.auth.api.verifyApiKey({
24
+ body: { key: request.headers.get('x-api-key') }
25
+ });
26
+ if (!result.valid || !result.key) {
27
+ if (result.error?.code === 'RATE_LIMITED')
28
+ error(429, 'API key rate limit exceeded');
29
+ error(401, 'Invalid or expired API key');
30
+ }
31
+ if (!apiKeyRoute(path, request.method))
32
+ error(403, 'API keys can only access content and media');
33
+ const action = request.method === 'GET' ? 'read' : 'write';
34
+ if (!result.key.permissions?.cms?.includes(action))
35
+ error(403, 'API key permission denied');
36
+ const owner = cms.store.db.select().from(user).where(eq(user.id, result.key.referenceId)).get();
37
+ if (!owner || !['admin', 'editor'].includes(owner.role))
38
+ error(403, 'API key owner cannot access the CMS');
39
+ if (owner.mustChangePassword)
40
+ error(403, 'Change your temporary password first');
41
+ return { user: owner, keyId: result.key.id };
42
+ }
43
+ if (!['GET', 'HEAD', 'OPTIONS'].includes(request.method) &&
44
+ request.headers.get('origin') !== cms.options.origin)
45
+ error(403, 'Invalid request origin');
46
+ const session = await cms.auth.api.getSession({ headers: request.headers });
47
+ if (!session)
48
+ error(401, 'Sign in required');
49
+ if (session.user.mustChangePassword)
50
+ error(403, 'Change your temporary password first');
51
+ return { user: session.user, keyId: null };
52
+ }
@@ -0,0 +1,34 @@
1
+ import type { CMS } from './cms.js';
2
+ export declare function contentPage(cms: CMS, params: URLSearchParams): {
3
+ items: {
4
+ id: string;
5
+ blueprint: string;
6
+ singleton: string | null;
7
+ draft: import("../index.ts").Payload;
8
+ published: import("../index.ts").Payload | null;
9
+ draftSlug: string | null;
10
+ publishedSlug: string | null;
11
+ version: number;
12
+ publishedAt: number | null;
13
+ updatedAt: number;
14
+ createdAt: number;
15
+ }[];
16
+ nextCursor: string | null;
17
+ };
18
+ export declare function mediaPage(cms: CMS, params: URLSearchParams): {
19
+ items: {
20
+ blueprint: string;
21
+ metadata: import("../index.ts").Payload;
22
+ id: string;
23
+ filename: string;
24
+ mime: string;
25
+ bytes: number;
26
+ status: "processing" | "ready" | "failed" | "deleting";
27
+ activeVersion: string | null;
28
+ targetVersion: string;
29
+ variants: import("./db/schema.js").Variant[];
30
+ error: string | null;
31
+ createdAt: number;
32
+ }[];
33
+ nextCursor: string | null;
34
+ };