@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.
- package/assets/dashboard/BeechLogo.svg +18 -18
- package/assets/dashboard/BeechLogoLIght.svg +48 -48
- package/assets/dashboard/assets/index-CH13idU1.js +554 -0
- package/assets/dashboard/assets/index-CewtCjom.css +1 -0
- package/assets/dashboard/beechLogoDark.svg +48 -48
- package/assets/dashboard/index.html +18 -18
- package/assets/dashboard/sol.svg +3 -3
- package/assets/dashboard/undraw_enter_nwx3.svg +36 -36
- package/migrations/0000_v040_base.sql +213 -213
- package/package.json +2 -2
- package/src/auth/bcrypt-hash-provider.ts +20 -0
- package/src/auth/constants.ts +10 -10
- package/src/auth/generate-refresh-token.test.ts +19 -0
- package/src/auth/hash-provider.test.ts +46 -0
- package/src/auth/in-memory-hash-provider.ts +13 -0
- package/src/auth/jose-token-service.ts +55 -0
- package/src/auth/login.test.ts +92 -0
- package/src/auth/login.ts +74 -91
- package/src/auth/refresh.ts +5 -127
- package/src/auth/static-token-service.ts +18 -0
- package/src/auth/token-service.test.ts +82 -0
- package/src/factory.ts +339 -303
- package/src/features/content/constants.ts +10 -0
- package/src/features/content/handlers/create.ts +157 -0
- package/src/features/content/handlers/delete.ts +80 -0
- package/src/features/content/handlers/facets.ts +45 -0
- package/src/features/content/handlers/get.ts +116 -0
- package/src/features/content/handlers/list.ts +88 -0
- package/src/features/content/handlers/update.ts +211 -0
- package/src/features/content/index.ts +20 -0
- package/src/features/draft/draft.handler.ts +283 -198
- package/src/features/draft/index.ts +1 -1
- package/src/features/email/email.provider.ts +38 -38
- package/src/features/email/email.service.ts +80 -80
- package/src/features/email/email.types.ts +98 -98
- package/src/features/email/index.ts +28 -28
- package/src/features/email/providers/resend.ts +63 -63
- package/src/features/email/templates/password-changed.ts +59 -59
- package/src/features/email/templates/password-reset.ts +64 -64
- package/src/features/email/templates/shell.ts +92 -93
- package/src/features/notifications/index.ts +1 -1
- package/src/features/notifications/notifications.handler.ts +101 -88
- package/src/features/password-reset/index.ts +15 -15
- package/src/features/password-reset/request.ts +82 -88
- package/src/features/password-reset/reset.ts +92 -110
- package/src/features/rotate-field/index.ts +1 -1
- package/src/features/rotate-field/rotate-field.handler.ts +128 -82
- package/src/features/rotate-field/rotate-field.schema.ts +13 -9
- package/src/features/schema/schema.handler.ts +16 -16
- package/src/features/settings/settings.handler.ts +301 -249
- package/src/features/setup/index.ts +91 -59
- package/src/features/stats/index.ts +1 -1
- package/src/features/stats/stats.handler.ts +430 -395
- package/src/index.ts +24 -11
- package/src/media-utils.ts +78 -78
- package/src/middleware/auth-providers.middleware.ts +32 -0
- package/src/middleware/observability.middleware.ts +52 -0
- package/src/middleware/rate-limit.middleware.ts +41 -0
- package/src/middleware/repository.middleware.ts +60 -0
- package/src/middleware/storage.middleware.ts +21 -0
- package/src/middleware.ts +47 -67
- package/src/public/access-policy.ts +23 -23
- package/src/public/api-key-middleware.ts +53 -53
- package/src/public/index.ts +12 -12
- package/src/public/problem-details.ts +48 -42
- package/src/public/public-add.ts +156 -183
- package/src/public/public-edit.ts +159 -183
- package/src/public/public-errors.ts +15 -15
- package/src/public/public-read.ts +216 -217
- package/src/public/public-routes.ts +84 -31
- package/src/public/query-builder.test.ts +220 -0
- package/src/public/query-builder.ts +152 -241
- package/src/public/rate-limit-middleware.ts +30 -42
- package/src/public/response-builder.ts +26 -26
- package/src/public/sanitize.ts +65 -65
- package/src/public/slug-utils.ts +14 -14
- package/src/rate-limit/cloudflare-rate-limiter.test.ts +26 -0
- package/src/rate-limit/cloudflare-rate-limiter.ts +11 -0
- package/src/rate-limit/in-memory-rate-limiter.test.ts +33 -0
- package/src/rate-limit/in-memory-rate-limiter.ts +13 -0
- package/src/rate-limit/no-op-rate-limiter.test.ts +18 -0
- package/src/rate-limit/no-op-rate-limiter.ts +7 -0
- package/src/search-utils.test.ts +207 -0
- package/src/search-utils.ts +209 -192
- package/src/search.ts +61 -72
- package/src/shared/apply-policies.test.ts +77 -0
- package/src/shared/apply-policies.ts +63 -63
- package/src/shared/background-notification-service.test.ts +58 -0
- package/src/shared/background-notification-service.ts +48 -0
- package/src/shared/base.repository.d1.ts +28 -0
- package/src/shared/content-utils.test.ts +161 -0
- package/src/shared/content-utils.ts +82 -108
- package/src/shared/content.repository.d1.test.ts +312 -0
- package/src/shared/content.repository.d1.ts +382 -0
- package/src/shared/d1-activity-log.repository.test.ts +136 -0
- package/src/shared/d1-activity-log.repository.ts +101 -0
- package/src/shared/d1-activity-logger.test.ts +82 -0
- package/src/shared/d1-activity-logger.ts +63 -0
- package/src/shared/d1-analytics.repository.test.ts +74 -0
- package/src/shared/d1-analytics.repository.ts +81 -0
- package/src/shared/d1-content-scan.repository.ts +29 -0
- package/src/shared/d1-notification.repository.test.ts +124 -0
- package/src/shared/d1-notification.repository.ts +114 -0
- package/src/shared/d1-password-reset-token.repository.test.ts +77 -0
- package/src/shared/d1-password-reset-token.repository.ts +52 -0
- package/src/shared/d1-search.repository.test.ts +83 -0
- package/src/shared/d1-search.repository.ts +84 -0
- package/src/shared/d1-session.repository.test.ts +121 -0
- package/src/shared/d1-session.repository.ts +98 -0
- package/src/shared/d1-user.repository.test.ts +147 -0
- package/src/shared/d1-user.repository.ts +109 -0
- package/src/shared/d1-widget.repository.test.ts +217 -0
- package/src/shared/d1-widget.repository.ts +337 -0
- package/src/shared/fixed-clock.ts +21 -0
- package/src/shared/fts-sync.ts +4 -4
- package/src/shared/idempotency.repository.d1.test.ts +79 -0
- package/src/shared/idempotency.repository.d1.ts +56 -0
- package/src/shared/in-memory-activity-logger.ts +15 -0
- package/src/shared/in-memory-notification-service.ts +15 -0
- package/src/shared/media.repository.d1.test.ts +103 -0
- package/src/shared/media.repository.d1.ts +64 -0
- package/src/shared/query-utils.ts +137 -137
- package/src/shared/request-utils.ts +22 -0
- package/src/shared/sequential-id-generator.ts +22 -0
- package/src/shared/storage/factory.ts +40 -0
- package/src/shared/storage/r2-binding-bucket.ts +81 -0
- package/src/shared/storage/s3-bucket.ts +163 -0
- package/src/shared/storage-utils.ts +36 -36
- package/src/shared/system-stats.repository.d1.test.ts +54 -0
- package/src/shared/system-stats.repository.d1.ts +44 -0
- package/src/types.ts +63 -36
- package/src/upload.ts +186 -335
- package/src/widget.ts +208 -349
- package/assets/dashboard/assets/index-CC-jbp6g.js +0 -554
- package/assets/dashboard/assets/index-CQODXprH.css +0 -1
- package/src/content.ts +0 -502
- package/src/features/draft/draft.test.ts +0 -315
- package/src/features/rotate-field/rotate-field.test.ts +0 -297
- package/src/shared/activity-logger.ts +0 -79
- 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
|
+
|
package/src/public/index.ts
CHANGED
|
@@ -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
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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
|
+
}
|
package/src/public/public-add.ts
CHANGED
|
@@ -1,183 +1,156 @@
|
|
|
1
|
-
import { isValidContentStatus } from '@beechcms/core'
|
|
2
|
-
import type {
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
const
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
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
|
+
}
|