@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,213 +1,213 @@
1
- -- =============================================================================
2
- -- Beech CMS v0.4.0 — Base Schema
3
- --
4
- -- Single migration for fresh installations. Creates all system tables.
5
- --
6
- -- Content tables (content_{slug}, fts_{slug}, content_{slug}_drafts) are
7
- -- NOT defined here — they are generated at deploy time by: beech seed:load
8
- -- FTS indexes text + richtext branches (policies.search !== false).
9
- --
10
- -- Usage:
11
- -- wrangler d1 execute beech-db --file=migrations/0000_v040_base.sql (remote)
12
- -- wrangler d1 execute beech-db --local --file=migrations/0000_v040_base.sql (local)
13
- --
14
- -- After this migration, run:
15
- -- beech seed:load → creates content_{slug} tables + FTS + triggers
16
- -- POST /auth/setup → creates first admin user
17
- -- =============================================================================
18
-
19
-
20
- -- =============================================================================
21
- -- 1. USERS
22
- -- Dashboard users (admins + editors). Passwords stored as bcrypt hashes.
23
- -- Profile fields (name, avatar_url, notification_prefs) merged in from
24
- -- the start — no incremental ALTER TABLE needed.
25
- -- =============================================================================
26
-
27
- CREATE TABLE IF NOT EXISTS users (
28
- id TEXT NOT NULL PRIMARY KEY,
29
- email TEXT NOT NULL UNIQUE,
30
- password_hash TEXT NOT NULL,
31
- role TEXT NOT NULL DEFAULT 'editor' CHECK (role IN ('admin', 'editor')),
32
- name TEXT,
33
- avatar_url TEXT,
34
- notification_prefs TEXT NOT NULL DEFAULT '{}',
35
- created_at INTEGER NOT NULL DEFAULT (unixepoch())
36
- );
37
-
38
-
39
- -- =============================================================================
40
- -- 2. REFRESH TOKENS
41
- -- JWT refresh token rotation. Stored as SHA-256 hashes, never plaintext.
42
- -- revoked_at IS NULL = active token.
43
- -- =============================================================================
44
-
45
- CREATE TABLE IF NOT EXISTS refresh_tokens (
46
- id TEXT NOT NULL PRIMARY KEY,
47
- user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
48
- token_hash TEXT NOT NULL,
49
- expires_at INTEGER NOT NULL,
50
- created_at INTEGER NOT NULL DEFAULT (unixepoch()),
51
- revoked_at INTEGER DEFAULT NULL
52
- );
53
-
54
- CREATE INDEX IF NOT EXISTS idx_refresh_user ON refresh_tokens(user_id);
55
- CREATE INDEX IF NOT EXISTS idx_refresh_hash ON refresh_tokens(token_hash);
56
- CREATE INDEX IF NOT EXISTS idx_refresh_expires ON refresh_tokens(expires_at);
57
-
58
-
59
- -- =============================================================================
60
- -- 3. PASSWORD RESET TOKENS
61
- -- Single-use, 30-minute TTL, stored as SHA-256 hashes.
62
- -- used_at set on redemption to prevent replay attacks.
63
- -- =============================================================================
64
-
65
- CREATE TABLE IF NOT EXISTS password_reset_tokens (
66
- id TEXT NOT NULL PRIMARY KEY,
67
- user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
68
- token_hash TEXT NOT NULL,
69
- expires_at INTEGER NOT NULL,
70
- created_at INTEGER NOT NULL DEFAULT (unixepoch()),
71
- used_at INTEGER DEFAULT NULL
72
- );
73
-
74
- CREATE INDEX IF NOT EXISTS idx_prt_hash ON password_reset_tokens(token_hash);
75
- CREATE INDEX IF NOT EXISTS idx_prt_user ON password_reset_tokens(user_id);
76
-
77
-
78
- -- =============================================================================
79
- -- 4. PUBLIC API — IDEMPOTENCY KEYS
80
- -- Deduplicates POST requests from public consumers (e.g. contact forms).
81
- -- expires_at-based pruning keeps the table small.
82
- -- =============================================================================
83
-
84
- CREATE TABLE IF NOT EXISTS public_idempotency_keys (
85
- idempotency_key TEXT NOT NULL PRIMARY KEY,
86
- request_fingerprint TEXT NOT NULL,
87
- response_status INTEGER NOT NULL,
88
- response_body TEXT NOT NULL,
89
- created_at INTEGER NOT NULL,
90
- expires_at INTEGER NOT NULL
91
- );
92
-
93
- CREATE INDEX IF NOT EXISTS idx_idempotency_expires ON public_idempotency_keys(expires_at);
94
-
95
-
96
- -- =============================================================================
97
- -- 5. ANALYTICS
98
- -- Daily metric counters per seed and global (seed = '' sentinel).
99
- -- Metrics: 'requests' | 'visitors' | 'bandwidth_mb'
100
- -- =============================================================================
101
-
102
- CREATE TABLE IF NOT EXISTS analytics (
103
- id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
104
- day_ts INTEGER NOT NULL,
105
- metric TEXT NOT NULL,
106
- seed TEXT NOT NULL DEFAULT '',
107
- value INTEGER NOT NULL DEFAULT 0,
108
- UNIQUE(day_ts, metric, seed)
109
- );
110
-
111
- CREATE INDEX IF NOT EXISTS idx_analytics_day ON analytics(day_ts);
112
- CREATE INDEX IF NOT EXISTS idx_analytics_seed ON analytics(seed, day_ts);
113
-
114
-
115
- -- =============================================================================
116
- -- 6. SYSTEM STATS
117
- -- Persistent key-value store for system-level counters.
118
- -- 'total_storage_bytes' is kept for dashboard widgets;
119
- -- SUM(size_bytes) FROM media_objects is the authoritative source.
120
- -- =============================================================================
121
-
122
- CREATE TABLE IF NOT EXISTS system_stats (
123
- id TEXT NOT NULL PRIMARY KEY,
124
- value TEXT NOT NULL
125
- );
126
-
127
- INSERT OR IGNORE INTO system_stats (id, value) VALUES ('total_storage_bytes', '0');
128
-
129
-
130
- -- =============================================================================
131
- -- 7. ACTIVITY LOGS
132
- -- Append-only audit log. No FK on user_id — deleted users are retained
133
- -- for compliance. user_name denormalized to survive user deletions.
134
- -- Actions: 'create' | 'update' | 'delete' | 'upload'
135
- -- Entity types: 'content' | 'media'
136
- -- =============================================================================
137
-
138
- CREATE TABLE IF NOT EXISTS activity_logs (
139
- id TEXT NOT NULL PRIMARY KEY,
140
- user_id TEXT NOT NULL,
141
- user_email TEXT NOT NULL,
142
- user_name TEXT,
143
- action TEXT NOT NULL,
144
- entity_type TEXT NOT NULL,
145
- entity_id TEXT NOT NULL,
146
- entity_slug TEXT,
147
- details TEXT,
148
- created_at INTEGER NOT NULL DEFAULT (unixepoch())
149
- );
150
-
151
- CREATE INDEX IF NOT EXISTS idx_activity_user ON activity_logs(user_id);
152
- CREATE INDEX IF NOT EXISTS idx_activity_created ON activity_logs(created_at);
153
-
154
-
155
- -- =============================================================================
156
- -- 8. NOTIFICATIONS
157
- -- In-app notification inbox for system events (e.g. new form submission).
158
- -- is_read: 0 = unread, 1 = read.
159
- -- =============================================================================
160
-
161
- CREATE TABLE IF NOT EXISTS notifications (
162
- id TEXT NOT NULL PRIMARY KEY,
163
- title TEXT NOT NULL,
164
- message TEXT NOT NULL,
165
- type TEXT NOT NULL DEFAULT 'info' CHECK (type IN ('info', 'warning', 'error')),
166
- is_read INTEGER NOT NULL DEFAULT 0 CHECK (is_read IN (0, 1)),
167
- created_at INTEGER NOT NULL DEFAULT (unixepoch())
168
- );
169
-
170
- CREATE INDEX IF NOT EXISTS idx_notifications_created ON notifications(created_at);
171
- CREATE INDEX IF NOT EXISTS idx_notifications_unread ON notifications(is_read);
172
-
173
-
174
- -- =============================================================================
175
- -- 9. MEDIA OBJECTS
176
- -- Tracks every file uploaded to R2. Enables media library UI, orphan
177
- -- detection, and storage reporting. No FK on uploaded_by for D1 portability.
178
- -- =============================================================================
179
-
180
- CREATE TABLE IF NOT EXISTS media_objects (
181
- key TEXT NOT NULL PRIMARY KEY,
182
- filename TEXT NOT NULL,
183
- mime_type TEXT NOT NULL,
184
- size_bytes INTEGER NOT NULL,
185
- uploaded_by TEXT NOT NULL DEFAULT '',
186
- created_at INTEGER NOT NULL DEFAULT (unixepoch())
187
- );
188
-
189
- CREATE INDEX IF NOT EXISTS idx_media_user ON media_objects(uploaded_by);
190
- CREATE INDEX IF NOT EXISTS idx_media_created ON media_objects(created_at DESC);
191
-
192
-
193
- -- =============================================================================
194
- -- 10. CONTENT EVENT LOG
195
- -- Lightweight event log for activity feed and dashboard stats.
196
- -- Does NOT store field data — only event metadata (who did what, when).
197
- -- Replaces the legacy content_entries table as cross-seed event source.
198
- -- The actual content lives in content_{slug} tables (created by seed:load).
199
- -- =============================================================================
200
-
201
- CREATE TABLE IF NOT EXISTS content_event_log (
202
- id TEXT NOT NULL PRIMARY KEY,
203
- schema_slug TEXT NOT NULL,
204
- entry_id TEXT NOT NULL,
205
- action TEXT NOT NULL CHECK (action IN ('create', 'update', 'delete')),
206
- user_id TEXT,
207
- details TEXT,
208
- created_at INTEGER NOT NULL DEFAULT (unixepoch())
209
- );
210
-
211
- CREATE INDEX IF NOT EXISTS idx_event_log_schema_slug ON content_event_log(schema_slug);
212
- CREATE INDEX IF NOT EXISTS idx_event_log_created_at ON content_event_log(created_at DESC);
213
- CREATE INDEX IF NOT EXISTS idx_event_log_entry_id ON content_event_log(entry_id);
1
+ -- =============================================================================
2
+ -- Beech CMS v0.4.0 — Base Schema
3
+ --
4
+ -- Single migration for fresh installations. Creates all system tables.
5
+ --
6
+ -- Content tables (content_{slug}, fts_{slug}, content_{slug}_drafts) are
7
+ -- NOT defined here — they are generated at deploy time by: beech seed:load
8
+ -- FTS indexes text + richtext branches (policies.search !== false).
9
+ --
10
+ -- Usage:
11
+ -- wrangler d1 execute beech-db --file=migrations/0000_v040_base.sql (remote)
12
+ -- wrangler d1 execute beech-db --local --file=migrations/0000_v040_base.sql (local)
13
+ --
14
+ -- After this migration, run:
15
+ -- beech seed:load → creates content_{slug} tables + FTS + triggers
16
+ -- POST /auth/setup → creates first admin user
17
+ -- =============================================================================
18
+
19
+
20
+ -- =============================================================================
21
+ -- 1. USERS
22
+ -- Dashboard users (admins + editors). Passwords stored as bcrypt hashes.
23
+ -- Profile fields (name, avatar_url, notification_prefs) merged in from
24
+ -- the start — no incremental ALTER TABLE needed.
25
+ -- =============================================================================
26
+
27
+ CREATE TABLE IF NOT EXISTS users (
28
+ id TEXT NOT NULL PRIMARY KEY,
29
+ email TEXT NOT NULL UNIQUE,
30
+ password_hash TEXT NOT NULL,
31
+ role TEXT NOT NULL DEFAULT 'editor' CHECK (role IN ('admin', 'editor')),
32
+ name TEXT,
33
+ avatar_url TEXT,
34
+ notification_prefs TEXT NOT NULL DEFAULT '{}',
35
+ created_at INTEGER NOT NULL DEFAULT (unixepoch())
36
+ );
37
+
38
+
39
+ -- =============================================================================
40
+ -- 2. REFRESH TOKENS
41
+ -- JWT refresh token rotation. Stored as SHA-256 hashes, never plaintext.
42
+ -- revoked_at IS NULL = active token.
43
+ -- =============================================================================
44
+
45
+ CREATE TABLE IF NOT EXISTS refresh_tokens (
46
+ id TEXT NOT NULL PRIMARY KEY,
47
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
48
+ token_hash TEXT NOT NULL,
49
+ expires_at INTEGER NOT NULL,
50
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
51
+ revoked_at INTEGER DEFAULT NULL
52
+ );
53
+
54
+ CREATE INDEX IF NOT EXISTS idx_refresh_user ON refresh_tokens(user_id);
55
+ CREATE INDEX IF NOT EXISTS idx_refresh_hash ON refresh_tokens(token_hash);
56
+ CREATE INDEX IF NOT EXISTS idx_refresh_expires ON refresh_tokens(expires_at);
57
+
58
+
59
+ -- =============================================================================
60
+ -- 3. PASSWORD RESET TOKENS
61
+ -- Single-use, 30-minute TTL, stored as SHA-256 hashes.
62
+ -- used_at set on redemption to prevent replay attacks.
63
+ -- =============================================================================
64
+
65
+ CREATE TABLE IF NOT EXISTS password_reset_tokens (
66
+ id TEXT NOT NULL PRIMARY KEY,
67
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
68
+ token_hash TEXT NOT NULL,
69
+ expires_at INTEGER NOT NULL,
70
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
71
+ used_at INTEGER DEFAULT NULL
72
+ );
73
+
74
+ CREATE INDEX IF NOT EXISTS idx_prt_hash ON password_reset_tokens(token_hash);
75
+ CREATE INDEX IF NOT EXISTS idx_prt_user ON password_reset_tokens(user_id);
76
+
77
+
78
+ -- =============================================================================
79
+ -- 4. PUBLIC API — IDEMPOTENCY KEYS
80
+ -- Deduplicates POST requests from public consumers (e.g. contact forms).
81
+ -- expires_at-based pruning keeps the table small.
82
+ -- =============================================================================
83
+
84
+ CREATE TABLE IF NOT EXISTS public_idempotency_keys (
85
+ idempotency_key TEXT NOT NULL PRIMARY KEY,
86
+ request_fingerprint TEXT NOT NULL,
87
+ response_status INTEGER NOT NULL,
88
+ response_body TEXT NOT NULL,
89
+ created_at INTEGER NOT NULL,
90
+ expires_at INTEGER NOT NULL
91
+ );
92
+
93
+ CREATE INDEX IF NOT EXISTS idx_idempotency_expires ON public_idempotency_keys(expires_at);
94
+
95
+
96
+ -- =============================================================================
97
+ -- 5. ANALYTICS
98
+ -- Daily metric counters per seed and global (seed = '' sentinel).
99
+ -- Metrics: 'requests' | 'visitors' | 'bandwidth_mb'
100
+ -- =============================================================================
101
+
102
+ CREATE TABLE IF NOT EXISTS analytics (
103
+ id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
104
+ day_ts INTEGER NOT NULL,
105
+ metric TEXT NOT NULL,
106
+ seed TEXT NOT NULL DEFAULT '',
107
+ value INTEGER NOT NULL DEFAULT 0,
108
+ UNIQUE(day_ts, metric, seed)
109
+ );
110
+
111
+ CREATE INDEX IF NOT EXISTS idx_analytics_day ON analytics(day_ts);
112
+ CREATE INDEX IF NOT EXISTS idx_analytics_seed ON analytics(seed, day_ts);
113
+
114
+
115
+ -- =============================================================================
116
+ -- 6. SYSTEM STATS
117
+ -- Persistent key-value store for system-level counters.
118
+ -- 'total_storage_bytes' is kept for dashboard widgets;
119
+ -- SUM(size_bytes) FROM media_objects is the authoritative source.
120
+ -- =============================================================================
121
+
122
+ CREATE TABLE IF NOT EXISTS system_stats (
123
+ id TEXT NOT NULL PRIMARY KEY,
124
+ value TEXT NOT NULL
125
+ );
126
+
127
+ INSERT OR IGNORE INTO system_stats (id, value) VALUES ('total_storage_bytes', '0');
128
+
129
+
130
+ -- =============================================================================
131
+ -- 7. ACTIVITY LOGS
132
+ -- Append-only audit log. No FK on user_id — deleted users are retained
133
+ -- for compliance. user_name denormalized to survive user deletions.
134
+ -- Actions: 'create' | 'update' | 'delete' | 'upload'
135
+ -- Entity types: 'content' | 'media'
136
+ -- =============================================================================
137
+
138
+ CREATE TABLE IF NOT EXISTS activity_logs (
139
+ id TEXT NOT NULL PRIMARY KEY,
140
+ user_id TEXT NOT NULL,
141
+ user_email TEXT NOT NULL,
142
+ user_name TEXT,
143
+ action TEXT NOT NULL,
144
+ entity_type TEXT NOT NULL,
145
+ entity_id TEXT NOT NULL,
146
+ entity_slug TEXT,
147
+ details TEXT,
148
+ created_at INTEGER NOT NULL DEFAULT (unixepoch())
149
+ );
150
+
151
+ CREATE INDEX IF NOT EXISTS idx_activity_user ON activity_logs(user_id);
152
+ CREATE INDEX IF NOT EXISTS idx_activity_created ON activity_logs(created_at);
153
+
154
+
155
+ -- =============================================================================
156
+ -- 8. NOTIFICATIONS
157
+ -- In-app notification inbox for system events (e.g. new form submission).
158
+ -- is_read: 0 = unread, 1 = read.
159
+ -- =============================================================================
160
+
161
+ CREATE TABLE IF NOT EXISTS notifications (
162
+ id TEXT NOT NULL PRIMARY KEY,
163
+ title TEXT NOT NULL,
164
+ message TEXT NOT NULL,
165
+ type TEXT NOT NULL DEFAULT 'info' CHECK (type IN ('info', 'warning', 'error')),
166
+ is_read INTEGER NOT NULL DEFAULT 0 CHECK (is_read IN (0, 1)),
167
+ created_at INTEGER NOT NULL DEFAULT (unixepoch())
168
+ );
169
+
170
+ CREATE INDEX IF NOT EXISTS idx_notifications_created ON notifications(created_at);
171
+ CREATE INDEX IF NOT EXISTS idx_notifications_unread ON notifications(is_read);
172
+
173
+
174
+ -- =============================================================================
175
+ -- 9. MEDIA OBJECTS
176
+ -- Tracks every file uploaded to R2. Enables media library UI, orphan
177
+ -- detection, and storage reporting. No FK on uploaded_by for D1 portability.
178
+ -- =============================================================================
179
+
180
+ CREATE TABLE IF NOT EXISTS media_objects (
181
+ key TEXT NOT NULL PRIMARY KEY,
182
+ filename TEXT NOT NULL,
183
+ mime_type TEXT NOT NULL,
184
+ size_bytes INTEGER NOT NULL,
185
+ uploaded_by TEXT NOT NULL DEFAULT '',
186
+ created_at INTEGER NOT NULL DEFAULT (unixepoch())
187
+ );
188
+
189
+ CREATE INDEX IF NOT EXISTS idx_media_user ON media_objects(uploaded_by);
190
+ CREATE INDEX IF NOT EXISTS idx_media_created ON media_objects(created_at DESC);
191
+
192
+
193
+ -- =============================================================================
194
+ -- 10. CONTENT EVENT LOG
195
+ -- Lightweight event log for activity feed and dashboard stats.
196
+ -- Does NOT store field data — only event metadata (who did what, when).
197
+ -- Replaces the legacy content_entries table as cross-seed event source.
198
+ -- The actual content lives in content_{slug} tables (created by seed:load).
199
+ -- =============================================================================
200
+
201
+ CREATE TABLE IF NOT EXISTS content_event_log (
202
+ id TEXT NOT NULL PRIMARY KEY,
203
+ schema_slug TEXT NOT NULL,
204
+ entry_id TEXT NOT NULL,
205
+ action TEXT NOT NULL CHECK (action IN ('create', 'update', 'delete')),
206
+ user_id TEXT,
207
+ details TEXT,
208
+ created_at INTEGER NOT NULL DEFAULT (unixepoch())
209
+ );
210
+
211
+ CREATE INDEX IF NOT EXISTS idx_event_log_schema_slug ON content_event_log(schema_slug);
212
+ CREATE INDEX IF NOT EXISTS idx_event_log_created_at ON content_event_log(created_at DESC);
213
+ CREATE INDEX IF NOT EXISTS idx_event_log_entry_id ON content_event_log(entry_id);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@beechcms/api",
3
- "version": "0.4.0-preview.9",
3
+ "version": "0.4.1",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/factory.ts"
@@ -22,7 +22,7 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@aws-sdk/client-s3": "^3.995.0",
25
- "@beechcms/core": "^0.4.0-preview.9",
25
+ "@beechcms/core": "^0.4.1",
26
26
  "bcryptjs": "^2.4.3",
27
27
  "hono": "^4.11.9",
28
28
  "jose": "^6.1.3"
@@ -0,0 +1,20 @@
1
+ import bcrypt from 'bcryptjs'
2
+ import type { IHashProvider } from '@beechcms/core'
3
+
4
+ const DEFAULT_BCRYPT_ROUNDS = 10
5
+
6
+ export class BcryptHashProvider implements IHashProvider {
7
+ private readonly saltRounds: number
8
+
9
+ constructor(saltRounds: number = DEFAULT_BCRYPT_ROUNDS) {
10
+ this.saltRounds = saltRounds
11
+ }
12
+
13
+ async hash(plaintextPassword: string): Promise<string> {
14
+ return bcrypt.hash(plaintextPassword, this.saltRounds)
15
+ }
16
+
17
+ async verify(plaintextPassword: string, storedHash: string): Promise<boolean> {
18
+ return bcrypt.compare(plaintextPassword, storedHash)
19
+ }
20
+ }
@@ -1,10 +1,10 @@
1
- /** Messaggi di errore API auth - usati da handler e test */
2
- export const AUTH_ERRORS = {
3
- INVALID_REQUEST: 'Invalid request',
4
- INVALID_CREDENTIALS: 'Invalid credentials',
5
- DATABASE_ERROR: 'Database error',
6
- /** Messaggio generico per errori 500 - non rivela dettagli del sistema */
7
- GENERIC_ERROR: 'An error occurred',
8
- /** Rate limit superato */
9
- RATE_LIMIT_EXCEEDED: 'Too many requests',
10
- } as const
1
+ /** API auth error messages - used by handlers and tests */
2
+ export const AUTH_ERRORS = {
3
+ INVALID_REQUEST: 'Invalid request',
4
+ INVALID_CREDENTIALS: 'Invalid credentials',
5
+ DATABASE_ERROR: 'Database error',
6
+ /** Generic message for 500 errors - does not reveal system details */
7
+ GENERIC_ERROR: 'An error occurred',
8
+ /** Rate limit exceeded */
9
+ RATE_LIMIT_EXCEEDED: 'Too many requests',
10
+ } as const
@@ -0,0 +1,19 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { generateRefreshToken } from './refresh'
3
+
4
+ describe('generateRefreshToken', () => {
5
+ it('returns a non-empty string', () => {
6
+ expect(generateRefreshToken().length).toBeGreaterThan(0)
7
+ })
8
+
9
+ it('returns a UUID-shaped value (8-4-4-4-12 hex groups)', () => {
10
+ expect(generateRefreshToken()).toMatch(
11
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
12
+ )
13
+ })
14
+
15
+ it('returns a different token on every call', () => {
16
+ const tokens = new Set(Array.from({ length: 10 }, () => generateRefreshToken()))
17
+ expect(tokens.size).toBe(10)
18
+ })
19
+ })
@@ -0,0 +1,46 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { InMemoryHashProvider } from './in-memory-hash-provider'
3
+ import { BcryptHashProvider } from './bcrypt-hash-provider'
4
+
5
+ describe('InMemoryHashProvider', () => {
6
+ const provider = new InMemoryHashProvider()
7
+
8
+ it('hash returns the HASH: prefix concatenated with the plaintext', async () => {
9
+ expect(await provider.hash('mypassword')).toBe('HASH:mypassword')
10
+ })
11
+
12
+ it('verify returns true when the plaintext matches the stored hash', async () => {
13
+ const hash = await provider.hash('correct')
14
+ expect(await provider.verify('correct', hash)).toBe(true)
15
+ })
16
+
17
+ it('verify returns false when the plaintext does not match', async () => {
18
+ const hash = await provider.hash('correct')
19
+ expect(await provider.verify('wrong', hash)).toBe(false)
20
+ })
21
+
22
+ it('verify returns false for a string that does not follow the HASH: format', async () => {
23
+ expect(await provider.verify('anything', 'not-a-prefixed-hash')).toBe(false)
24
+ })
25
+ })
26
+
27
+ describe('BcryptHashProvider', () => {
28
+ // Use 4 salt rounds so the test runs in milliseconds.
29
+ const provider = new BcryptHashProvider(4)
30
+
31
+ it('hash and verify roundtrip: correct password returns true', async () => {
32
+ const hash = await provider.hash('secure-password')
33
+ expect(await provider.verify('secure-password', hash)).toBe(true)
34
+ })
35
+
36
+ it('verify returns false for an incorrect password', async () => {
37
+ const hash = await provider.hash('correct')
38
+ expect(await provider.verify('incorrect', hash)).toBe(false)
39
+ })
40
+
41
+ it('verify returns false against the DUMMY_PASSWORD_HASH for any plaintext', async () => {
42
+ // The dummy hash is used for timing-attack mitigation; it must not match real passwords.
43
+ const dummyHash = '$2a$10$SbkRFOafACxVM2ahxerVDu3tSkCXWm29b62WdB.4WGG02Qjsfzni6'
44
+ expect(await provider.verify('password123', dummyHash)).toBe(false)
45
+ })
46
+ })
@@ -0,0 +1,13 @@
1
+ import type { IHashProvider } from '@beechcms/core'
2
+
3
+ const HASH_PREFIX = 'HASH:'
4
+
5
+ export class InMemoryHashProvider implements IHashProvider {
6
+ async hash(plaintextPassword: string): Promise<string> {
7
+ return HASH_PREFIX + plaintextPassword
8
+ }
9
+
10
+ async verify(plaintextPassword: string, storedHash: string): Promise<boolean> {
11
+ return storedHash === HASH_PREFIX + plaintextPassword
12
+ }
13
+ }
@@ -0,0 +1,55 @@
1
+ import { SignJWT, jwtVerify } from 'jose'
2
+ import type { ITokenService, IssueTokenOptions, JwtClaims, IClock } from '@beechcms/core'
3
+
4
+ const DEFAULT_TOKEN_TTL_SECONDS = 900
5
+ const DEFAULT_ALGORITHM = 'HS256' as const
6
+
7
+ export interface JoseTokenServiceConfig {
8
+ issuer?: string
9
+ audience?: string
10
+ algorithm?: 'HS256' | 'HS384' | 'HS512'
11
+ }
12
+
13
+ export class JoseTokenService implements ITokenService {
14
+ private readonly secretBytes: Uint8Array
15
+ private readonly config: JoseTokenServiceConfig
16
+ private readonly clock: IClock
17
+
18
+ constructor(secret: string, config: JoseTokenServiceConfig, clock: IClock) {
19
+ this.secretBytes = new TextEncoder().encode(secret)
20
+ this.config = config
21
+ this.clock = clock
22
+ }
23
+
24
+ async issue(claims: JwtClaims, options?: IssueTokenOptions): Promise<string> {
25
+ const { sub, ...remainingClaims } = claims
26
+ const ttlSeconds = options?.ttlSeconds ?? DEFAULT_TOKEN_TTL_SECONDS
27
+ const algorithm = this.config.algorithm ?? DEFAULT_ALGORITHM
28
+ const issuedAtSeconds = this.clock.nowSeconds()
29
+
30
+ let builder = new SignJWT(remainingClaims)
31
+ .setProtectedHeader({ alg: algorithm, typ: 'JWT' })
32
+ .setSubject(sub)
33
+ .setIssuedAt(issuedAtSeconds)
34
+ .setExpirationTime(issuedAtSeconds + ttlSeconds)
35
+
36
+ if (this.config.issuer) builder = builder.setIssuer(this.config.issuer)
37
+ if (this.config.audience) builder = builder.setAudience(this.config.audience)
38
+
39
+ return builder.sign(this.secretBytes)
40
+ }
41
+
42
+ async verify(token: string): Promise<JwtClaims | null> {
43
+ try {
44
+ const algorithm = this.config.algorithm ?? DEFAULT_ALGORITHM
45
+ const { payload } = await jwtVerify(token, this.secretBytes, {
46
+ algorithms: [algorithm],
47
+ issuer: this.config.issuer,
48
+ audience: this.config.audience,
49
+ })
50
+ return payload as JwtClaims
51
+ } catch {
52
+ return null
53
+ }
54
+ }
55
+ }