@beechcms/api 0.4.0-preview.9 → 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,241 +1,152 @@
1
- import type { Seed } from '@beechcms/core'
2
- import { parsePositiveInt } from '../shared/query-utils'
3
-
4
- export type PublicQueryInput = {
5
- page?: string
6
- limit?: string
7
- latest?: string
8
- }
9
-
10
- type PublicFilterLogic = 'AND' | 'OR'
11
- type PublicFilterOperator =
12
- | 'eq'
13
- | 'neq'
14
- | 'gt'
15
- | 'gte'
16
- | 'lt'
17
- | 'lte'
18
- | 'contains'
19
- | 'not_contains'
20
- | 'starts_with'
21
- | 'ends_with'
22
- | 'is_empty'
23
- | 'is_not_empty'
24
- | 'in'
25
- | 'not_in'
26
- | 'has_tag'
27
- | 'has_any_tag'
28
- | 'has_all_tags'
29
-
30
- type PublicFilterCondition = {
31
- field: string
32
- op: PublicFilterOperator
33
- value?: unknown
34
- }
35
-
36
- type ParsedPublicFilter = {
37
- where: PublicFilterCondition[]
38
- logic: PublicFilterLogic
39
- }
40
-
41
- const PUBLIC_FILTER_OPERATORS = new Set<PublicFilterOperator>([
42
- 'eq', 'neq', 'gt', 'gte', 'lt', 'lte',
43
- 'contains', 'not_contains', 'starts_with', 'ends_with',
44
- 'is_empty', 'is_not_empty', 'in', 'not_in',
45
- 'has_tag', 'has_any_tag', 'has_all_tags',
46
- ])
47
-
48
- const SYSTEM_COLUMNS = new Set(['id', 'slug', 'status', 'created_at', 'updated_at'])
49
-
50
- function asString(value: unknown): string | null {
51
- return typeof value === 'string' && value.trim() ? value.trim() : null
52
- }
53
-
54
- /**
55
- * Risolve il nome colonna SQL per un campo.
56
- * In v0.4.0 il nome colonna = branch.alias (nessun json_extract).
57
- */
58
- function resolveFieldExpression(
59
- seed: Seed | null,
60
- field: string
61
- ): { expr: string; fieldType: string } | null {
62
- if (SYSTEM_COLUMNS.has(field)) {
63
- const type = field === 'created_at' || field === 'updated_at' ? 'number' : 'text'
64
- return { expr: field, fieldType: type }
65
- }
66
- const branch = seed?.branches.find((b) => b.alias === field)
67
- if (!branch) return null
68
- return { expr: branch.alias, fieldType: branch.type }
69
- }
70
-
71
- function validateLogic(logicRaw: unknown): PublicFilterLogic {
72
- if (logicRaw === undefined) return 'AND'
73
- if (typeof logicRaw !== 'string') throw new TypeError("Invalid filter: 'logic' must be 'AND' or 'OR'")
74
- const normalized = logicRaw.toUpperCase()
75
- if (normalized !== 'AND' && normalized !== 'OR') throw new TypeError("Invalid filter: 'logic' must be 'AND' or 'OR'")
76
- return normalized
77
- }
78
-
79
- function parseWhereCondition(raw: unknown): PublicFilterCondition | null {
80
- if (!raw || typeof raw !== 'object') return null
81
- const maybe = raw as Record<string, unknown>
82
- const field = asString(maybe.field)
83
- const opRaw = asString(maybe.op)
84
- if (!field || !opRaw || !PUBLIC_FILTER_OPERATORS.has(opRaw as PublicFilterOperator)) {
85
- throw new TypeError(`Invalid filter: unknown operator '${opRaw ?? 'undefined'}'`)
86
- }
87
- return { field, op: opRaw as PublicFilterOperator, value: maybe.value }
88
- }
89
-
90
- export function parsePublicFilter(raw: string | undefined): ParsedPublicFilter | null {
91
- if (!raw) return null
92
- let parsed: unknown
93
- try {
94
- parsed = JSON.parse(raw)
95
- } catch {
96
- throw new TypeError('Invalid filter: malformed JSON')
97
- }
98
- if (!parsed || typeof parsed !== 'object') throw new TypeError('Invalid filter: object expected')
99
- const filterObj = parsed as Record<string, unknown>
100
- const logic = validateLogic(filterObj.logic)
101
- if (!Array.isArray(filterObj.where)) throw new TypeError("Invalid filter: 'where' must be an array")
102
- const where = filterObj.where
103
- .map(parseWhereCondition)
104
- .filter((item): item is PublicFilterCondition => item !== null)
105
- return { where, logic }
106
- }
107
-
108
- function ensureValueArray(value: unknown, op: PublicFilterOperator, field: string): unknown[] {
109
- if (!Array.isArray(value) || value.length === 0) {
110
- throw new TypeError(`Invalid filter: operator '${op}' for field '${field}' requires a non-empty array`)
111
- }
112
- return value
113
- }
114
-
115
- function buildTextOperation(
116
- op: PublicFilterOperator,
117
- expr: string,
118
- field: string,
119
- value: unknown
120
- ): { clause: string; bindings: Array<string | number> } {
121
- const str = asString(value)
122
- if (!str) throw new TypeError(`Invalid filter: operator '${op}' for field '${field}' requires a string value`)
123
- if (op === 'contains') return { clause: `LOWER(CAST(${expr} AS TEXT)) LIKE LOWER(?)`, bindings: [`%${str}%`] }
124
- if (op === 'not_contains') return { clause: `LOWER(CAST(${expr} AS TEXT)) NOT LIKE LOWER(?)`, bindings: [`%${str}%`] }
125
- if (op === 'starts_with') return { clause: `LOWER(CAST(${expr} AS TEXT)) LIKE LOWER(?)`, bindings: [`${str}%`] }
126
- return { clause: `LOWER(CAST(${expr} AS TEXT)) LIKE LOWER(?)`, bindings: [`%${str}`] }
127
- }
128
-
129
- function buildSetOperation(
130
- op: PublicFilterOperator,
131
- expr: string,
132
- field: string,
133
- value: unknown
134
- ): { clause: string; bindings: Array<string | number> } {
135
- const values = ensureValueArray(value, op, field)
136
- const placeholders = values.map(() => '?').join(',')
137
- return {
138
- clause: `${expr} ${op === 'in' ? 'IN' : 'NOT IN'} (${placeholders})`,
139
- bindings: values as Array<string | number>,
140
- }
141
- }
142
-
143
- function buildTagOperation(
144
- op: PublicFilterOperator,
145
- expr: string,
146
- field: string,
147
- value: unknown
148
- ): { clause: string; bindings: Array<string | number> } {
149
- const tags = op === 'has_tag' ? [value] : ensureValueArray(value, op, field)
150
- const cleaned = tags.map((item) => asString(item)).filter((item): item is string => item !== null)
151
- if (cleaned.length === 0) {
152
- throw new TypeError(`Invalid filter: operator '${op}' for field '${field}' requires tag string values`)
153
- }
154
- if (op === 'has_tag' || op === 'has_any_tag') {
155
- const placeholders = cleaned.map(() => '?').join(',')
156
- return {
157
- clause: `EXISTS (SELECT 1 FROM json_each(${expr}) je WHERE CAST(je.value AS TEXT) IN (${placeholders}))`,
158
- bindings: cleaned,
159
- }
160
- }
161
- const allParts = cleaned.map(() => `EXISTS (SELECT 1 FROM json_each(${expr}) je WHERE CAST(je.value AS TEXT) = ?)`)
162
- return { clause: allParts.join(' AND '), bindings: cleaned }
163
- }
164
-
165
- function buildConditionClause(
166
- condition: PublicFilterCondition,
167
- seed: Seed | null
168
- ): { clause: string; bindings: Array<string | number> } | null {
169
- const fieldMeta = resolveFieldExpression(seed, condition.field)
170
- if (!fieldMeta) return null
171
- const { expr, fieldType } = fieldMeta
172
- const { op, value, field } = condition
173
-
174
- if (op === 'is_empty') return { clause: `(${expr} IS NULL OR TRIM(CAST(${expr} AS TEXT)) = '')`, bindings: [] }
175
- if (op === 'is_not_empty') return { clause: `(${expr} IS NOT NULL AND TRIM(CAST(${expr} AS TEXT)) <> '')`, bindings: [] }
176
- if (op === 'contains' || op === 'not_contains' || op === 'starts_with' || op === 'ends_with') {
177
- return buildTextOperation(op, expr, field, value)
178
- }
179
- if (op === 'in' || op === 'not_in') return buildSetOperation(op, expr, field, value)
180
- if (op === 'has_tag' || op === 'has_any_tag' || op === 'has_all_tags') {
181
- if (fieldType !== 'json') throw new TypeError(`Invalid filter: operator '${op}' requires a json field`)
182
- return buildTagOperation(op, expr, field, value)
183
- }
184
-
185
- if (op === 'eq' || op === 'neq') {
186
- if (typeof value === 'boolean') {
187
- return { clause: `${expr} ${op === 'eq' ? '=' : '!='} ?`, bindings: [value ? 1 : 0] }
188
- }
189
- if (typeof value === 'number' && !Number.isNaN(value)) {
190
- return { clause: `${expr} ${op === 'eq' ? '=' : '!='} ?`, bindings: [value] }
191
- }
192
- const textValue = asString(value)
193
- if (!textValue) throw new TypeError(`Invalid filter: operator '${op}' for field '${field}' requires a scalar value`)
194
- return {
195
- clause: `LOWER(TRIM(CAST(${expr} AS TEXT))) ${op === 'eq' ? '=' : '!='} LOWER(TRIM(?))`,
196
- bindings: [textValue],
197
- }
198
- }
199
-
200
- const numberValue = typeof value === 'number' && !Number.isNaN(value) ? value : null
201
- const textValue = asString(value)
202
- const mathOp = op === 'gt' ? '>' : op === 'gte' ? '>=' : op === 'lt' ? '<' : op === 'lte' ? '<=' : null
203
- if (!mathOp) throw new TypeError(`Invalid filter: operator '${op}' is not supported`)
204
- if ((fieldType === 'number' || field === 'created_at' || field === 'updated_at') && numberValue !== null) {
205
- return { clause: `${expr} ${mathOp} ?`, bindings: [numberValue] }
206
- }
207
- if (textValue) return { clause: `CAST(${expr} AS TEXT) ${mathOp} ?`, bindings: [textValue] }
208
- throw new TypeError(`Invalid filter: operator '${op}' for field '${field}' requires a compatible value`)
209
- }
210
-
211
- export function buildPublicFilterWhereClause(
212
- seed: Seed | null,
213
- parsedFilter: ParsedPublicFilter | null
214
- ): { clause: string; bindings: Array<string | number> } {
215
- if (!parsedFilter || parsedFilter.where.length === 0) return { clause: '', bindings: [] }
216
- const clauses: string[] = []
217
- const bindings: Array<string | number> = []
218
- for (const condition of parsedFilter.where) {
219
- const built = buildConditionClause(condition, seed)
220
- if (!built) continue
221
- clauses.push(`(${built.clause})`)
222
- bindings.push(...built.bindings)
223
- }
224
- if (clauses.length === 0) return { clause: '', bindings: [] }
225
- return { clause: clauses.join(` ${parsedFilter.logic} `), bindings }
226
- }
227
-
228
- export function parsePublicPagination(input: PublicQueryInput): { page: number; limit: number } {
229
- const page = parsePositiveInt(input.page, 1)
230
- const limit = Math.min(parsePositiveInt(input.limit, 25), 100)
231
- return { page, limit }
232
- }
233
-
234
- export function parseLatestCount(latest: string | undefined): number {
235
- if (!latest) return 10
236
- const raw = Number.parseInt(latest, 10)
237
- const parsed = Number.isNaN(raw) ? 10 : raw
238
- if (parsed < 1) return 1
239
- if (parsed > 100) return 100
240
- return parsed
241
- }
1
+ import type { Seed, FilterGroup, FilterOperator, FilterType, BranchType } from '@beechcms/core'
2
+ import { parsePositiveInt } from '../shared/query-utils'
3
+
4
+ export type PublicQueryInput = {
5
+ page?: string
6
+ limit?: string
7
+ latest?: string
8
+ }
9
+
10
+ export type PublicFilterLogic = 'AND' | 'OR'
11
+ export type PublicFilterOperator =
12
+ | 'eq'
13
+ | 'neq'
14
+ | 'gt'
15
+ | 'gte'
16
+ | 'lt'
17
+ | 'lte'
18
+ | 'contains'
19
+ | 'not_contains'
20
+ | 'starts_with'
21
+ | 'ends_with'
22
+ | 'is_empty'
23
+ | 'is_not_empty'
24
+ | 'in'
25
+ | 'not_in'
26
+ | 'has_tag'
27
+ | 'has_any_tag'
28
+ | 'has_all_tags'
29
+
30
+ export type PublicFilterCondition = {
31
+ field: string
32
+ op: PublicFilterOperator
33
+ value?: unknown
34
+ }
35
+
36
+ export type ParsedPublicFilter = {
37
+ where: PublicFilterCondition[]
38
+ logic: PublicFilterLogic
39
+ }
40
+
41
+ const PUBLIC_FILTER_OPERATORS = new Set<PublicFilterOperator>([
42
+ 'eq', 'neq', 'gt', 'gte', 'lt', 'lte',
43
+ 'contains', 'not_contains', 'starts_with', 'ends_with',
44
+ 'is_empty', 'is_not_empty', 'in', 'not_in',
45
+ 'has_tag', 'has_any_tag', 'has_all_tags',
46
+ ])
47
+
48
+ function asString(value: unknown): string | null {
49
+ return typeof value === 'string' && value.trim() ? value.trim() : null
50
+ }
51
+
52
+ function validateLogic(logicRaw: unknown): PublicFilterLogic {
53
+ if (logicRaw === undefined) return 'AND'
54
+ if (typeof logicRaw !== 'string') throw new TypeError("Invalid filter: 'logic' must be 'AND' or 'OR'")
55
+ const normalized = logicRaw.toUpperCase()
56
+ if (normalized !== 'AND' && normalized !== 'OR') throw new TypeError("Invalid filter: 'logic' must be 'AND' or 'OR'")
57
+ return normalized
58
+ }
59
+
60
+ function parseWhereCondition(raw: unknown): PublicFilterCondition | null {
61
+ if (!raw || typeof raw !== 'object') return null
62
+ const maybe = raw as Record<string, unknown>
63
+ const field = asString(maybe.field)
64
+ const opRaw = asString(maybe.op)
65
+ if (!field || !opRaw || !PUBLIC_FILTER_OPERATORS.has(opRaw as PublicFilterOperator)) {
66
+ throw new TypeError(`Invalid filter: unknown operator '${opRaw ?? 'undefined'}'`)
67
+ }
68
+ return { field, op: opRaw as PublicFilterOperator, value: maybe.value }
69
+ }
70
+
71
+ export function parsePublicFilter(raw: string | undefined): ParsedPublicFilter | null {
72
+ if (!raw) return null
73
+ let parsed: unknown
74
+ try {
75
+ parsed = JSON.parse(raw)
76
+ } catch {
77
+ throw new TypeError('Invalid filter: malformed JSON')
78
+ }
79
+ if (!parsed || typeof parsed !== 'object') throw new TypeError('Invalid filter: object expected')
80
+ const filterObj = parsed as Record<string, unknown>
81
+ const logic = validateLogic(filterObj.logic)
82
+ if (!Array.isArray(filterObj.where)) throw new TypeError("Invalid filter: 'where' must be an array")
83
+ const where = filterObj.where
84
+ .map(parseWhereCondition)
85
+ .filter((item): item is PublicFilterCondition => item !== null)
86
+ return { where, logic }
87
+ }
88
+
89
+ const SYSTEM_COLUMNS = new Set(['id', 'slug', 'status', 'created_at', 'updated_at'])
90
+
91
+ function mapBranchToFilterType(type: BranchType): FilterType {
92
+ switch (type) {
93
+ case 'richtext':
94
+ case 'file':
95
+ return 'text'
96
+ case 'json':
97
+ return 'json'
98
+ case 'tags':
99
+ return 'tags'
100
+ case 'number':
101
+ return 'number'
102
+ case 'boolean':
103
+ return 'boolean'
104
+ case 'date':
105
+ return 'date'
106
+ case 'text':
107
+ default:
108
+ return 'text'
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Trasforma il filtro pubblico in FilterGroup[] per il Repository.
114
+ * Zero SQL: la logica di generazione query risiede esclusivamente nel Repository/Engine core.
115
+ */
116
+ export function toEngineFilters(seed: Seed, parsedFilter: ParsedPublicFilter | null): FilterGroup[] {
117
+ if (!parsedFilter || parsedFilter.where.length === 0) return []
118
+
119
+ // Note: Repository currently joins groups with AND.
120
+ // Public API supports logic: OR but the core engine currently defaults to AND for top-level groups.
121
+ // We map each condition to a group for maximum compatibility with the engine's buildFilterCondition.
122
+ return parsedFilter.where.map((cond) => {
123
+ const branch = seed.branches.find(b => b.alias === cond.field)
124
+ const type: FilterType = branch
125
+ ? mapBranchToFilterType(branch.type)
126
+ : (SYSTEM_COLUMNS.has(cond.field) ? 'system' : 'text')
127
+
128
+ return {
129
+ column: cond.field,
130
+ type,
131
+ conditions: [{
132
+ op: cond.op as FilterOperator,
133
+ value: cond.value as any
134
+ }]
135
+ }
136
+ })
137
+ }
138
+
139
+ export function parsePublicPagination(input: PublicQueryInput): { page: number; limit: number } {
140
+ const page = parsePositiveInt(input.page, 1)
141
+ const limit = Math.min(parsePositiveInt(input.limit, 25), 100)
142
+ return { page, limit }
143
+ }
144
+
145
+ export function parseLatestCount(latest: string | undefined): number {
146
+ if (!latest) return 10
147
+ const raw = Number.parseInt(latest, 10)
148
+ const parsed = Number.isNaN(raw) ? 10 : raw
149
+ if (parsed < 1) return 1
150
+ if (parsed > 100) return 100
151
+ return parsed
152
+ }
@@ -1,42 +1,42 @@
1
- import type { Context, Next } from 'hono'
2
- import { publicProblem } from './problem-details'
3
-
4
- type PublicBindings = {
5
- PUBLIC_READ_RATE_LIMITER?: RateLimit
6
- PUBLIC_WRITE_RATE_LIMITER?: RateLimit
7
- }
8
-
9
- function isReadMethod(method: string): boolean {
10
- return method === 'GET' || method === 'HEAD' || method === 'OPTIONS'
11
- }
12
-
13
- function getClientIp(headers: Headers): string {
14
- return headers.get('cf-connecting-ip') ?? 'unknown'
15
- }
16
-
17
- export function publicRateLimitMiddleware() {
18
- return async (c: Context, next: Next): Promise<Response | void> => {
19
- const env = c.env as PublicBindings
20
- const readMethod = isReadMethod(c.req.method)
21
- const limiter = readMethod ? env.PUBLIC_READ_RATE_LIMITER : env.PUBLIC_WRITE_RATE_LIMITER
22
- if (!limiter) {
23
- await next()
24
- return
25
- }
26
-
27
- const seed = c.req.param('seed') ?? 'no-seed'
28
- const key = `${getClientIp(c.req.raw.headers)}:${seed}:${readMethod ? 'read' : 'write'}`
29
- const { success } = await limiter.limit({ key })
30
-
31
- if (!success) {
32
- return publicProblem(c, {
33
- type: 'rate-limit-exceeded',
34
- title: 'Too Many Requests',
35
- status: 429,
36
- detail: 'Too many requests',
37
- })
38
- }
39
-
40
- await next()
41
- }
42
- }
1
+ import type { Context, Next } from 'hono'
2
+ import { publicProblem } from './problem-details'
3
+
4
+ type PublicBindings = {
5
+ PUBLIC_READ_RATE_LIMITER?: RateLimit
6
+ PUBLIC_WRITE_RATE_LIMITER?: RateLimit
7
+ }
8
+
9
+ function isReadMethod(method: string): boolean {
10
+ return method === 'GET' || method === 'HEAD' || method === 'OPTIONS'
11
+ }
12
+
13
+ function getClientIp(headers: Headers): string {
14
+ return headers.get('cf-connecting-ip') ?? 'unknown'
15
+ }
16
+
17
+ export function publicRateLimitMiddleware() {
18
+ return async (c: Context, next: Next): Promise<Response | void> => {
19
+ const env = c.env as PublicBindings
20
+ const readMethod = isReadMethod(c.req.method)
21
+ const limiter = readMethod ? env.PUBLIC_READ_RATE_LIMITER : env.PUBLIC_WRITE_RATE_LIMITER
22
+ if (!limiter) {
23
+ await next()
24
+ return
25
+ }
26
+
27
+ const seed = c.req.param('seed') ?? 'no-seed'
28
+ const key = `${getClientIp(c.req.raw.headers)}:${seed}:${readMethod ? 'read' : 'write'}`
29
+ const { success } = await limiter.limit({ key })
30
+
31
+ if (!success) {
32
+ return publicProblem(c, {
33
+ type: 'rate-limit-exceeded',
34
+ title: 'Too Many Requests',
35
+ status: 429,
36
+ detail: 'Too many requests',
37
+ })
38
+ }
39
+
40
+ await next()
41
+ }
42
+ }
@@ -1,26 +1,26 @@
1
- /**
2
- * Helper meta per risposta lista Public API.
3
- */
4
- export function buildPublicListMeta(input: {
5
- total: number
6
- page: number
7
- limit: number
8
- returned: number
9
- seed: string
10
- }) {
11
- return {
12
- total: input.total,
13
- page: input.page,
14
- limit: input.limit,
15
- returned: input.returned,
16
- seed: input.seed,
17
- }
18
- }
19
-
20
- /**
21
- * Helper meta per risposta singolo elemento Public API.
22
- */
23
- export function buildPublicSingleMeta(seed: string) {
24
- return { seed }
25
- }
26
-
1
+ /**
2
+ * Helper meta per risposta lista Public API.
3
+ */
4
+ export function buildPublicListMeta(input: {
5
+ total: number
6
+ page: number
7
+ limit: number
8
+ returned: number
9
+ seed: string
10
+ }) {
11
+ return {
12
+ total: input.total,
13
+ page: input.page,
14
+ limit: input.limit,
15
+ returned: input.returned,
16
+ seed: input.seed,
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Helper meta per risposta singolo elemento Public API.
22
+ */
23
+ export function buildPublicSingleMeta(seed: string) {
24
+ return { seed }
25
+ }
26
+