@beechcms/api 0.5.0 → 0.6.0-preview.2
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/Searching.svg +1 -0
- package/assets/dashboard/assets/chart-BrJFdsGZ.js +39 -0
- package/assets/dashboard/assets/index-CIaoMxuB.css +1 -0
- package/assets/dashboard/assets/index-wTKgygsg.js +636 -0
- package/assets/dashboard/assets/pie-chart-recharts-BEaE1FOE.js +1 -0
- package/assets/dashboard/assets/timeseries-chart-recharts-DmWM6imF.js +1 -0
- package/assets/dashboard/beechLogoDark.svg +48 -48
- package/assets/dashboard/index.html +18 -18
- package/assets/dashboard/noResult.svg +43 -0
- package/assets/dashboard/sol.svg +3 -3
- package/assets/dashboard/undraw_enter_nwx3.svg +36 -36
- package/assets/dashboard/working.svg +1 -0
- package/migrations/0000_v040_base.sql +265 -238
- package/migrations/0029_automations.sql +14 -14
- package/migrations/0030_test_seeds.sql +125 -125
- package/package.json +13 -9
- package/src/auth/{in-memory-hash-provider.ts → __fixtures__/in-memory-hash-provider.ts} +17 -13
- package/src/auth/{static-token-service.ts → __fixtures__/static-token-service.ts} +22 -18
- package/src/auth/bcrypt-hash-provider.ts +24 -20
- package/src/auth/constants.ts +14 -10
- package/src/auth/generate-refresh-token.test.ts +23 -19
- package/src/auth/hash-provider.test.ts +55 -46
- package/src/auth/jose-token-service.ts +62 -55
- package/src/auth/jwt-claims-passthrough.test.ts +87 -0
- package/src/auth/login.test.ts +100 -92
- package/src/auth/login.ts +78 -74
- package/src/auth/refresh.ts +11 -5
- package/src/auth/token-service.test.ts +90 -82
- package/src/factory.ts +370 -347
- package/src/features/automations/__tests__/action-executors.test.ts +255 -268
- package/src/features/automations/__tests__/automation-runner.test.ts +196 -192
- package/src/features/automations/__tests__/automation-runner.utils.test.ts +60 -56
- package/src/features/automations/__tests__/automations.handler.test.ts +264 -260
- package/src/features/automations/__tests__/automations.repository.test.ts +163 -159
- package/src/features/automations/__tests__/automations.schema.test.ts +224 -134
- package/src/features/automations/__tests__/context-resolver.test.ts +126 -122
- package/src/features/automations/__tests__/cron-runner.test.ts +267 -263
- package/src/features/automations/__tests__/cron-runner.utils.test.ts +144 -140
- package/src/features/automations/__tests__/set-variable.executor.test.ts +383 -306
- package/src/features/automations/__tests__/template-grammar.test.ts +308 -304
- package/src/features/automations/__tests__/webhook.executor.test.ts +142 -0
- package/src/features/automations/__tests__/when-evaluator.test.ts +274 -270
- package/src/features/automations/__tests__/when-pushdown.test.ts +281 -277
- package/src/features/automations/action-executors/create-entry.executor.ts +27 -23
- package/src/features/automations/action-executors/edit-field.executor.ts +26 -22
- package/src/features/automations/action-executors/index.ts +37 -33
- package/src/features/automations/action-executors/send-mail.executor.ts +53 -42
- package/src/features/automations/action-executors/set-variable.executor.ts +159 -146
- package/src/features/automations/action-executors/webhook.executor.ts +67 -25
- package/src/features/automations/automation-runner.ts +85 -81
- package/src/features/automations/automation-runner.utils.ts +47 -43
- package/src/features/automations/automations.handler.ts +197 -193
- package/src/features/automations/automations.schema.ts +177 -160
- package/src/features/automations/context-resolver.ts +152 -148
- package/src/features/automations/cron-runner.ts +140 -136
- package/src/features/automations/cron-runner.utils.ts +44 -40
- package/src/features/automations/filter-translation.ts +46 -42
- package/src/features/automations/index.ts +16 -12
- package/src/features/automations/template-grammar.ts +245 -241
- package/src/features/automations/var-access-resolver.ts +140 -136
- package/src/features/automations/when-evaluator.ts +87 -83
- package/src/features/automations/when-pushdown.ts +57 -53
- package/src/features/backrefs/__tests__/backrefs.handler.test.ts +359 -0
- package/src/features/backrefs/backrefs.handler.ts +168 -0
- package/src/features/backrefs/d1-backref.repository.ts +84 -0
- package/src/features/backrefs/index.ts +5 -0
- package/src/features/content/constants.ts +16 -10
- package/src/features/content/handlers/bulk.handler.ts +185 -0
- package/src/features/content/handlers/create.ts +129 -165
- package/src/features/content/handlers/delete.ts +62 -87
- package/src/features/content/handlers/facets.ts +49 -45
- package/src/features/content/handlers/get.ts +120 -116
- package/src/features/content/handlers/helpers.test.ts +180 -0
- package/src/features/content/handlers/helpers.ts +93 -0
- package/src/features/content/handlers/list.ts +174 -88
- package/src/features/content/handlers/update.ts +174 -219
- package/src/features/content/index.ts +26 -20
- package/src/features/dashboard-layout/__tests__/dashboard-layout.handler.test.ts +388 -0
- package/src/features/dashboard-layout/dashboard-layout.handler.ts +206 -0
- package/src/features/dashboard-layout/index.ts +5 -0
- package/src/features/draft/draft.handler.ts +195 -170
- package/src/features/draft/draft.middleware.ts +66 -62
- package/src/features/draft/index.ts +5 -1
- package/src/features/email/email.provider.ts +42 -38
- package/src/features/email/email.service.ts +98 -93
- package/src/features/email/email.types.ts +119 -108
- package/src/features/email/index.ts +33 -29
- package/src/features/email/providers/resend.ts +67 -63
- package/src/features/email/providers/smtp.ts +55 -0
- package/src/features/email/templates/automation-mail.ts +19 -15
- package/src/features/email/templates/password-changed.ts +63 -59
- package/src/features/email/templates/password-reset.ts +68 -64
- package/src/features/email/templates/shell.ts +96 -92
- package/src/features/notifications/index.ts +5 -1
- package/src/features/notifications/notifications.handler.ts +105 -101
- package/src/features/password-reset/index.ts +19 -15
- package/src/features/password-reset/request.ts +92 -82
- package/src/features/password-reset/reset.ts +102 -92
- package/src/features/rotate-field/index.ts +5 -1
- package/src/features/rotate-field/rotate-field.handler.ts +132 -128
- package/src/features/rotate-field/rotate-field.schema.ts +17 -13
- package/src/features/schema/schema.handler.ts +131 -16
- package/src/features/seeds/index.ts +5 -0
- package/src/features/seeds/seeds.handler.test.ts +1199 -0
- package/src/features/seeds/seeds.handler.ts +558 -0
- package/src/features/settings/__tests__/settings.handler.test.ts +555 -0
- package/src/features/settings/settings.handler.ts +392 -302
- package/src/features/setup/index.ts +288 -91
- package/src/features/stats/index.ts +5 -1
- package/src/features/stats/stats.handler.ts +420 -430
- package/src/features/webhooks/index.ts +63 -0
- package/src/index.ts +65 -56
- package/src/media-utils.ts +82 -78
- package/src/middleware/auth-providers.middleware.test.ts +85 -0
- package/src/middleware/auth-providers.middleware.ts +45 -32
- package/src/middleware/observability.middleware.test.ts +93 -0
- package/src/middleware/observability.middleware.ts +70 -52
- package/src/middleware/rate-limit.middleware.ts +45 -41
- package/src/middleware/repository.middleware.ts +117 -91
- package/src/middleware/seed-registry.middleware.test.ts +97 -0
- package/src/middleware/seed-registry.middleware.ts +21 -0
- package/src/middleware/storage.middleware.ts +25 -21
- package/src/middleware.ts +45 -47
- package/src/public/access-policy.ts +27 -23
- package/src/public/api-key-middleware.ts +57 -53
- package/src/public/cache-utils.ts +38 -34
- package/src/public/entry-projection.ts +46 -42
- package/src/public/idempotency.ts +23 -19
- package/src/public/index.ts +16 -12
- package/src/public/problem-details.ts +124 -53
- package/src/public/public-add.ts +114 -110
- package/src/public/public-edit.ts +163 -159
- package/src/public/public-errors.ts +19 -15
- package/src/public/public-read.ts +63 -59
- package/src/public/public-routes.ts +88 -84
- package/src/public/query-builder.test.ts +224 -220
- package/src/public/query-builder.ts +156 -152
- package/src/public/rate-limit-middleware.ts +34 -30
- package/src/public/read-list.ts +54 -50
- package/src/public/read-single.ts +48 -44
- package/src/public/response-builder.ts +30 -26
- package/src/public/sanitize.ts +69 -65
- package/src/public/slug-utils.ts +18 -14
- package/src/rate-limit/cloudflare-rate-limiter.test.ts +30 -26
- package/src/rate-limit/cloudflare-rate-limiter.ts +15 -11
- package/src/rate-limit/in-memory-rate-limiter.test.ts +37 -33
- package/src/rate-limit/in-memory-rate-limiter.ts +17 -13
- package/src/rate-limit/no-op-rate-limiter.test.ts +22 -18
- package/src/rate-limit/no-op-rate-limiter.ts +11 -7
- package/src/search-utils.test.ts +211 -207
- package/src/search-utils.ts +213 -209
- package/src/search.ts +65 -61
- package/src/shared/apply-policies.test.ts +81 -77
- package/src/shared/apply-policies.ts +67 -63
- package/src/shared/automations.repository.d1.ts +150 -146
- package/src/shared/background-notification-service.test.ts +62 -58
- package/src/shared/background-notification-service.ts +52 -48
- package/src/shared/base.repository.d1.ts +32 -28
- package/src/shared/content-utils.test.ts +165 -161
- package/src/shared/content-utils.ts +86 -82
- package/src/shared/content.repository.d1.test.ts +507 -312
- package/src/shared/content.repository.d1.ts +851 -382
- package/src/shared/d1-activity-log.repository.test.ts +140 -136
- package/src/shared/d1-activity-log.repository.ts +105 -101
- package/src/shared/d1-activity-logger.test.ts +86 -82
- package/src/shared/d1-activity-logger.ts +67 -63
- package/src/shared/d1-analytics.repository.test.ts +78 -74
- package/src/shared/d1-analytics.repository.ts +85 -81
- package/src/shared/d1-content-scan.repository.test.ts +80 -76
- package/src/shared/d1-content-scan.repository.ts +37 -29
- package/src/shared/d1-notification.repository.test.ts +128 -124
- package/src/shared/d1-notification.repository.ts +118 -114
- package/src/shared/d1-password-reset-token.repository.test.ts +81 -77
- package/src/shared/d1-password-reset-token.repository.ts +56 -52
- package/src/shared/d1-search.repository.test.ts +87 -83
- package/src/shared/d1-search.repository.ts +88 -84
- package/src/shared/d1-session.repository.test.ts +125 -121
- package/src/shared/d1-session.repository.ts +102 -98
- package/src/shared/d1-setup-checklist.repository.ts +36 -0
- package/src/shared/d1-user.repository.test.ts +151 -147
- package/src/shared/d1-user.repository.ts +119 -109
- package/src/shared/d1-widget.repository.test.ts +267 -217
- package/src/shared/d1-widget.repository.ts +385 -337
- package/src/shared/dashboard-layout.repository.d1.test.ts +135 -0
- package/src/shared/dashboard-layout.repository.d1.ts +58 -0
- package/src/shared/demo-data-sql.ts +216 -0
- package/src/shared/demo-data.repository.d1.ts +20 -0
- package/src/shared/execution-context-scheduler.ts +13 -9
- package/src/shared/fixed-clock.ts +25 -21
- package/src/shared/fts-sync.ts +8 -4
- package/src/shared/idempotency.repository.d1.test.ts +83 -79
- package/src/shared/idempotency.repository.d1.ts +60 -56
- package/src/shared/in-memory-activity-logger.ts +19 -15
- package/src/shared/in-memory-notification-service.ts +19 -15
- package/src/shared/in-memory-seed.repository.ts +58 -0
- package/src/shared/media.repository.d1.test.ts +107 -103
- package/src/shared/media.repository.d1.ts +68 -64
- package/src/shared/qstash-notification-service.test.ts +67 -0
- package/src/shared/qstash-notification-service.ts +55 -0
- package/src/shared/query-utils.ts +141 -137
- package/src/shared/request-utils.ts +26 -22
- package/src/shared/schema-mutator.d1.test.ts +142 -0
- package/src/shared/schema-mutator.d1.ts +64 -0
- package/src/shared/seed-layout.repository.d1.test.ts +114 -0
- package/src/shared/seed-layout.repository.d1.ts +62 -0
- package/src/shared/seed-registry-cache.test.ts +68 -0
- package/src/shared/seed-registry-cache.ts +49 -0
- package/src/shared/seed.repository.d1.test.ts +143 -0
- package/src/shared/seed.repository.d1.ts +98 -0
- package/src/shared/sequential-id-generator.ts +33 -22
- package/src/shared/site-settings.repository.d1.ts +53 -0
- package/src/shared/storage/factory.ts +41 -40
- package/src/shared/storage/s3-bucket.ts +195 -163
- package/src/shared/storage-utils.ts +40 -36
- package/src/shared/system-stats.repository.d1.test.ts +58 -54
- package/src/shared/system-stats.repository.d1.ts +48 -44
- package/src/types.ts +90 -67
- package/src/upload.ts +198 -187
- package/src/widget.test.ts +85 -0
- package/src/widget.ts +251 -208
- package/assets/dashboard/assets/index-B1mUfgiK.css +0 -1
- package/assets/dashboard/assets/index-CHxxc_id.js +0 -629
- package/src/shared/storage/r2-binding-bucket.ts +0 -81
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
// SPDX-License-Identifier: BUSL-1.1
|
|
2
|
+
// Copyright (c) 2024–2026 Flavio De Musso. All rights reserved.
|
|
3
|
+
// See LICENSE in the repository root for license terms.
|
|
4
|
+
|
|
5
|
+
import { describe, it, expect, vi } from 'vitest'
|
|
6
|
+
import { Hono } from 'hono'
|
|
7
|
+
import { dashboardLayoutApp } from '../dashboard-layout.handler'
|
|
8
|
+
import type { DashboardLayout, DashboardLayoutRecord, IDashboardLayoutRepository } from '@beechcms/core'
|
|
9
|
+
import type { Env, Variables } from '../../../types'
|
|
10
|
+
|
|
11
|
+
// ---------------------------------------------------------------------------
|
|
12
|
+
// Helpers and Mocks
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
|
|
15
|
+
/** Stateful in-memory stub so PUT/DELETE effects are observable by a later GET. */
|
|
16
|
+
function makeRepoStub(initial: DashboardLayoutRecord | null = null): IDashboardLayoutRepository {
|
|
17
|
+
let state = initial
|
|
18
|
+
return {
|
|
19
|
+
get: vi.fn(async (scope: string) => (state && state.scope === scope ? state : null)),
|
|
20
|
+
listScopes: vi.fn(async () => (state ? [state.scope] : [])),
|
|
21
|
+
upsert: vi.fn(async (scope: string, layout: DashboardLayout, updatedBy: string) => {
|
|
22
|
+
state = { scope, layout, updatedAt: 0, updatedBy }
|
|
23
|
+
}),
|
|
24
|
+
remove: vi.fn(async (scope: string) => {
|
|
25
|
+
if (state?.scope === scope) state = null
|
|
26
|
+
}),
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Stateful in-memory stub supporting multiple scopes at once. */
|
|
31
|
+
function makeMultiRepoStub(initial: Record<string, DashboardLayout> = {}): IDashboardLayoutRepository {
|
|
32
|
+
const state = new Map<string, DashboardLayoutRecord>(
|
|
33
|
+
Object.entries(initial).map(([scope, layout]) => [scope, { scope, layout, updatedAt: 0, updatedBy: 'seed' }]),
|
|
34
|
+
)
|
|
35
|
+
return {
|
|
36
|
+
get: vi.fn(async (scope: string) => state.get(scope) ?? null),
|
|
37
|
+
listScopes: vi.fn(async () => [...state.keys()]),
|
|
38
|
+
upsert: vi.fn(async (scope: string, layout: DashboardLayout, updatedBy: string) => {
|
|
39
|
+
state.set(scope, { scope, layout, updatedAt: 0, updatedBy })
|
|
40
|
+
}),
|
|
41
|
+
remove: vi.fn(async (scope: string) => {
|
|
42
|
+
state.delete(scope)
|
|
43
|
+
}),
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function buildApp(opts: {
|
|
48
|
+
repo?: IDashboardLayoutRepository
|
|
49
|
+
role?: string
|
|
50
|
+
seedSlugs?: string[]
|
|
51
|
+
} = {}) {
|
|
52
|
+
const repo = opts.repo ?? makeRepoStub()
|
|
53
|
+
const app = new Hono<{ Bindings: Env; Variables: Variables }>()
|
|
54
|
+
app.use('*', async (c, next) => {
|
|
55
|
+
c.set('dashboardLayoutRepository', repo)
|
|
56
|
+
c.set('seedRegistry', {
|
|
57
|
+
all: () => (opts.seedSlugs ?? ['articoli']).map((slug) => ({ slug })),
|
|
58
|
+
} as any)
|
|
59
|
+
c.set('jwtPayload', { sub: 'user-1', role: opts.role ?? 'admin', email: 'user@beechcms.com' } as any)
|
|
60
|
+
await next()
|
|
61
|
+
})
|
|
62
|
+
app.route('/', dashboardLayoutApp)
|
|
63
|
+
return { app, repo }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const validLayout: DashboardLayout = {
|
|
67
|
+
version: 1,
|
|
68
|
+
pages: [
|
|
69
|
+
{
|
|
70
|
+
id: 'page-1',
|
|
71
|
+
slug: 'overview',
|
|
72
|
+
label: 'Overview',
|
|
73
|
+
sections: [
|
|
74
|
+
{
|
|
75
|
+
id: 'section-1',
|
|
76
|
+
columns: [{ id: 'col-1', widgets: [{ id: 'w1', type: 'core/stat', config: {} }] }],
|
|
77
|
+
},
|
|
78
|
+
],
|
|
79
|
+
},
|
|
80
|
+
],
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function putRequest(body: unknown) {
|
|
84
|
+
return {
|
|
85
|
+
method: 'PUT',
|
|
86
|
+
headers: { 'Content-Type': 'application/json' },
|
|
87
|
+
body: JSON.stringify(body),
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ---------------------------------------------------------------------------
|
|
92
|
+
// Tests
|
|
93
|
+
// ---------------------------------------------------------------------------
|
|
94
|
+
|
|
95
|
+
describe('Dashboard Layout Handler', () => {
|
|
96
|
+
describe('GET /', () => {
|
|
97
|
+
it('returns layout: null when no row exists', async () => {
|
|
98
|
+
const { app } = buildApp()
|
|
99
|
+
const res = await app.request('/')
|
|
100
|
+
expect(res.status).toBe(200)
|
|
101
|
+
expect(await res.json()).toEqual({ scope: 'default', layout: null })
|
|
102
|
+
})
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
describe('PUT /', () => {
|
|
106
|
+
it('returns 403 problem+json for an editor', async () => {
|
|
107
|
+
const { app } = buildApp({ role: 'editor' })
|
|
108
|
+
const res = await app.request('/', putRequest(validLayout))
|
|
109
|
+
expect(res.status).toBe(403)
|
|
110
|
+
expect(res.headers.get('Content-Type')).toContain('application/problem+json')
|
|
111
|
+
const body = await res.json() as { type: string }
|
|
112
|
+
expect(body.type).toContain('forbidden')
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
it('returns 400 invalid-json for malformed JSON body', async () => {
|
|
116
|
+
const { app } = buildApp()
|
|
117
|
+
const res = await app.request('/', {
|
|
118
|
+
method: 'PUT',
|
|
119
|
+
headers: { 'Content-Type': 'application/json' },
|
|
120
|
+
body: 'not-json',
|
|
121
|
+
})
|
|
122
|
+
expect(res.status).toBe(400)
|
|
123
|
+
const body = await res.json() as { type: string }
|
|
124
|
+
expect(body.type).toContain('invalid-json')
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
it('returns 422 for a shape that fails Zod validation', async () => {
|
|
128
|
+
const { app } = buildApp()
|
|
129
|
+
const res = await app.request('/', putRequest({ version: 2, pages: [] }))
|
|
130
|
+
expect(res.status).toBe(422)
|
|
131
|
+
const body = await res.json() as { type: string }
|
|
132
|
+
expect(body.type).toContain('invalid-layout')
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
it('returns 422 when the layout has duplicate widget ids', async () => {
|
|
136
|
+
const duplicateLayout: DashboardLayout = {
|
|
137
|
+
version: 1,
|
|
138
|
+
pages: [
|
|
139
|
+
{
|
|
140
|
+
id: 'page-1',
|
|
141
|
+
slug: 'overview',
|
|
142
|
+
label: 'Overview',
|
|
143
|
+
sections: [
|
|
144
|
+
{
|
|
145
|
+
id: 'section-1',
|
|
146
|
+
columns: [
|
|
147
|
+
{ id: 'col-1', widgets: [{ id: 'dup', type: 'core/stat', config: {} }] },
|
|
148
|
+
{ id: 'col-2', widgets: [{ id: 'dup', type: 'core/stat', config: {} }] },
|
|
149
|
+
],
|
|
150
|
+
columnSpans: [6, 6],
|
|
151
|
+
},
|
|
152
|
+
],
|
|
153
|
+
},
|
|
154
|
+
],
|
|
155
|
+
}
|
|
156
|
+
const { app } = buildApp()
|
|
157
|
+
const res = await app.request('/', putRequest(duplicateLayout))
|
|
158
|
+
expect(res.status).toBe(422)
|
|
159
|
+
const body = await res.json() as { type: string; detail: string }
|
|
160
|
+
expect(body.type).toContain('invalid-layout')
|
|
161
|
+
expect(body.detail).toContain('dup')
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
it('strips widgets bound to a non-existent seed and reports a warning', async () => {
|
|
165
|
+
const layoutWithGhostSeed: DashboardLayout = {
|
|
166
|
+
version: 1,
|
|
167
|
+
pages: [
|
|
168
|
+
{
|
|
169
|
+
id: 'page-1',
|
|
170
|
+
slug: 'overview',
|
|
171
|
+
label: 'Overview',
|
|
172
|
+
sections: [
|
|
173
|
+
{
|
|
174
|
+
id: 'section-1',
|
|
175
|
+
columns: [
|
|
176
|
+
{
|
|
177
|
+
id: 'col-1',
|
|
178
|
+
widgets: [
|
|
179
|
+
{ id: 'w1', type: 'core/recent-content', config: { seedSlug: 'ghost-seed' } },
|
|
180
|
+
{ id: 'w2', type: 'core/stat', config: {} },
|
|
181
|
+
],
|
|
182
|
+
},
|
|
183
|
+
],
|
|
184
|
+
},
|
|
185
|
+
],
|
|
186
|
+
},
|
|
187
|
+
],
|
|
188
|
+
}
|
|
189
|
+
const { app, repo } = buildApp({ seedSlugs: ['articoli'] })
|
|
190
|
+
const res = await app.request('/', putRequest(layoutWithGhostSeed))
|
|
191
|
+
expect(res.status).toBe(200)
|
|
192
|
+
const body = await res.json() as { ok: boolean; layout: DashboardLayout; warnings: string[] }
|
|
193
|
+
expect(body.ok).toBe(true)
|
|
194
|
+
expect(body.warnings.length).toBeGreaterThan(0)
|
|
195
|
+
|
|
196
|
+
const widgetIds = body.layout.pages[0].sections[0].columns[0].widgets.map((w) => w.id)
|
|
197
|
+
expect(widgetIds).toEqual(['w2'])
|
|
198
|
+
expect(repo.upsert).toHaveBeenCalledWith('default', body.layout, 'user-1')
|
|
199
|
+
})
|
|
200
|
+
|
|
201
|
+
it('passes through an unknown widget type unchanged with no warning', async () => {
|
|
202
|
+
const layoutWithUnknownWidget: DashboardLayout = {
|
|
203
|
+
version: 1,
|
|
204
|
+
pages: [
|
|
205
|
+
{
|
|
206
|
+
id: 'page-1',
|
|
207
|
+
slug: 'overview',
|
|
208
|
+
label: 'Overview',
|
|
209
|
+
sections: [
|
|
210
|
+
{
|
|
211
|
+
id: 'section-1',
|
|
212
|
+
columns: [{ id: 'col-1', widgets: [{ id: 'w1', type: '@acme/ghost', config: {} }] }],
|
|
213
|
+
},
|
|
214
|
+
],
|
|
215
|
+
},
|
|
216
|
+
],
|
|
217
|
+
}
|
|
218
|
+
const { app } = buildApp()
|
|
219
|
+
const res = await app.request('/', putRequest(layoutWithUnknownWidget))
|
|
220
|
+
expect(res.status).toBe(200)
|
|
221
|
+
const body = await res.json() as { ok: boolean; layout: DashboardLayout; warnings: string[] }
|
|
222
|
+
expect(body.warnings).toEqual([])
|
|
223
|
+
expect(body.layout.pages[0].sections[0].columns[0].widgets[0]).toEqual({
|
|
224
|
+
id: 'w1',
|
|
225
|
+
type: '@acme/ghost',
|
|
226
|
+
config: {},
|
|
227
|
+
})
|
|
228
|
+
})
|
|
229
|
+
|
|
230
|
+
it('persists a valid layout as admin and returns it on a subsequent GET', async () => {
|
|
231
|
+
const { app } = buildApp()
|
|
232
|
+
|
|
233
|
+
const putRes = await app.request('/', putRequest(validLayout))
|
|
234
|
+
expect(putRes.status).toBe(200)
|
|
235
|
+
const putBody = await putRes.json() as { ok: boolean; layout: DashboardLayout }
|
|
236
|
+
expect(putBody.ok).toBe(true)
|
|
237
|
+
|
|
238
|
+
const getRes = await app.request('/')
|
|
239
|
+
expect(getRes.status).toBe(200)
|
|
240
|
+
const getBody = await getRes.json() as { scope: string; layout: DashboardLayout }
|
|
241
|
+
expect(getBody.scope).toBe('default')
|
|
242
|
+
expect(getBody.layout).toEqual(putBody.layout)
|
|
243
|
+
})
|
|
244
|
+
})
|
|
245
|
+
|
|
246
|
+
describe('DELETE /', () => {
|
|
247
|
+
it('returns 403 problem+json for an editor', async () => {
|
|
248
|
+
const { app } = buildApp({ role: 'editor' })
|
|
249
|
+
const res = await app.request('/', { method: 'DELETE' })
|
|
250
|
+
expect(res.status).toBe(403)
|
|
251
|
+
expect(res.headers.get('Content-Type')).toContain('application/problem+json')
|
|
252
|
+
})
|
|
253
|
+
|
|
254
|
+
it('removes the stored layout as admin; subsequent GET returns layout: null', async () => {
|
|
255
|
+
const repo = makeRepoStub({ scope: 'default', layout: validLayout, updatedAt: 0, updatedBy: 'admin-1' })
|
|
256
|
+
const { app } = buildApp({ repo })
|
|
257
|
+
|
|
258
|
+
const delRes = await app.request('/', { method: 'DELETE' })
|
|
259
|
+
expect(delRes.status).toBe(200)
|
|
260
|
+
expect(await delRes.json()).toEqual({ ok: true })
|
|
261
|
+
|
|
262
|
+
const getRes = await app.request('/')
|
|
263
|
+
expect(await getRes.json()).toEqual({ scope: 'default', layout: null })
|
|
264
|
+
})
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
// ---------------------------------------------------------------------------
|
|
268
|
+
// Sprint 06: role-based dashboards
|
|
269
|
+
// ---------------------------------------------------------------------------
|
|
270
|
+
|
|
271
|
+
describe('GET / — scope resolution matrix', () => {
|
|
272
|
+
it('returns default + layout: null when nothing is stored (editor)', async () => {
|
|
273
|
+
const { app } = buildApp({ role: 'editor', repo: makeMultiRepoStub() })
|
|
274
|
+
const res = await app.request('/')
|
|
275
|
+
expect(await res.json()).toEqual({ scope: 'default', layout: null })
|
|
276
|
+
})
|
|
277
|
+
|
|
278
|
+
it('returns default when only default is stored (editor)', async () => {
|
|
279
|
+
const repo = makeMultiRepoStub({ default: validLayout })
|
|
280
|
+
const { app } = buildApp({ role: 'editor', repo })
|
|
281
|
+
const res = await app.request('/')
|
|
282
|
+
const body = await res.json() as { scope: string; layout: DashboardLayout }
|
|
283
|
+
expect(body.scope).toBe('default')
|
|
284
|
+
expect(body.layout).toEqual(validLayout)
|
|
285
|
+
})
|
|
286
|
+
|
|
287
|
+
it('returns role:editor when only role:editor is stored (editor)', async () => {
|
|
288
|
+
const repo = makeMultiRepoStub({ 'role:editor': validLayout })
|
|
289
|
+
const { app } = buildApp({ role: 'editor', repo })
|
|
290
|
+
const res = await app.request('/')
|
|
291
|
+
const body = await res.json() as { scope: string; layout: DashboardLayout }
|
|
292
|
+
expect(body.scope).toBe('role:editor')
|
|
293
|
+
expect(body.layout).toEqual(validLayout)
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
it('returns role:editor when both are stored (editor)', async () => {
|
|
297
|
+
const otherLayout: DashboardLayout = { version: 1, pages: [{ ...validLayout.pages[0], slug: 'other' }] }
|
|
298
|
+
const repo = makeMultiRepoStub({ default: otherLayout, 'role:editor': validLayout })
|
|
299
|
+
const { app } = buildApp({ role: 'editor', repo })
|
|
300
|
+
const res = await app.request('/')
|
|
301
|
+
const body = await res.json() as { scope: string; layout: DashboardLayout }
|
|
302
|
+
expect(body.scope).toBe('role:editor')
|
|
303
|
+
expect(body.layout).toEqual(validLayout)
|
|
304
|
+
})
|
|
305
|
+
|
|
306
|
+
it('ignores role:editor for an admin caller, falling back to default + null', async () => {
|
|
307
|
+
const repo = makeMultiRepoStub({ 'role:editor': validLayout })
|
|
308
|
+
const { app } = buildApp({ role: 'admin', repo })
|
|
309
|
+
const res = await app.request('/')
|
|
310
|
+
expect(await res.json()).toEqual({ scope: 'default', layout: null })
|
|
311
|
+
})
|
|
312
|
+
})
|
|
313
|
+
|
|
314
|
+
describe('PUT/DELETE /:scope', () => {
|
|
315
|
+
it('admin can write role:editor (200)', async () => {
|
|
316
|
+
const { app } = buildApp({ role: 'admin', repo: makeMultiRepoStub() })
|
|
317
|
+
const res = await app.request('/role:editor', putRequest(validLayout))
|
|
318
|
+
expect(res.status).toBe(200)
|
|
319
|
+
const body = await res.json() as { ok: boolean }
|
|
320
|
+
expect(body.ok).toBe(true)
|
|
321
|
+
})
|
|
322
|
+
|
|
323
|
+
it('editor cannot write role:editor (403)', async () => {
|
|
324
|
+
const { app } = buildApp({ role: 'editor', repo: makeMultiRepoStub() })
|
|
325
|
+
const res = await app.request('/role:editor', putRequest(validLayout))
|
|
326
|
+
expect(res.status).toBe(403)
|
|
327
|
+
})
|
|
328
|
+
|
|
329
|
+
it('rejects an unknown scope with a 400 invalid-scope problem', async () => {
|
|
330
|
+
const { app } = buildApp({ role: 'admin', repo: makeMultiRepoStub() })
|
|
331
|
+
const res = await app.request('/role:ghost', putRequest(validLayout))
|
|
332
|
+
expect(res.status).toBe(400)
|
|
333
|
+
const body = await res.json() as { type: string }
|
|
334
|
+
expect(body.type).toContain('invalid-scope')
|
|
335
|
+
})
|
|
336
|
+
|
|
337
|
+
it('removes the stored row for a scope', async () => {
|
|
338
|
+
const repo = makeMultiRepoStub({ 'role:editor': validLayout })
|
|
339
|
+
const { app } = buildApp({ role: 'admin', repo })
|
|
340
|
+
const res = await app.request('/role:editor', { method: 'DELETE' })
|
|
341
|
+
expect(res.status).toBe(200)
|
|
342
|
+
expect(await repo.get('role:editor')).toBeNull()
|
|
343
|
+
})
|
|
344
|
+
})
|
|
345
|
+
|
|
346
|
+
describe('GET /:scope', () => {
|
|
347
|
+
it('returns the raw stored layout for a scope', async () => {
|
|
348
|
+
const repo = makeMultiRepoStub({ 'role:editor': validLayout })
|
|
349
|
+
const { app } = buildApp({ role: 'admin', repo })
|
|
350
|
+
const res = await app.request('/role:editor')
|
|
351
|
+
const body = await res.json() as { scope: string; layout: DashboardLayout | null }
|
|
352
|
+
expect(body.scope).toBe('role:editor')
|
|
353
|
+
expect(body.layout).toEqual(validLayout)
|
|
354
|
+
})
|
|
355
|
+
|
|
356
|
+
it('returns layout: null for an unstored scope', async () => {
|
|
357
|
+
const { app } = buildApp({ role: 'admin', repo: makeMultiRepoStub() })
|
|
358
|
+
const res = await app.request('/role:editor')
|
|
359
|
+
expect(await res.json()).toEqual({ scope: 'role:editor', layout: null })
|
|
360
|
+
})
|
|
361
|
+
|
|
362
|
+
it('returns 403 for an editor', async () => {
|
|
363
|
+
const { app } = buildApp({ role: 'editor', repo: makeMultiRepoStub() })
|
|
364
|
+
const res = await app.request('/role:editor')
|
|
365
|
+
expect(res.status).toBe(403)
|
|
366
|
+
})
|
|
367
|
+
})
|
|
368
|
+
|
|
369
|
+
describe('GET /scopes', () => {
|
|
370
|
+
it('lists the closed set of scopes annotated with stored state', async () => {
|
|
371
|
+
const repo = makeMultiRepoStub({ default: validLayout, 'role:editor': validLayout })
|
|
372
|
+
const { app } = buildApp({ role: 'admin', repo })
|
|
373
|
+
const res = await app.request('/scopes')
|
|
374
|
+
expect(res.status).toBe(200)
|
|
375
|
+
expect(await res.json()).toEqual([
|
|
376
|
+
{ scope: 'default', stored: true },
|
|
377
|
+
{ scope: 'role:admin', stored: false },
|
|
378
|
+
{ scope: 'role:editor', stored: true },
|
|
379
|
+
])
|
|
380
|
+
})
|
|
381
|
+
|
|
382
|
+
it('returns 403 for an editor', async () => {
|
|
383
|
+
const { app } = buildApp({ role: 'editor', repo: makeMultiRepoStub() })
|
|
384
|
+
const res = await app.request('/scopes')
|
|
385
|
+
expect(res.status).toBe(403)
|
|
386
|
+
})
|
|
387
|
+
})
|
|
388
|
+
})
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// SPDX-License-Identifier: BUSL-1.1
|
|
2
|
+
// Copyright (c) 2024–2026 Flavio De Musso. All rights reserved.
|
|
3
|
+
// See LICENSE in the repository root for license terms.
|
|
4
|
+
|
|
5
|
+
/// <reference types="@cloudflare/workers-types" />
|
|
6
|
+
import { Hono } from 'hono'
|
|
7
|
+
import {
|
|
8
|
+
canEditDashboard,
|
|
9
|
+
dashboardLayoutSchema,
|
|
10
|
+
validateDashboardLayout,
|
|
11
|
+
isValidDashboardScope,
|
|
12
|
+
resolveDashboardScopeChain,
|
|
13
|
+
roleScope,
|
|
14
|
+
KNOWN_DASHBOARD_ROLES,
|
|
15
|
+
DEFAULT_DASHBOARD_SCOPE,
|
|
16
|
+
} from '@beechcms/core'
|
|
17
|
+
import { publicProblem } from '../../public/problem-details'
|
|
18
|
+
import type { Context } from 'hono'
|
|
19
|
+
import type { DashboardLayout } from '@beechcms/core'
|
|
20
|
+
import type { Env, Variables } from '../../types'
|
|
21
|
+
|
|
22
|
+
type AppContext = Context<{ Bindings: Env; Variables: Variables }>
|
|
23
|
+
|
|
24
|
+
/** Returns a 403 response if the caller lacks dashboard-edit permission, otherwise undefined. */
|
|
25
|
+
function requireDashboardEditPermission(context: AppContext) {
|
|
26
|
+
const role = context.get('jwtPayload')?.role
|
|
27
|
+
if (!canEditDashboard(role)) {
|
|
28
|
+
return publicProblem(context, {
|
|
29
|
+
type: 'forbidden',
|
|
30
|
+
title: 'Forbidden',
|
|
31
|
+
status: 403,
|
|
32
|
+
detail: 'Dashboard layout edit requires admin role.',
|
|
33
|
+
})
|
|
34
|
+
}
|
|
35
|
+
return undefined
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Shared validate-and-upsert logic for the bare and `:scope` PUT routes. */
|
|
39
|
+
async function putLayout(context: AppContext, scope: string) {
|
|
40
|
+
const forbidden = requireDashboardEditPermission(context)
|
|
41
|
+
if (forbidden) return forbidden
|
|
42
|
+
|
|
43
|
+
let body: unknown
|
|
44
|
+
try {
|
|
45
|
+
body = await context.req.json()
|
|
46
|
+
} catch {
|
|
47
|
+
return publicProblem(context, {
|
|
48
|
+
type: 'invalid-json',
|
|
49
|
+
title: 'Invalid JSON',
|
|
50
|
+
status: 400,
|
|
51
|
+
detail: 'Body must be valid JSON.',
|
|
52
|
+
})
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const parsed = dashboardLayoutSchema.safeParse(body)
|
|
56
|
+
if (!parsed.success) {
|
|
57
|
+
return publicProblem(context, {
|
|
58
|
+
type: 'invalid-layout',
|
|
59
|
+
title: 'Invalid layout',
|
|
60
|
+
status: 422,
|
|
61
|
+
detail: parsed.error.message,
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const seedSlugs = new Set(context.get('seedRegistry').all().map((seed) => seed.slug))
|
|
66
|
+
const result = validateDashboardLayout(parsed.data, { seedSlugs })
|
|
67
|
+
if (!result.ok) {
|
|
68
|
+
return publicProblem(context, {
|
|
69
|
+
type: 'invalid-layout',
|
|
70
|
+
title: 'Invalid layout',
|
|
71
|
+
status: 422,
|
|
72
|
+
detail: result.errors.join('; '),
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const userId = context.get('jwtPayload')?.sub ?? 'unknown'
|
|
77
|
+
await context.get('dashboardLayoutRepository').upsert(scope, result.cleaned, userId)
|
|
78
|
+
|
|
79
|
+
return context.json({ ok: true, layout: result.cleaned, warnings: result.warnings })
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const dashboardLayoutApp = new Hono<{ Bindings: Env; Variables: Variables }>()
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Returns the dashboard layout for the caller, walking the scope chain
|
|
86
|
+
* derived from their role (`role:<role>` → `default`). Returns the winning
|
|
87
|
+
* scope alongside the (auto-cleaned) layout, or `{ scope: 'default', layout: null }`
|
|
88
|
+
* if nothing is stored anywhere. Any authenticated user may read it.
|
|
89
|
+
*/
|
|
90
|
+
dashboardLayoutApp.get('/', async (context) => {
|
|
91
|
+
const role = context.get('jwtPayload')?.role
|
|
92
|
+
const chain = resolveDashboardScopeChain(role)
|
|
93
|
+
const repo = context.get('dashboardLayoutRepository')
|
|
94
|
+
|
|
95
|
+
for (const scope of chain) {
|
|
96
|
+
const record = await repo.get(scope)
|
|
97
|
+
if (!record) continue
|
|
98
|
+
|
|
99
|
+
const seedSlugs = new Set(context.get('seedRegistry').all().map((seed) => seed.slug))
|
|
100
|
+
const { cleaned } = validateDashboardLayout(record.layout, { seedSlugs })
|
|
101
|
+
return context.json({ scope, layout: cleaned })
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return context.json({ scope: DEFAULT_DASHBOARD_SCOPE, layout: null as DashboardLayout | null })
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Lists the closed set of dashboard scopes (`default` + one per known role),
|
|
109
|
+
* annotated with whether each currently has a stored layout. Admin-only —
|
|
110
|
+
* builder furniture for the scope switcher.
|
|
111
|
+
*/
|
|
112
|
+
dashboardLayoutApp.get('/scopes', async (context) => {
|
|
113
|
+
const forbidden = requireDashboardEditPermission(context)
|
|
114
|
+
if (forbidden) return forbidden
|
|
115
|
+
|
|
116
|
+
const stored = new Set(await context.get('dashboardLayoutRepository').listScopes())
|
|
117
|
+
const scopes = [DEFAULT_DASHBOARD_SCOPE, ...KNOWN_DASHBOARD_ROLES.map(roleScope)]
|
|
118
|
+
return context.json(scopes.map((scope) => ({ scope, stored: stored.has(scope) })))
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Returns the raw stored layout for an arbitrary scope (`'default'` or
|
|
123
|
+
* `'role:<role>'`), or `{ scope, layout: null }` if nothing is stored.
|
|
124
|
+
* Admin-only — builder furniture for loading a scope's draft.
|
|
125
|
+
*/
|
|
126
|
+
dashboardLayoutApp.get('/:scope', async (context) => {
|
|
127
|
+
const forbidden = requireDashboardEditPermission(context)
|
|
128
|
+
if (forbidden) return forbidden
|
|
129
|
+
|
|
130
|
+
const scope = context.req.param('scope')
|
|
131
|
+
if (!isValidDashboardScope(scope)) {
|
|
132
|
+
return publicProblem(context, {
|
|
133
|
+
type: 'invalid-scope',
|
|
134
|
+
title: 'Invalid scope',
|
|
135
|
+
status: 400,
|
|
136
|
+
detail: `Unknown dashboard scope '${scope}'.`,
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const record = await context.get('dashboardLayoutRepository').get(scope)
|
|
141
|
+
if (!record) return context.json({ scope, layout: null as DashboardLayout | null })
|
|
142
|
+
|
|
143
|
+
const seedSlugs = new Set(context.get('seedRegistry').all().map((seed) => seed.slug))
|
|
144
|
+
const { cleaned } = validateDashboardLayout(record.layout, { seedSlugs })
|
|
145
|
+
return context.json({ scope, layout: cleaned })
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Upserts the dashboard layout for the default scope.
|
|
150
|
+
* Admin-only. Validates Zod shape, then semantic constraints (seed
|
|
151
|
+
* auto-cleanup, span sums, config size cap) before persisting.
|
|
152
|
+
*/
|
|
153
|
+
dashboardLayoutApp.put('/', (context) => putLayout(context, DEFAULT_DASHBOARD_SCOPE))
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Removes the stored dashboard layout for the default scope ("Reset").
|
|
157
|
+
* Admin-only. The next GET regenerates the default layout client-side.
|
|
158
|
+
*/
|
|
159
|
+
dashboardLayoutApp.delete('/', async (context) => {
|
|
160
|
+
const forbidden = requireDashboardEditPermission(context)
|
|
161
|
+
if (forbidden) return forbidden
|
|
162
|
+
|
|
163
|
+
await context.get('dashboardLayoutRepository').remove(DEFAULT_DASHBOARD_SCOPE)
|
|
164
|
+
return context.json({ ok: true })
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Upserts the dashboard layout for an arbitrary scope (`'default'` or
|
|
169
|
+
* `'role:<role>'`). Admin-only, `400` problem on an unknown scope.
|
|
170
|
+
*/
|
|
171
|
+
dashboardLayoutApp.put('/:scope', async (context) => {
|
|
172
|
+
const scope = context.req.param('scope')
|
|
173
|
+
if (!isValidDashboardScope(scope)) {
|
|
174
|
+
return publicProblem(context, {
|
|
175
|
+
type: 'invalid-scope',
|
|
176
|
+
title: 'Invalid scope',
|
|
177
|
+
status: 400,
|
|
178
|
+
detail: `Unknown dashboard scope '${scope}'.`,
|
|
179
|
+
})
|
|
180
|
+
}
|
|
181
|
+
return putLayout(context, scope)
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Removes the stored dashboard layout for an arbitrary scope ("Reset").
|
|
186
|
+
* Admin-only, `400` problem on an unknown scope.
|
|
187
|
+
*/
|
|
188
|
+
dashboardLayoutApp.delete('/:scope', async (context) => {
|
|
189
|
+
const forbidden = requireDashboardEditPermission(context)
|
|
190
|
+
if (forbidden) return forbidden
|
|
191
|
+
|
|
192
|
+
const scope = context.req.param('scope')
|
|
193
|
+
if (!isValidDashboardScope(scope)) {
|
|
194
|
+
return publicProblem(context, {
|
|
195
|
+
type: 'invalid-scope',
|
|
196
|
+
title: 'Invalid scope',
|
|
197
|
+
status: 400,
|
|
198
|
+
detail: `Unknown dashboard scope '${scope}'.`,
|
|
199
|
+
})
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
await context.get('dashboardLayoutRepository').remove(scope)
|
|
203
|
+
return context.json({ ok: true })
|
|
204
|
+
})
|
|
205
|
+
|
|
206
|
+
export { dashboardLayoutApp }
|