@beechcms/api 0.4.0-preview.9 → 0.4.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 (140) hide show
  1. package/assets/dashboard/BeechLogo.svg +18 -18
  2. package/assets/dashboard/BeechLogoLIght.svg +48 -48
  3. package/assets/dashboard/assets/index-CH13idU1.js +554 -0
  4. package/assets/dashboard/assets/index-CewtCjom.css +1 -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/bcrypt-hash-provider.ts +20 -0
  12. package/src/auth/constants.ts +10 -10
  13. package/src/auth/generate-refresh-token.test.ts +19 -0
  14. package/src/auth/hash-provider.test.ts +46 -0
  15. package/src/auth/in-memory-hash-provider.ts +13 -0
  16. package/src/auth/jose-token-service.ts +55 -0
  17. package/src/auth/login.test.ts +92 -0
  18. package/src/auth/login.ts +74 -91
  19. package/src/auth/refresh.ts +5 -127
  20. package/src/auth/static-token-service.ts +18 -0
  21. package/src/auth/token-service.test.ts +82 -0
  22. package/src/factory.ts +339 -303
  23. package/src/features/content/constants.ts +10 -0
  24. package/src/features/content/handlers/create.ts +157 -0
  25. package/src/features/content/handlers/delete.ts +80 -0
  26. package/src/features/content/handlers/facets.ts +45 -0
  27. package/src/features/content/handlers/get.ts +116 -0
  28. package/src/features/content/handlers/list.ts +88 -0
  29. package/src/features/content/handlers/update.ts +211 -0
  30. package/src/features/content/index.ts +20 -0
  31. package/src/features/draft/draft.handler.ts +283 -198
  32. package/src/features/draft/index.ts +1 -1
  33. package/src/features/email/email.provider.ts +38 -38
  34. package/src/features/email/email.service.ts +80 -80
  35. package/src/features/email/email.types.ts +98 -98
  36. package/src/features/email/index.ts +28 -28
  37. package/src/features/email/providers/resend.ts +63 -63
  38. package/src/features/email/templates/password-changed.ts +59 -59
  39. package/src/features/email/templates/password-reset.ts +64 -64
  40. package/src/features/email/templates/shell.ts +92 -93
  41. package/src/features/notifications/index.ts +1 -1
  42. package/src/features/notifications/notifications.handler.ts +101 -88
  43. package/src/features/password-reset/index.ts +15 -15
  44. package/src/features/password-reset/request.ts +82 -88
  45. package/src/features/password-reset/reset.ts +92 -110
  46. package/src/features/rotate-field/index.ts +1 -1
  47. package/src/features/rotate-field/rotate-field.handler.ts +128 -82
  48. package/src/features/rotate-field/rotate-field.schema.ts +13 -9
  49. package/src/features/schema/schema.handler.ts +16 -16
  50. package/src/features/settings/settings.handler.ts +301 -249
  51. package/src/features/setup/index.ts +91 -59
  52. package/src/features/stats/index.ts +1 -1
  53. package/src/features/stats/stats.handler.ts +430 -395
  54. package/src/index.ts +24 -11
  55. package/src/media-utils.ts +78 -78
  56. package/src/middleware/auth-providers.middleware.ts +32 -0
  57. package/src/middleware/observability.middleware.ts +52 -0
  58. package/src/middleware/rate-limit.middleware.ts +41 -0
  59. package/src/middleware/repository.middleware.ts +60 -0
  60. package/src/middleware/storage.middleware.ts +21 -0
  61. package/src/middleware.ts +47 -67
  62. package/src/public/access-policy.ts +23 -23
  63. package/src/public/api-key-middleware.ts +53 -53
  64. package/src/public/index.ts +12 -12
  65. package/src/public/problem-details.ts +48 -42
  66. package/src/public/public-add.ts +156 -183
  67. package/src/public/public-edit.ts +159 -183
  68. package/src/public/public-errors.ts +15 -15
  69. package/src/public/public-read.ts +216 -217
  70. package/src/public/public-routes.ts +84 -31
  71. package/src/public/query-builder.test.ts +220 -0
  72. package/src/public/query-builder.ts +152 -241
  73. package/src/public/rate-limit-middleware.ts +30 -42
  74. package/src/public/response-builder.ts +26 -26
  75. package/src/public/sanitize.ts +65 -65
  76. package/src/public/slug-utils.ts +14 -14
  77. package/src/rate-limit/cloudflare-rate-limiter.test.ts +26 -0
  78. package/src/rate-limit/cloudflare-rate-limiter.ts +11 -0
  79. package/src/rate-limit/in-memory-rate-limiter.test.ts +33 -0
  80. package/src/rate-limit/in-memory-rate-limiter.ts +13 -0
  81. package/src/rate-limit/no-op-rate-limiter.test.ts +18 -0
  82. package/src/rate-limit/no-op-rate-limiter.ts +7 -0
  83. package/src/search-utils.test.ts +207 -0
  84. package/src/search-utils.ts +209 -192
  85. package/src/search.ts +61 -72
  86. package/src/shared/apply-policies.test.ts +77 -0
  87. package/src/shared/apply-policies.ts +63 -63
  88. package/src/shared/background-notification-service.test.ts +58 -0
  89. package/src/shared/background-notification-service.ts +48 -0
  90. package/src/shared/base.repository.d1.ts +28 -0
  91. package/src/shared/content-utils.test.ts +161 -0
  92. package/src/shared/content-utils.ts +82 -108
  93. package/src/shared/content.repository.d1.test.ts +312 -0
  94. package/src/shared/content.repository.d1.ts +382 -0
  95. package/src/shared/d1-activity-log.repository.test.ts +136 -0
  96. package/src/shared/d1-activity-log.repository.ts +101 -0
  97. package/src/shared/d1-activity-logger.test.ts +82 -0
  98. package/src/shared/d1-activity-logger.ts +63 -0
  99. package/src/shared/d1-analytics.repository.test.ts +74 -0
  100. package/src/shared/d1-analytics.repository.ts +81 -0
  101. package/src/shared/d1-content-scan.repository.ts +29 -0
  102. package/src/shared/d1-notification.repository.test.ts +124 -0
  103. package/src/shared/d1-notification.repository.ts +114 -0
  104. package/src/shared/d1-password-reset-token.repository.test.ts +77 -0
  105. package/src/shared/d1-password-reset-token.repository.ts +52 -0
  106. package/src/shared/d1-search.repository.test.ts +83 -0
  107. package/src/shared/d1-search.repository.ts +84 -0
  108. package/src/shared/d1-session.repository.test.ts +121 -0
  109. package/src/shared/d1-session.repository.ts +98 -0
  110. package/src/shared/d1-user.repository.test.ts +147 -0
  111. package/src/shared/d1-user.repository.ts +109 -0
  112. package/src/shared/d1-widget.repository.test.ts +217 -0
  113. package/src/shared/d1-widget.repository.ts +337 -0
  114. package/src/shared/fixed-clock.ts +21 -0
  115. package/src/shared/fts-sync.ts +4 -4
  116. package/src/shared/idempotency.repository.d1.test.ts +79 -0
  117. package/src/shared/idempotency.repository.d1.ts +56 -0
  118. package/src/shared/in-memory-activity-logger.ts +15 -0
  119. package/src/shared/in-memory-notification-service.ts +15 -0
  120. package/src/shared/media.repository.d1.test.ts +103 -0
  121. package/src/shared/media.repository.d1.ts +64 -0
  122. package/src/shared/query-utils.ts +137 -137
  123. package/src/shared/request-utils.ts +22 -0
  124. package/src/shared/sequential-id-generator.ts +22 -0
  125. package/src/shared/storage/factory.ts +40 -0
  126. package/src/shared/storage/r2-binding-bucket.ts +81 -0
  127. package/src/shared/storage/s3-bucket.ts +163 -0
  128. package/src/shared/storage-utils.ts +36 -36
  129. package/src/shared/system-stats.repository.d1.test.ts +54 -0
  130. package/src/shared/system-stats.repository.d1.ts +44 -0
  131. package/src/types.ts +63 -36
  132. package/src/upload.ts +186 -335
  133. package/src/widget.ts +208 -349
  134. package/assets/dashboard/assets/index-CC-jbp6g.js +0 -554
  135. package/assets/dashboard/assets/index-CQODXprH.css +0 -1
  136. package/src/content.ts +0 -502
  137. package/src/features/draft/draft.test.ts +0 -315
  138. package/src/features/rotate-field/rotate-field.test.ts +0 -297
  139. package/src/shared/activity-logger.ts +0 -79
  140. package/src/shared/notification-service.ts +0 -56
@@ -1,53 +1,53 @@
1
- import type { Context, Next } from 'hono'
2
- import { PUBLIC_ERRORS } from './public-errors'
3
- import { publicProblem } from './problem-details'
4
-
5
- type PublicBindings = {
6
- PUBLIC_READ_API_KEY?: string
7
- PUBLIC_WRITE_API_KEY?: string
8
- }
9
-
10
- function isReadMethod(method: string): boolean {
11
- return method === 'GET' || method === 'HEAD' || method === 'OPTIONS'
12
- }
13
-
14
- function getConfiguredKey(env: PublicBindings, method: string): string | undefined {
15
- if (isReadMethod(method)) {
16
- return env.PUBLIC_READ_API_KEY
17
- }
18
- return env.PUBLIC_WRITE_API_KEY
19
- }
20
-
21
- /**
22
- * API key auth middleware for Public API routes.
23
- * Uses X-API-Key header only.
24
- */
25
- export function apiKeyMiddleware() {
26
- return async (c: Context, next: Next): Promise<Response | void> => {
27
- const env = c.env as PublicBindings
28
- const configuredKey = getConfiguredKey(env, c.req.method)
29
-
30
- if (!configuredKey) {
31
- return publicProblem(c, {
32
- type: 'public-api-not-configured',
33
- title: PUBLIC_ERRORS.API_KEY_FORBIDDEN.error,
34
- status: 403,
35
- detail: PUBLIC_ERRORS.API_KEY_FORBIDDEN.message,
36
- })
37
- }
38
-
39
- const providedKey = c.req.header('X-API-Key')
40
-
41
- if (!providedKey || providedKey !== configuredKey) {
42
- return publicProblem(c, {
43
- type: 'public-api-key-unauthorized',
44
- title: PUBLIC_ERRORS.API_KEY_UNAUTHORIZED.error,
45
- status: 401,
46
- detail: PUBLIC_ERRORS.API_KEY_UNAUTHORIZED.message,
47
- })
48
- }
49
-
50
- await next()
51
- }
52
- }
53
-
1
+ import type { Context, Next } from 'hono'
2
+ import { PUBLIC_ERRORS } from './public-errors'
3
+ import { publicProblem } from './problem-details'
4
+
5
+ type PublicBindings = {
6
+ PUBLIC_READ_API_KEY?: string
7
+ PUBLIC_WRITE_API_KEY?: string
8
+ }
9
+
10
+ function isReadMethod(method: string): boolean {
11
+ return method === 'GET' || method === 'HEAD' || method === 'OPTIONS'
12
+ }
13
+
14
+ function getConfiguredKey(env: PublicBindings, method: string): string | undefined {
15
+ if (isReadMethod(method)) {
16
+ return env.PUBLIC_READ_API_KEY
17
+ }
18
+ return env.PUBLIC_WRITE_API_KEY
19
+ }
20
+
21
+ /**
22
+ * API key auth middleware for Public API routes.
23
+ * Uses X-API-Key header only.
24
+ */
25
+ export function apiKeyMiddleware() {
26
+ return async (c: Context, next: Next): Promise<Response | void> => {
27
+ const env = c.env as PublicBindings
28
+ const configuredKey = getConfiguredKey(env, c.req.method)
29
+
30
+ if (!configuredKey) {
31
+ return publicProblem(c, {
32
+ type: 'public-api-not-configured',
33
+ title: PUBLIC_ERRORS.API_KEY_FORBIDDEN.error,
34
+ status: 403,
35
+ detail: PUBLIC_ERRORS.API_KEY_FORBIDDEN.message,
36
+ })
37
+ }
38
+
39
+ const providedKey = c.req.header('X-API-Key')
40
+
41
+ if (!providedKey || providedKey !== configuredKey) {
42
+ return publicProblem(c, {
43
+ type: 'public-api-key-unauthorized',
44
+ title: PUBLIC_ERRORS.API_KEY_UNAUTHORIZED.error,
45
+ status: 401,
46
+ detail: PUBLIC_ERRORS.API_KEY_UNAUTHORIZED.message,
47
+ })
48
+ }
49
+
50
+ await next()
51
+ }
52
+ }
53
+
@@ -1,12 +1,12 @@
1
- export { apiKeyMiddleware } from './api-key-middleware'
2
- export { publicRateLimitMiddleware } from './rate-limit-middleware'
3
- export { publicRoutes } from './public-routes'
4
- export { PUBLIC_ERRORS } from './public-errors'
5
- export { sanitizePublicPayload } from './sanitize'
6
- export { generateEntrySlug, slugify } from './slug-utils'
7
- export { buildPublicListMeta, buildPublicSingleMeta } from './response-builder'
8
- export { parseLatestCount, parsePublicPagination } from './query-builder'
9
- export { publicReadHandler } from './public-read'
10
- export { publicAddHandler } from './public-add'
11
- export { publicEditHandler } from './public-edit'
12
-
1
+ export { apiKeyMiddleware } from './api-key-middleware'
2
+ export { publicRateLimitMiddleware } from './rate-limit-middleware'
3
+ export { publicRoutes } from './public-routes'
4
+ export { PUBLIC_ERRORS } from './public-errors'
5
+ export { sanitizePublicPayload } from './sanitize'
6
+ export { generateEntrySlug, slugify } from './slug-utils'
7
+ export { buildPublicListMeta, buildPublicSingleMeta } from './response-builder'
8
+ export { parseLatestCount, parsePublicPagination } from './query-builder'
9
+ export { publicReadHandler } from './public-read'
10
+ export { publicAddHandler } from './public-add'
11
+ export { publicEditHandler } from './public-edit'
12
+
@@ -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,183 +1,156 @@
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, sha256hex } 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 { AppEnv } from '../types'
9
+
10
+ function errorMessage(context: Context<AppEnv>, error: unknown): string {
11
+ if (context.env.ENV !== 'production' && error instanceof Error) return error.message
12
+ return 'An unexpected error occurred.'
13
+ }
14
+
15
+ function asRecord(value: unknown): Record<string, unknown> | null {
16
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
17
+ ? (value as Record<string, unknown>)
18
+ : null
19
+ }
20
+
21
+ function pickSlugFromBody(body: Record<string, unknown>, sanitizedData: Record<string, unknown>): string {
22
+ const explicitSlug = cleanStr(body.slug)
23
+ if (explicitSlug) return slugify(explicitSlug)
24
+ return generateEntrySlug({ title: sanitizedData.title, name: sanitizedData.name })
25
+ }
26
+
27
+ function parseIdempotencyKey(rawValue: string | undefined): string | null {
28
+ if (!rawValue) return null
29
+ const key = rawValue.trim()
30
+ if (!key || key.length > 128) return null
31
+ return key
32
+ }
33
+
34
+
35
+ export async function publicAddHandler(context: Context<AppEnv>) {
36
+ const seedSlug = context.req.param('seed') ?? ''
37
+ const seed = context.get('getSeed')(seedSlug)
38
+ if (!seed) {
39
+ return publicProblem(context, {
40
+ type: 'seed-not-found',
41
+ title: 'Seed Not Found',
42
+ status: 404,
43
+ detail: `The content type '${seedSlug}' does not exist.`
44
+ })
45
+ }
46
+
47
+ const access = checkPublicOperation(seed, 'add')
48
+ if (!access.ok) {
49
+ return publicProblem(context, {
50
+ type: 'operation-not-allowed',
51
+ title: access.error.error,
52
+ status: 403,
53
+ detail: access.error.message
54
+ })
55
+ }
56
+
57
+ let body: Record<string, unknown>
58
+ try {
59
+ const parsed = await context.req.json<unknown>()
60
+ body = asRecord(parsed) ?? {}
61
+ } catch {
62
+ return publicProblem(context, { type: 'invalid-json-body', title: 'Bad Request', status: 400, detail: 'Invalid JSON body' })
63
+ }
64
+
65
+ const rawData = asRecord(body.data)
66
+ if (!rawData || Object.keys(rawData).length === 0) {
67
+ return publicProblem(context, { type: 'invalid-data-object', title: 'Bad Request', status: 400, detail: "Field 'data' is required and must be a non-empty object" })
68
+ }
69
+
70
+ const statusValue = body.status ?? 'draft'
71
+ if (!isValidContentStatus(statusValue)) {
72
+ return publicProblem(context, { type: 'invalid-status', title: 'Bad Request', status: 400, detail: 'Invalid status. Allowed values are: draft, review, published' })
73
+ }
74
+
75
+ const sanitized = sanitizePublicPayload(seed, rawData, {
76
+ operation: 'create',
77
+ allowNull: false,
78
+ requireAtLeastOneValidField: true,
79
+ enforceRequiredFields: true,
80
+ })
81
+
82
+ if (!sanitized.ok) {
83
+ if (sanitized.status === 422) {
84
+ return publicProblem(context, { type: sanitized.code, title: 'Unprocessable Entity', status: 422, detail: sanitized.message })
85
+ }
86
+ return publicProblem(context, { type: sanitized.code, title: 'Bad Request', status: 400, detail: sanitized.message, errors: sanitized.details })
87
+ }
88
+
89
+ const idempotencyKey = parseIdempotencyKey(context.req.header('Idempotency-Key'))
90
+ const entrySlug = pickSlugFromBody(body, sanitized.data)
91
+ const finalSlug = entrySlug || context.get('idGenerator').uuid().slice(0, 8)
92
+ const repository = context.get('repository')
93
+ const idempotencyRepository = context.get('idempotencyRepository')
94
+
95
+ try {
96
+ const now = Math.floor(Date.now() / 1000)
97
+ const fingerprintPayload = JSON.stringify({ seedSlug, statusValue, slug: cleanStr(body.slug) ?? null, data: sanitized.data })
98
+ const fingerprint = await sha256hex(fingerprintPayload)
99
+ const idempotencyTtlSeconds = Math.max(60, Number.parseInt(context.env.PUBLIC_IDEMPOTENCY_TTL_SECONDS ?? '86400', 10) || 86400)
100
+
101
+ if (idempotencyKey) {
102
+ const existing = await idempotencyRepository.lookup(idempotencyKey)
103
+ if (existing && existing.expiresAt >= now) {
104
+ if (existing.fingerprint !== fingerprint) {
105
+ return publicProblem(context, { type: 'idempotency-key-conflict', title: 'Conflict', status: 409, detail: 'Idempotency-Key was already used with a different request payload.' })
106
+ }
107
+ let parsedBody: unknown = null
108
+ try { parsedBody = JSON.parse(existing.responseBody) } catch { parsedBody = { success: true } }
109
+ return context.json(parsedBody, existing.responseStatus as 201)
110
+ }
111
+ }
112
+
113
+ const id = context.get('idGenerator').uuid()
114
+
115
+ try {
116
+ await repository.create(seed, id, finalSlug, statusValue as any, sanitized.data)
117
+ } catch (error) {
118
+ if (error instanceof SlugConflictError) {
119
+ return publicProblem(context, {
120
+ type: 'slug-conflict',
121
+ title: 'Conflict',
122
+ status: 409,
123
+ detail: `An entry with slug '${finalSlug}' already exists for content type '${seedSlug}'.`
124
+ })
125
+ }
126
+ throw error
127
+ }
128
+
129
+ const responseBody = { success: true, id, slug: finalSlug }
130
+ if (idempotencyKey) {
131
+ await idempotencyRepository.store({
132
+ key: idempotencyKey,
133
+ fingerprint,
134
+ responseStatus: 201,
135
+ responseBody: JSON.stringify(responseBody),
136
+ expiresAt: now + idempotencyTtlSeconds
137
+ })
138
+ }
139
+
140
+ context.get('notificationService').notify({
141
+ title: `${seed.label}: New entry`,
142
+ message: `A new entry ("${sanitized.data.title || sanitized.data.name || finalSlug}") has been added via the public API.`,
143
+ type: 'success',
144
+ })
145
+
146
+ return context.json(responseBody, 201)
147
+ } catch (error) {
148
+ console.error('Public add error:', error)
149
+ return publicProblem(context, {
150
+ type: 'internal-server-error',
151
+ title: 'Internal Server Error',
152
+ status: 500,
153
+ detail: errorMessage(context, error)
154
+ })
155
+ }
156
+ }