@beechcms/api 0.4.0-preview.8 → 0.4.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 (89) hide show
  1. package/assets/dashboard/BeechLogo.svg +18 -18
  2. package/assets/dashboard/BeechLogoLIght.svg +48 -48
  3. package/assets/dashboard/assets/index-CewtCjom.css +1 -0
  4. package/assets/dashboard/assets/index-FQ6JhvRH.js +554 -0
  5. package/assets/dashboard/beechLogoDark.svg +48 -48
  6. package/assets/dashboard/index.html +18 -18
  7. package/assets/dashboard/sol.svg +3 -3
  8. package/assets/dashboard/undraw_enter_nwx3.svg +36 -36
  9. package/migrations/0000_v040_base.sql +213 -213
  10. package/package.json +2 -2
  11. package/src/auth/constants.ts +10 -10
  12. package/src/auth/login.ts +91 -91
  13. package/src/auth/refresh.ts +127 -127
  14. package/src/factory.ts +347 -303
  15. package/src/features/content/constants.ts +10 -0
  16. package/src/features/content/handlers/create.ts +153 -0
  17. package/src/features/content/handlers/delete.ts +76 -0
  18. package/src/features/content/handlers/facets.ts +45 -0
  19. package/src/features/content/handlers/get.ts +116 -0
  20. package/src/features/content/handlers/list.ts +88 -0
  21. package/src/features/content/handlers/update.ts +207 -0
  22. package/src/features/content/index.ts +20 -0
  23. package/src/features/draft/draft.handler.ts +272 -198
  24. package/src/features/draft/index.ts +1 -1
  25. package/src/features/email/email.provider.ts +38 -38
  26. package/src/features/email/email.service.ts +80 -80
  27. package/src/features/email/email.types.ts +98 -98
  28. package/src/features/email/index.ts +28 -28
  29. package/src/features/email/providers/resend.ts +63 -63
  30. package/src/features/email/templates/password-changed.ts +59 -59
  31. package/src/features/email/templates/password-reset.ts +64 -64
  32. package/src/features/email/templates/shell.ts +92 -93
  33. package/src/features/notifications/index.ts +1 -1
  34. package/src/features/notifications/notifications.handler.ts +130 -88
  35. package/src/features/password-reset/index.ts +15 -15
  36. package/src/features/password-reset/request.ts +106 -88
  37. package/src/features/password-reset/reset.ts +128 -110
  38. package/src/features/rotate-field/index.ts +1 -1
  39. package/src/features/rotate-field/rotate-field.handler.ts +132 -82
  40. package/src/features/rotate-field/rotate-field.schema.ts +13 -9
  41. package/src/features/schema/schema.handler.ts +16 -16
  42. package/src/features/settings/settings.handler.ts +414 -249
  43. package/src/features/setup/index.ts +96 -59
  44. package/src/features/stats/index.ts +1 -1
  45. package/src/features/stats/stats.handler.ts +458 -395
  46. package/src/index.ts +24 -11
  47. package/src/media-utils.ts +78 -78
  48. package/src/middleware/repository.middleware.ts +24 -0
  49. package/src/middleware/storage.middleware.ts +21 -0
  50. package/src/middleware.ts +67 -67
  51. package/src/public/access-policy.ts +23 -23
  52. package/src/public/api-key-middleware.ts +53 -53
  53. package/src/public/index.ts +12 -12
  54. package/src/public/problem-details.ts +48 -42
  55. package/src/public/public-add.ts +166 -183
  56. package/src/public/public-edit.ts +158 -183
  57. package/src/public/public-errors.ts +15 -15
  58. package/src/public/public-read.ts +216 -217
  59. package/src/public/public-routes.ts +84 -31
  60. package/src/public/query-builder.ts +152 -241
  61. package/src/public/rate-limit-middleware.ts +42 -42
  62. package/src/public/response-builder.ts +26 -26
  63. package/src/public/sanitize.ts +65 -65
  64. package/src/public/slug-utils.ts +14 -14
  65. package/src/search-utils.ts +192 -192
  66. package/src/search.ts +72 -72
  67. package/src/shared/activity-logger.ts +79 -79
  68. package/src/shared/apply-policies.ts +63 -63
  69. package/src/shared/base.repository.d1.ts +28 -0
  70. package/src/shared/content-utils.ts +82 -108
  71. package/src/shared/content.repository.d1.ts +382 -0
  72. package/src/shared/fts-sync.ts +4 -4
  73. package/src/shared/idempotency.repository.d1.ts +56 -0
  74. package/src/shared/media.repository.d1.ts +64 -0
  75. package/src/shared/notification-service.ts +56 -56
  76. package/src/shared/query-utils.ts +137 -137
  77. package/src/shared/storage/factory.ts +40 -0
  78. package/src/shared/storage/r2-binding-bucket.ts +81 -0
  79. package/src/shared/storage/s3-bucket.ts +163 -0
  80. package/src/shared/storage-utils.ts +36 -36
  81. package/src/shared/system-stats.repository.d1.ts +44 -0
  82. package/src/types.ts +46 -36
  83. package/src/upload.ts +179 -335
  84. package/src/widget.ts +349 -349
  85. package/assets/dashboard/assets/index-CC-jbp6g.js +0 -554
  86. package/assets/dashboard/assets/index-CQODXprH.css +0 -1
  87. package/src/content.ts +0 -502
  88. package/src/features/draft/draft.test.ts +0 -315
  89. package/src/features/rotate-field/rotate-field.test.ts +0 -297
@@ -1,183 +1,166 @@
1
- import { isValidContentStatus } from '@beechcms/core'
2
- import type { Seed } from '@beechcms/core'
3
- import type { Context } from 'hono'
4
- import { cleanStr } from '../shared/query-utils'
5
- import { buildInsertBindings } from '../shared/content-utils'
6
- import { checkPublicOperation } from './access-policy'
7
- import { publicProblem } from './problem-details'
8
- import { generateEntrySlug, slugify } from './slug-utils'
9
- import { sanitizePublicPayload } from './sanitize'
10
- import { createNotification } from '../shared/notification-service'
11
-
12
- type Bindings = {
13
- DB: D1Database
14
- PUBLIC_READ_API_KEY?: string
15
- PUBLIC_WRITE_API_KEY?: string
16
- PUBLIC_IDEMPOTENCY_TTL_SECONDS?: string
17
- ENV?: string
18
- }
19
-
20
- type Variables = {
21
- jwtPayload: { sub: string; email?: string }
22
- getSeed: (slug: string) => Seed | null
23
- seedRegistry: Record<string, Seed>
24
- }
25
-
26
- function errorMessage(c: Context<{ Bindings: Bindings; Variables: Variables }>, err: unknown): string {
27
- if (c.env.ENV !== 'production' && err instanceof Error) return err.message
28
- return 'An unexpected error occurred.'
29
- }
30
-
31
- function asRecord(value: unknown): Record<string, unknown> | null {
32
- return value !== null && typeof value === 'object' && !Array.isArray(value)
33
- ? (value as Record<string, unknown>)
34
- : null
35
- }
36
-
37
- function pickSlugFromBody(body: Record<string, unknown>, sanitizedData: Record<string, unknown>): string {
38
- const explicitSlug = cleanStr(body.slug)
39
- if (explicitSlug) return slugify(explicitSlug)
40
- return generateEntrySlug({ title: sanitizedData.title, name: sanitizedData.name })
41
- }
42
-
43
- function parseIdempotencyKey(rawValue: string | undefined): string | null {
44
- if (!rawValue) return null
45
- const key = rawValue.trim()
46
- if (!key || key.length > 128) return null
47
- return key
48
- }
49
-
50
- function toHex(buffer: ArrayBuffer): string {
51
- return [...new Uint8Array(buffer)].map((v) => v.toString(16).padStart(2, '0')).join('')
52
- }
53
-
54
- async function sha256Hex(input: string): Promise<string> {
55
- const data = new TextEncoder().encode(input)
56
- const digest = await crypto.subtle.digest('SHA-256', data)
57
- return toHex(digest)
58
- }
59
-
60
- type StoredIdempotencyRecord = {
61
- idempotency_key: string
62
- request_fingerprint: string
63
- response_status: number
64
- response_body: string
65
- expires_at: number
66
- }
67
-
68
- async function lookupIdempotency(db: D1Database, key: string): Promise<StoredIdempotencyRecord | null> {
69
- return db.prepare(
70
- `SELECT idempotency_key, request_fingerprint, response_status, response_body, expires_at
71
- FROM public_idempotency_keys WHERE idempotency_key = ? LIMIT 1`
72
- ).bind(key).first<StoredIdempotencyRecord>()
73
- }
74
-
75
- async function storeIdempotency(db: D1Database, input: {
76
- key: string; fingerprint: string; responseStatus: number
77
- responseBody: string; expiresAt: number; createdAt: number
78
- }): Promise<void> {
79
- await db.prepare(
80
- `INSERT INTO public_idempotency_keys (idempotency_key, request_fingerprint, response_status, response_body, created_at, expires_at)
81
- VALUES (?, ?, ?, ?, ?, ?)
82
- ON CONFLICT(idempotency_key) DO UPDATE SET
83
- request_fingerprint = excluded.request_fingerprint,
84
- response_status = excluded.response_status,
85
- response_body = excluded.response_body,
86
- created_at = excluded.created_at,
87
- expires_at = excluded.expires_at`
88
- ).bind(input.key, input.fingerprint, input.responseStatus, input.responseBody, input.createdAt, input.expiresAt).run()
89
- }
90
-
91
- export async function publicAddHandler(c: Context<{ Bindings: Bindings; Variables: Variables }>) {
92
- const seedSlug = c.req.param('seed') ?? ''
93
- const seed = c.get('getSeed')(seedSlug)
94
- if (!seed) {
95
- return publicProblem(c, { type: 'seed-not-found', title: 'Seed Not Found', status: 404, detail: `The content type '${seedSlug}' does not exist.` })
96
- }
97
- const access = checkPublicOperation(seed, 'add')
98
- if (!access.ok) {
99
- return publicProblem(c, { type: 'operation-not-allowed', title: access.error.error, status: 403, detail: access.error.message })
100
- }
101
-
102
- let body: Record<string, unknown>
103
- try {
104
- const parsed = await c.req.json<unknown>()
105
- body = asRecord(parsed) ?? {}
106
- } catch {
107
- return publicProblem(c, { type: 'invalid-json-body', title: 'Bad Request', status: 400, detail: 'Invalid JSON body' })
108
- }
109
-
110
- const rawData = asRecord(body.data)
111
- if (!rawData || Object.keys(rawData).length === 0) {
112
- return publicProblem(c, { type: 'invalid-data-object', title: 'Bad Request', status: 400, detail: "Field 'data' is required and must be a non-empty object" })
113
- }
114
-
115
- const statusValue = body.status ?? 'draft'
116
- if (!isValidContentStatus(statusValue)) {
117
- return publicProblem(c, { type: 'invalid-status', title: 'Bad Request', status: 400, detail: 'Invalid status. Allowed values are: draft, review, published' })
118
- }
119
-
120
- const sanitized = sanitizePublicPayload(seed, rawData, {
121
- operation: 'create', allowNull: false, requireAtLeastOneValidField: true, enforceRequiredFields: true,
122
- })
123
- if (!sanitized.ok) {
124
- if (sanitized.status === 422) {
125
- return publicProblem(c, { type: sanitized.code, title: 'Unprocessable Entity', status: 422, detail: sanitized.message })
126
- }
127
- return publicProblem(c, { type: sanitized.code, title: 'Bad Request', status: 400, detail: sanitized.message, errors: sanitized.details })
128
- }
129
-
130
- const idempotencyKey = parseIdempotencyKey(c.req.header('Idempotency-Key'))
131
- const entrySlug = pickSlugFromBody(body, sanitized.data)
132
- const finalSlug = entrySlug || crypto.randomUUID().slice(0, 8)
133
- const table = `content_${seedSlug}`
134
-
135
- try {
136
- const { DB } = c.env
137
- const now = Math.floor(Date.now() / 1000)
138
- const fingerprintPayload = JSON.stringify({ seedSlug, statusValue, slug: cleanStr(body.slug) ?? null, data: sanitized.data })
139
- const fingerprint = await sha256Hex(fingerprintPayload)
140
- const idempotencyTtlSeconds = Math.max(60, Number.parseInt(c.env.PUBLIC_IDEMPOTENCY_TTL_SECONDS ?? '86400', 10) || 86400)
141
-
142
- if (idempotencyKey) {
143
- const existing = await lookupIdempotency(DB, idempotencyKey)
144
- if (existing && existing.expires_at >= now) {
145
- if (existing.request_fingerprint !== fingerprint) {
146
- return publicProblem(c, { type: 'idempotency-key-conflict', title: 'Conflict', status: 409, detail: 'Idempotency-Key was already used with a different request payload.' })
147
- }
148
- let parsedBody: unknown = null
149
- try { parsedBody = JSON.parse(existing.response_body) } catch { parsedBody = { success: true } }
150
- return c.json(parsedBody, existing.response_status as 201)
151
- }
152
- }
153
-
154
- const slugExisting = await DB.prepare(`SELECT id FROM ${table} WHERE slug = ? LIMIT 1`).bind(finalSlug).first<{ id: string }>()
155
- if (slugExisting) {
156
- return publicProblem(c, { type: 'slug-conflict', title: 'Conflict', status: 409, detail: `An entry with slug '${finalSlug}' already exists for content type '${seedSlug}'.` })
157
- }
158
-
159
- const id = crypto.randomUUID()
160
- const { cols, placeholders, bindings } = buildInsertBindings(seed, sanitized.data)
161
- const systemCols = ['id', 'slug', 'status', 'created_at', 'updated_at']
162
- const systemVals = [id, finalSlug, statusValue, now, now]
163
- const allCols = [...systemCols, ...cols].join(', ')
164
- const allPlaceholders = [...systemVals.map(() => '?'), ...placeholders].join(', ')
165
-
166
- await DB.prepare(`INSERT INTO ${table} (${allCols}) VALUES (${allPlaceholders})`).bind(...systemVals, ...bindings).run()
167
-
168
- const responseBody = { success: true, id, slug: finalSlug }
169
- if (idempotencyKey) {
170
- await storeIdempotency(DB, { key: idempotencyKey, fingerprint, responseStatus: 201, responseBody: JSON.stringify(responseBody), createdAt: now, expiresAt: now + idempotencyTtlSeconds })
171
- }
172
-
173
- await createNotification(c, {
174
- title: `${seed.label}: Nuovo inserimento`,
175
- message: `Una nuova entry ("${sanitized.data.title || sanitized.data.name || finalSlug}") è stata aggiunta via API pubblica.`,
176
- type: 'success',
177
- })
178
-
179
- return c.json(responseBody, 201)
180
- } catch (err) {
181
- return publicProblem(c, { type: 'internal-server-error', title: 'Internal Server Error', status: 500, detail: errorMessage(c, err) })
182
- }
183
- }
1
+ import { isValidContentStatus, SlugConflictError } from '@beechcms/core'
2
+ import type { Context } from 'hono'
3
+ import { cleanStr } from '../shared/query-utils'
4
+ import { checkPublicOperation } from './access-policy'
5
+ import { publicProblem } from './problem-details'
6
+ import { generateEntrySlug, slugify } from './slug-utils'
7
+ import { sanitizePublicPayload } from './sanitize'
8
+ import { createNotification } from '../shared/notification-service'
9
+ import { AppEnv } from '../types'
10
+
11
+ function errorMessage(context: Context<AppEnv>, error: unknown): string {
12
+ if (context.env.ENV !== 'production' && error instanceof Error) return error.message
13
+ return 'An unexpected error occurred.'
14
+ }
15
+
16
+ function asRecord(value: unknown): Record<string, unknown> | null {
17
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
18
+ ? (value as Record<string, unknown>)
19
+ : null
20
+ }
21
+
22
+ function pickSlugFromBody(body: Record<string, unknown>, sanitizedData: Record<string, unknown>): string {
23
+ const explicitSlug = cleanStr(body.slug)
24
+ if (explicitSlug) return slugify(explicitSlug)
25
+ return generateEntrySlug({ title: sanitizedData.title, name: sanitizedData.name })
26
+ }
27
+
28
+ function parseIdempotencyKey(rawValue: string | undefined): string | null {
29
+ if (!rawValue) return null
30
+ const key = rawValue.trim()
31
+ if (!key || key.length > 128) return null
32
+ return key
33
+ }
34
+
35
+ function toHex(buffer: ArrayBuffer): string {
36
+ return [...new Uint8Array(buffer)].map((v) => v.toString(16).padStart(2, '0')).join('')
37
+ }
38
+
39
+ async function sha256Hex(input: string): Promise<string> {
40
+ const data = new TextEncoder().encode(input)
41
+ const digest = await crypto.subtle.digest('SHA-256', data)
42
+ return toHex(digest)
43
+ }
44
+
45
+ export async function publicAddHandler(context: Context<AppEnv>) {
46
+ const seedSlug = context.req.param('seed') ?? ''
47
+ const seed = context.get('getSeed')(seedSlug)
48
+ if (!seed) {
49
+ return publicProblem(context, {
50
+ type: 'seed-not-found',
51
+ title: 'Seed Not Found',
52
+ status: 404,
53
+ detail: `The content type '${seedSlug}' does not exist.`
54
+ })
55
+ }
56
+
57
+ const access = checkPublicOperation(seed, 'add')
58
+ if (!access.ok) {
59
+ return publicProblem(context, {
60
+ type: 'operation-not-allowed',
61
+ title: access.error.error,
62
+ status: 403,
63
+ detail: access.error.message
64
+ })
65
+ }
66
+
67
+ let body: Record<string, unknown>
68
+ try {
69
+ const parsed = await context.req.json<unknown>()
70
+ body = asRecord(parsed) ?? {}
71
+ } catch {
72
+ return publicProblem(context, { type: 'invalid-json-body', title: 'Bad Request', status: 400, detail: 'Invalid JSON body' })
73
+ }
74
+
75
+ const rawData = asRecord(body.data)
76
+ if (!rawData || Object.keys(rawData).length === 0) {
77
+ return publicProblem(context, { type: 'invalid-data-object', title: 'Bad Request', status: 400, detail: "Field 'data' is required and must be a non-empty object" })
78
+ }
79
+
80
+ const statusValue = body.status ?? 'draft'
81
+ if (!isValidContentStatus(statusValue)) {
82
+ return publicProblem(context, { type: 'invalid-status', title: 'Bad Request', status: 400, detail: 'Invalid status. Allowed values are: draft, review, published' })
83
+ }
84
+
85
+ const sanitized = sanitizePublicPayload(seed, rawData, {
86
+ operation: 'create',
87
+ allowNull: false,
88
+ requireAtLeastOneValidField: true,
89
+ enforceRequiredFields: true,
90
+ })
91
+
92
+ if (!sanitized.ok) {
93
+ if (sanitized.status === 422) {
94
+ return publicProblem(context, { type: sanitized.code, title: 'Unprocessable Entity', status: 422, detail: sanitized.message })
95
+ }
96
+ return publicProblem(context, { type: sanitized.code, title: 'Bad Request', status: 400, detail: sanitized.message, errors: sanitized.details })
97
+ }
98
+
99
+ const idempotencyKey = parseIdempotencyKey(context.req.header('Idempotency-Key'))
100
+ const entrySlug = pickSlugFromBody(body, sanitized.data)
101
+ const finalSlug = entrySlug || crypto.randomUUID().slice(0, 8)
102
+ const repository = context.get('repository')
103
+ const idempotencyRepository = context.get('idempotencyRepository')
104
+
105
+ try {
106
+ const now = Math.floor(Date.now() / 1000)
107
+ const fingerprintPayload = JSON.stringify({ seedSlug, statusValue, slug: cleanStr(body.slug) ?? null, data: sanitized.data })
108
+ const fingerprint = await sha256Hex(fingerprintPayload)
109
+ const idempotencyTtlSeconds = Math.max(60, Number.parseInt(context.env.PUBLIC_IDEMPOTENCY_TTL_SECONDS ?? '86400', 10) || 86400)
110
+
111
+ if (idempotencyKey) {
112
+ const existing = await idempotencyRepository.lookup(idempotencyKey)
113
+ if (existing && existing.expiresAt >= now) {
114
+ if (existing.fingerprint !== fingerprint) {
115
+ return publicProblem(context, { type: 'idempotency-key-conflict', title: 'Conflict', status: 409, detail: 'Idempotency-Key was already used with a different request payload.' })
116
+ }
117
+ let parsedBody: unknown = null
118
+ try { parsedBody = JSON.parse(existing.responseBody) } catch { parsedBody = { success: true } }
119
+ return context.json(parsedBody, existing.responseStatus as 201)
120
+ }
121
+ }
122
+
123
+ const id = crypto.randomUUID()
124
+
125
+ try {
126
+ await repository.create(seed, id, finalSlug, statusValue as any, sanitized.data)
127
+ } catch (error) {
128
+ if (error instanceof SlugConflictError) {
129
+ return publicProblem(context, {
130
+ type: 'slug-conflict',
131
+ title: 'Conflict',
132
+ status: 409,
133
+ detail: `An entry with slug '${finalSlug}' already exists for content type '${seedSlug}'.`
134
+ })
135
+ }
136
+ throw error
137
+ }
138
+
139
+ const responseBody = { success: true, id, slug: finalSlug }
140
+ if (idempotencyKey) {
141
+ await idempotencyRepository.store({
142
+ key: idempotencyKey,
143
+ fingerprint,
144
+ responseStatus: 201,
145
+ responseBody: JSON.stringify(responseBody),
146
+ expiresAt: now + idempotencyTtlSeconds
147
+ })
148
+ }
149
+
150
+ await createNotification(context, {
151
+ title: `${seed.label}: New entry`,
152
+ message: `A new entry ("${sanitized.data.title || sanitized.data.name || finalSlug}") has been added via the public API.`,
153
+ type: 'success',
154
+ })
155
+
156
+ return context.json(responseBody, 201)
157
+ } catch (error) {
158
+ console.error('Public add error:', error)
159
+ return publicProblem(context, {
160
+ type: 'internal-server-error',
161
+ title: 'Internal Server Error',
162
+ status: 500,
163
+ detail: errorMessage(context, error)
164
+ })
165
+ }
166
+ }