@beechcms/api 0.4.0-preview.12 → 0.4.0-preview.13

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 (85) 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-CTSuGxlX.js → index-FQ6JhvRH.js} +99 -99
  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 -325
  15. package/src/features/content/constants.ts +10 -10
  16. package/src/features/content/handlers/create.ts +153 -163
  17. package/src/features/content/handlers/delete.ts +76 -85
  18. package/src/features/content/handlers/facets.ts +45 -45
  19. package/src/features/content/handlers/get.ts +116 -116
  20. package/src/features/content/handlers/list.ts +88 -88
  21. package/src/features/content/handlers/update.ts +207 -216
  22. package/src/features/content/index.ts +20 -20
  23. package/src/features/draft/draft.handler.ts +272 -272
  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 -267
  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 -24
  47. package/src/media-utils.ts +78 -78
  48. package/src/middleware/repository.middleware.ts +24 -18
  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 -166
  56. package/src/public/public-edit.ts +158 -158
  57. package/src/public/public-errors.ts +15 -15
  58. package/src/public/public-read.ts +216 -216
  59. package/src/public/public-routes.ts +84 -31
  60. package/src/public/query-builder.ts +152 -152
  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 -28
  70. package/src/shared/content-utils.ts +82 -108
  71. package/src/shared/content.repository.d1.ts +382 -382
  72. package/src/shared/fts-sync.ts +4 -4
  73. package/src/shared/idempotency.repository.d1.ts +56 -45
  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 -41
  83. package/src/upload.ts +179 -331
  84. package/src/widget.ts +349 -349
  85. package/assets/dashboard/assets/index-ye3325L9.css +0 -1
@@ -1,42 +1,48 @@
1
- import type { Context } from 'hono'
2
-
3
- export interface PublicProblemDetailItem {
4
- field: string
5
- expected: string
6
- received: string
7
- message: string
8
- }
9
-
10
- type PublicProblemInput = {
11
- type: string
12
- title: string
13
- status: 400 | 401 | 403 | 404 | 405 | 409 | 422 | 429 | 500 | 501
14
- detail: string
15
- errors?: PublicProblemDetailItem[]
16
- }
17
-
18
- function normalizeProblemType(type: string): string {
19
- if (type.startsWith('http://') || type.startsWith('https://')) {
20
- return type
21
- }
22
- return `https://beechcms.dev/problems/${type}`
23
- }
24
-
25
- /**
26
- * Restituisce errori API in formato Problem Details (RFC 9457).
27
- */
28
- export function publicProblem(c: Context, input: PublicProblemInput): Response {
29
- const body: Record<string, unknown> = {
30
- type: normalizeProblemType(input.type),
31
- title: input.title,
32
- status: input.status,
33
- detail: input.detail,
34
- instance: c.req.path,
35
- }
36
- if (input.errors && input.errors.length > 0) {
37
- body.errors = input.errors
38
- }
39
- return c.json(body, input.status, {
40
- 'Content-Type': 'application/problem+json',
41
- })
42
- }
1
+ import type { Context } from 'hono'
2
+
3
+ export interface PublicProblemDetailItem {
4
+ field: string
5
+ expected: string
6
+ received: string
7
+ message: string
8
+ }
9
+
10
+ type PublicProblemInput = {
11
+ type: string
12
+ title: string
13
+ status: 400 | 401 | 403 | 404 | 405 | 409 | 422 | 429 | 500 | 501
14
+ detail: string
15
+ errors?: PublicProblemDetailItem[]
16
+ }
17
+
18
+ /**
19
+ * TODO: UPDATE DOMAIN ONCE REGISTERED
20
+ * Currently uses 'beechcms.dev' as a placeholder.
21
+ * When a real domain is registered for BeechCMS, update the URL below
22
+ * to point to the official API error documentation (RFC 9457).
23
+ */
24
+ function normalizeProblemType(type: string): string {
25
+ if (type.startsWith('http://') || type.startsWith('https://')) {
26
+ return type
27
+ }
28
+ return `https://beechcms.dev/problems/${type}`
29
+ }
30
+
31
+ /**
32
+ * Restituisce errori API in formato Problem Details (RFC 9457).
33
+ */
34
+ export function publicProblem(c: Context, input: PublicProblemInput): Response {
35
+ const body: Record<string, unknown> = {
36
+ type: normalizeProblemType(input.type),
37
+ title: input.title,
38
+ status: input.status,
39
+ detail: input.detail,
40
+ instance: c.req.path,
41
+ }
42
+ if (input.errors && input.errors.length > 0) {
43
+ body.errors = input.errors
44
+ }
45
+ return c.json(body, input.status, {
46
+ 'Content-Type': 'application/problem+json',
47
+ })
48
+ }
@@ -1,166 +1,166 @@
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}: Nuovo inserimento`,
152
- message: `Una nuova entry ("${sanitized.data.title || sanitized.data.name || finalSlug}") è stata aggiunta via API pubblica.`,
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
- }
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
+ }