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
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
  };
@@ -27,6 +27,7 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
27
27
  description?: string;
28
28
  preview?: string;
29
29
  fields: Record<string, import("../index.ts").Field>;
30
+ tabs?: Record<string, import("../index.ts").BlueprintTab>;
30
31
  columns?: string[];
31
32
  export?: string[];
32
33
  }[];
@@ -75,13 +76,14 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
75
76
  }[];
76
77
  editing: boolean;
77
78
  assets: {
79
+ expectedVersion: string;
78
80
  blueprint: string;
79
81
  metadata: import("../index.ts").Payload;
80
82
  id: string;
81
83
  filename: string;
82
84
  mime: string;
83
85
  bytes: number;
84
- status: "processing" | "ready" | "failed";
86
+ status: "processing" | "ready" | "failed" | "deleting";
85
87
  activeVersion: string | null;
86
88
  targetVersion: string;
87
89
  variants: import("./db/schema.js").Variant[];
@@ -120,6 +122,7 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
120
122
  description?: string;
121
123
  preview?: string;
122
124
  fields: Record<string, import("../index.ts").Field>;
125
+ tabs?: Record<string, import("../index.ts").BlueprintTab>;
123
126
  columns?: string[];
124
127
  export?: string[];
125
128
  }[];
@@ -131,13 +134,14 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
131
134
  next?: undefined;
132
135
  } | {
133
136
  assets: {
137
+ expectedVersion: string;
134
138
  blueprint: string;
135
139
  metadata: import("../index.ts").Payload;
136
140
  id: string;
137
141
  filename: string;
138
142
  mime: string;
139
143
  bytes: number;
140
- status: "processing" | "ready" | "failed";
144
+ status: "processing" | "ready" | "failed" | "deleting";
141
145
  activeVersion: string | null;
142
146
  targetVersion: string;
143
147
  variants: import("./db/schema.js").Variant[];
@@ -185,6 +189,7 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
185
189
  description?: string;
186
190
  preview?: string;
187
191
  fields: Record<string, import("../index.ts").Field>;
192
+ tabs?: Record<string, import("../index.ts").BlueprintTab>;
188
193
  columns?: string[];
189
194
  export?: string[];
190
195
  }[];
@@ -242,6 +247,7 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
242
247
  description?: string;
243
248
  preview?: string;
244
249
  fields: Record<string, import("../index.ts").Field>;
250
+ tabs?: Record<string, import("../index.ts").BlueprintTab>;
245
251
  columns?: string[];
246
252
  export?: string[];
247
253
  }[];
@@ -258,6 +264,7 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
258
264
  role: "admin" | "editor";
259
265
  expiresAt: number;
260
266
  status: "failed" | "sending" | "accepted";
267
+ failureReason: "timeout" | "dns" | "connection" | "authentication" | "tls" | "recipient_rejected" | "message_rejected" | "not_configured" | "configuration" | "invalid_message" | "unknown" | null;
261
268
  }[];
262
269
  users: {
263
270
  id: string;
@@ -292,6 +299,7 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
292
299
  description?: string;
293
300
  preview?: string;
294
301
  fields: Record<string, import("../index.ts").Field>;
302
+ tabs?: Record<string, import("../index.ts").BlueprintTab>;
295
303
  columns?: string[];
296
304
  export?: string[];
297
305
  }[];
@@ -348,6 +356,7 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
348
356
  description?: string;
349
357
  preview?: string;
350
358
  fields: Record<string, import("../index.ts").Field>;
359
+ tabs?: Record<string, import("../index.ts").BlueprintTab>;
351
360
  columns?: string[];
352
361
  export?: string[];
353
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
+ };
@@ -0,0 +1,87 @@
1
+ import { error } from '@sveltejs/kit';
2
+ import { and, desc, eq, inArray, lt, or } from 'drizzle-orm';
3
+ import { documents, media } from './db/schema.js';
4
+ import { searchQuery, documentText, assetText, matchScore } from './search.js';
5
+ function pagination(params, scope) {
6
+ const rawLimit = params.get('limit') ?? '100';
7
+ if (!/^\d+$/.test(rawLimit) || Number(rawLimit) < 1 || Number(rawLimit) > 500)
8
+ error(400, 'limit must be an integer between 1 and 500');
9
+ let cursor;
10
+ const rawCursor = params.get('cursor');
11
+ if (rawCursor !== null) {
12
+ try {
13
+ if (!rawCursor || rawCursor.length > 2048 || !/^[A-Za-z0-9_-]+$/.test(rawCursor))
14
+ throw new Error();
15
+ const parsed = JSON.parse(Buffer.from(rawCursor, 'base64url').toString('utf8'));
16
+ if (parsed.scope !== scope ||
17
+ !Number.isSafeInteger(parsed.time) ||
18
+ parsed.time < 0 ||
19
+ typeof parsed.id !== 'string' ||
20
+ !parsed.id ||
21
+ parsed.id.length > 255)
22
+ throw new Error();
23
+ cursor = parsed;
24
+ }
25
+ catch {
26
+ error(400, 'Invalid pagination cursor');
27
+ }
28
+ }
29
+ return { limit: Number(rawLimit), cursor, scope };
30
+ }
31
+ function page(rows, limit, scope, time) {
32
+ const items = rows.slice(0, limit), last = items.at(-1);
33
+ return {
34
+ items,
35
+ nextCursor: rows.length > limit && last
36
+ ? Buffer.from(JSON.stringify({ scope, time: time(last), id: last.id })).toString('base64url')
37
+ : null
38
+ };
39
+ }
40
+ const scanBatch = 200;
41
+ function scan(limit, cursor, time, fetch, match) {
42
+ if (!match)
43
+ return fetch(cursor, limit + 1);
44
+ const rows = [];
45
+ for (let after = cursor;;) {
46
+ const batch = fetch(after, scanBatch);
47
+ for (const row of batch)
48
+ if (match(row) && rows.push(row) > limit)
49
+ return rows;
50
+ if (batch.length < scanBatch)
51
+ return rows;
52
+ const last = batch.at(-1);
53
+ after = { time: time(last), id: last.id };
54
+ }
55
+ }
56
+ export function contentPage(cms, params) {
57
+ const blueprint = params.get('blueprint') ?? '';
58
+ if (!cms.definition.blueprints.some((b) => b.id === blueprint && b.kind !== 'form'))
59
+ error(404, 'Content blueprint not found');
60
+ const query = searchQuery(params);
61
+ const { limit, cursor, scope } = pagination(params, query ? JSON.stringify(['content', blueprint, query]) : `content:${blueprint}`);
62
+ const rows = scan(limit, cursor, (row) => row.updatedAt, (after, count) => cms.store.db
63
+ .select()
64
+ .from(documents)
65
+ .where(and(eq(documents.blueprint, blueprint), after
66
+ ? or(lt(documents.updatedAt, after.time), and(eq(documents.updatedAt, after.time), lt(documents.id, after.id)))
67
+ : undefined))
68
+ .orderBy(desc(documents.updatedAt), desc(documents.id))
69
+ .limit(count)
70
+ .all(), query ? (row) => matchScore(query, String(row.draft.title ?? ''), documentText(cms, row)) >= 0 : undefined);
71
+ return page(rows, limit, scope, (row) => row.updatedAt);
72
+ }
73
+ export function mediaPage(cms, params) {
74
+ const query = searchQuery(params), blueprint = params.get('blueprint'), mime = params.getAll('mime');
75
+ const { limit, cursor, scope } = pagination(params, query || blueprint || mime.length ? JSON.stringify(['media', query, blueprint, [...mime].sort()]) : 'media');
76
+ const labels = new Map();
77
+ const rows = scan(limit, cursor, (row) => row.createdAt, (after, count) => cms.store.db
78
+ .select()
79
+ .from(media)
80
+ .where(and(blueprint ? eq(media.blueprint, blueprint) : undefined, mime.length ? inArray(media.mime, mime) : undefined, after
81
+ ? or(lt(media.createdAt, after.time), and(eq(media.createdAt, after.time), lt(media.id, after.id)))
82
+ : undefined))
83
+ .orderBy(desc(media.createdAt), desc(media.id))
84
+ .limit(count)
85
+ .all(), query ? (row) => matchScore(query, row.filename, assetText(cms, row, labels)) >= 0 : undefined);
86
+ return page(rows, limit, scope, (row) => row.createdAt);
87
+ }