@basicbenframework/cms 0.0.0-stage → 0.6.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 (590) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +206 -2
  3. package/db/migrations/001_create_users.js +15 -0
  4. package/db/migrations/002_create_posts.js +18 -0
  5. package/db/migrations/003_create_categories.js +19 -0
  6. package/db/migrations/004_create_tags.js +16 -0
  7. package/db/migrations/005_create_post_tags.js +16 -0
  8. package/db/migrations/006_create_pages.js +26 -0
  9. package/db/migrations/007_create_comments.js +24 -0
  10. package/db/migrations/008_create_media.js +22 -0
  11. package/db/migrations/009_update_posts_blogging.js +27 -0
  12. package/db/migrations/010_create_settings.js +29 -0
  13. package/db/migrations/011_add_user_roles.js +23 -0
  14. package/db/migrations/012_create_auth_tokens.js +30 -0
  15. package/db/migrations/013_add_email_verified.js +24 -0
  16. package/db/migrations/014_create_user_two_factor.js +30 -0
  17. package/db/migrations/015_create_user_credentials.js +35 -0
  18. package/db/migrations/016_create_rate_limits.js +31 -0
  19. package/db/migrations/017_add_content_html.js +38 -0
  20. package/db/migrations/018_create_api_tokens.js +34 -0
  21. package/db/migrations/019_create_post_categories.js +40 -0
  22. package/db/migrations/020_add_author_profiles.js +60 -0
  23. package/db/migrations/021_add_page_featured_image.js +23 -0
  24. package/db/migrations/022_backfill_post_slugs_and_excerpts.js +57 -0
  25. package/db/migrations/023_add_user_session_controls.js +25 -0
  26. package/db/migrations/024_add_post_status_and_trash.js +45 -0
  27. package/db/migrations/025_add_social_and_indexing_fields.js +40 -0
  28. package/db/migrations/026_create_post_revisions.js +29 -0
  29. package/db/migrations/027_add_media_dimensions.js +19 -0
  30. package/db/migrations/028_create_navigation_menus.js +65 -0
  31. package/db/migrations/029_create_redirects.js +40 -0
  32. package/db/migrations/030_add_comment_status_and_notifications.js +53 -0
  33. package/db/migrations/031_create_post_locks.js +38 -0
  34. package/db/migrations/032_create_snippets.js +31 -0
  35. package/db/migrations/033_create_members.js +70 -0
  36. package/db/migrations/034_add_post_visibility.js +28 -0
  37. package/db/migrations/035_create_newsletters.js +72 -0
  38. package/db/migrations/036_create_analytics.js +89 -0
  39. package/db/migrations/037_create_ops_heartbeats.js +30 -0
  40. package/db/migrations/038_create_content_types.js +84 -0
  41. package/db/migrations/039_create_content_type_fields.js +47 -0
  42. package/db/migrations/040_create_taxonomies.js +80 -0
  43. package/db/migrations/041_add_newsletter_handoff.js +28 -0
  44. package/db/migrations/042_create_mysendbox_contacts.js +63 -0
  45. package/lib/cli/backup.d.mts +2 -0
  46. package/lib/cli/backup.mjs +124 -0
  47. package/lib/cli/export.d.mts +2 -0
  48. package/lib/cli/export.mjs +54 -0
  49. package/lib/cli/import-ghost.d.mts +2 -0
  50. package/lib/cli/import-ghost.mjs +50 -0
  51. package/lib/cli/import-json.d.mts +2 -0
  52. package/lib/cli/import-json.mjs +61 -0
  53. package/lib/cli/import-wordpress.d.mts +2 -0
  54. package/lib/cli/import-wordpress.mjs +169 -0
  55. package/lib/cli/import-wxr.d.mts +2 -0
  56. package/lib/cli/import-wxr.mjs +55 -0
  57. package/lib/cli/index.d.mts +2 -0
  58. package/lib/cli/index.mjs +53 -0
  59. package/lib/cli/lib/backup.d.mts +112 -0
  60. package/lib/cli/lib/backup.mjs +297 -0
  61. package/lib/cli/lib/ghost.d.mts +30 -0
  62. package/lib/cli/lib/ghost.mjs +201 -0
  63. package/lib/cli/lib/html-to-markdown.d.mts +61 -0
  64. package/lib/cli/lib/html-to-markdown.mjs +523 -0
  65. package/lib/cli/lib/import-common.d.mts +100 -0
  66. package/lib/cli/lib/import-common.mjs +252 -0
  67. package/lib/cli/lib/json-import.d.mts +22 -0
  68. package/lib/cli/lib/json-import.mjs +422 -0
  69. package/lib/cli/lib/site-import.d.mts +32 -0
  70. package/lib/cli/lib/site-import.mjs +456 -0
  71. package/lib/cli/lib/wordpress-rest.d.mts +25 -0
  72. package/lib/cli/lib/wordpress-rest.mjs +177 -0
  73. package/lib/cli/lib/wxr.d.mts +18 -0
  74. package/lib/cli/lib/wxr.mjs +307 -0
  75. package/lib/cli/lib/xml.d.mts +33 -0
  76. package/lib/cli/lib/xml.mjs +186 -0
  77. package/lib/cli/restore.d.mts +2 -0
  78. package/lib/cli/restore.mjs +98 -0
  79. package/lib/client/components/Alert.d.ts +7 -0
  80. package/lib/client/components/Alert.js +8 -0
  81. package/lib/client/components/Avatar.d.ts +15 -0
  82. package/lib/client/components/Avatar.js +10 -0
  83. package/lib/client/components/BackLink.d.ts +7 -0
  84. package/lib/client/components/BackLink.js +6 -0
  85. package/lib/client/components/Button.d.ts +7 -0
  86. package/lib/client/components/Button.js +12 -0
  87. package/lib/client/components/Card.d.ts +7 -0
  88. package/lib/client/components/Card.js +6 -0
  89. package/lib/client/components/CommentThread.d.ts +15 -0
  90. package/lib/client/components/CommentThread.js +101 -0
  91. package/lib/client/components/Empty.d.ts +6 -0
  92. package/lib/client/components/Empty.js +6 -0
  93. package/lib/client/components/Input.d.ts +6 -0
  94. package/lib/client/components/Input.js +6 -0
  95. package/lib/client/components/Link.d.ts +31 -0
  96. package/lib/client/components/Link.js +49 -0
  97. package/lib/client/components/Loading.d.ts +1 -0
  98. package/lib/client/components/Loading.js +6 -0
  99. package/lib/client/components/Logo.d.ts +5 -0
  100. package/lib/client/components/Logo.js +4 -0
  101. package/lib/client/components/MarkdownEditor.d.ts +41 -0
  102. package/lib/client/components/MarkdownEditor.js +156 -0
  103. package/lib/client/components/Nav/DarkModeToggle.d.ts +6 -0
  104. package/lib/client/components/Nav/DarkModeToggle.js +6 -0
  105. package/lib/client/components/Nav/DesktopNav.d.ts +8 -0
  106. package/lib/client/components/Nav/DesktopNav.js +9 -0
  107. package/lib/client/components/Nav/MobileNav.d.ts +9 -0
  108. package/lib/client/components/Nav/MobileNav.js +15 -0
  109. package/lib/client/components/NavLink.d.ts +8 -0
  110. package/lib/client/components/NavLink.js +6 -0
  111. package/lib/client/components/PageHeader.d.ts +8 -0
  112. package/lib/client/components/PageHeader.js +6 -0
  113. package/lib/client/components/PostCard.d.ts +8 -0
  114. package/lib/client/components/PostCard.js +7 -0
  115. package/lib/client/components/Textarea.d.ts +6 -0
  116. package/lib/client/components/Textarea.js +6 -0
  117. package/lib/client/components/ThemeContext.d.ts +18 -0
  118. package/lib/client/components/ThemeContext.js +8 -0
  119. package/lib/client/components/admin/AdminIcons.d.ts +13 -0
  120. package/lib/client/components/admin/AdminIcons.js +66 -0
  121. package/lib/client/components/admin/ContentModelPanels.d.ts +22 -0
  122. package/lib/client/components/admin/ContentModelPanels.js +93 -0
  123. package/lib/client/components/admin/FeaturedImageBox.d.ts +21 -0
  124. package/lib/client/components/admin/FeaturedImageBox.js +24 -0
  125. package/lib/client/components/admin/MediaGrid.d.ts +23 -0
  126. package/lib/client/components/admin/MediaGrid.js +69 -0
  127. package/lib/client/components/admin/MediaPicker.d.ts +17 -0
  128. package/lib/client/components/admin/MediaPicker.js +61 -0
  129. package/lib/client/components/admin/Pagination.d.ts +27 -0
  130. package/lib/client/components/admin/Pagination.js +29 -0
  131. package/lib/client/components/admin/SnippetPicker.d.ts +27 -0
  132. package/lib/client/components/admin/SnippetPicker.js +65 -0
  133. package/lib/client/components/admin/TermPicker.d.ts +52 -0
  134. package/lib/client/components/admin/TermPicker.js +58 -0
  135. package/lib/client/contexts/ToastContext.d.ts +12 -0
  136. package/lib/client/contexts/ToastContext.js +49 -0
  137. package/lib/client/features.d.ts +11 -0
  138. package/lib/client/features.js +7 -0
  139. package/lib/client/hooks/useContentTypes.d.ts +48 -0
  140. package/lib/client/hooks/useContentTypes.js +48 -0
  141. package/lib/client/hooks/useMediaLibrary.d.ts +46 -0
  142. package/lib/client/hooks/useMediaLibrary.js +189 -0
  143. package/lib/client/hooks/usePostLock.d.ts +32 -0
  144. package/lib/client/hooks/usePostLock.js +107 -0
  145. package/lib/client/host/index.d.ts +71 -0
  146. package/lib/client/host/index.js +58 -0
  147. package/lib/client/i18n/index.d.ts +79 -0
  148. package/lib/client/i18n/index.js +177 -0
  149. package/lib/client/i18n/locales/es/content.d.ts +4 -0
  150. package/lib/client/i18n/locales/es/content.js +220 -0
  151. package/lib/client/i18n/locales/es/editor.d.ts +9 -0
  152. package/lib/client/i18n/locales/es/editor.js +144 -0
  153. package/lib/client/i18n/locales/es/index.d.ts +8 -0
  154. package/lib/client/i18n/locales/es/index.js +7 -0
  155. package/lib/client/i18n/locales/es/layout.d.ts +4 -0
  156. package/lib/client/i18n/locales/es/layout.js +35 -0
  157. package/lib/client/i18n/locales/es/people.d.ts +4 -0
  158. package/lib/client/i18n/locales/es/people.js +187 -0
  159. package/lib/client/i18n/locales/es/site.d.ts +4 -0
  160. package/lib/client/i18n/locales/es/site.js +208 -0
  161. package/lib/client/layouts/AdminLayout.d.ts +7 -0
  162. package/lib/client/layouts/AdminLayout.js +1046 -0
  163. package/lib/client/layouts/AppLayout.d.ts +6 -0
  164. package/lib/client/layouts/AppLayout.js +19 -0
  165. package/lib/client/layouts/AuthLayout.d.ts +6 -0
  166. package/lib/client/layouts/AuthLayout.js +14 -0
  167. package/lib/client/layouts/DocsLayout.d.ts +6 -0
  168. package/lib/client/layouts/DocsLayout.js +28 -0
  169. package/lib/client/layouts/RootLayout.d.ts +6 -0
  170. package/lib/client/layouts/RootLayout.js +11 -0
  171. package/lib/client/pages/AcceptInvite.d.ts +8 -0
  172. package/lib/client/pages/AcceptInvite.js +60 -0
  173. package/lib/client/pages/Auth.d.ts +1 -0
  174. package/lib/client/pages/Auth.js +40 -0
  175. package/lib/client/pages/Authentication.d.ts +1 -0
  176. package/lib/client/pages/Authentication.js +230 -0
  177. package/lib/client/pages/Content.d.ts +1 -0
  178. package/lib/client/pages/Content.js +21 -0
  179. package/lib/client/pages/Database.d.ts +1 -0
  180. package/lib/client/pages/Database.js +264 -0
  181. package/lib/client/pages/Extending.d.ts +1 -0
  182. package/lib/client/pages/Extending.js +28 -0
  183. package/lib/client/pages/Feed.d.ts +1 -0
  184. package/lib/client/pages/Feed.js +19 -0
  185. package/lib/client/pages/FeedPost.d.ts +1 -0
  186. package/lib/client/pages/FeedPost.js +31 -0
  187. package/lib/client/pages/ForgotPassword.d.ts +8 -0
  188. package/lib/client/pages/ForgotPassword.js +38 -0
  189. package/lib/client/pages/GettingStarted.d.ts +1 -0
  190. package/lib/client/pages/GettingStarted.js +84 -0
  191. package/lib/client/pages/Headless.d.ts +1 -0
  192. package/lib/client/pages/Headless.js +49 -0
  193. package/lib/client/pages/Home.d.ts +1 -0
  194. package/lib/client/pages/Home.js +67 -0
  195. package/lib/client/pages/PostForm.d.ts +1 -0
  196. package/lib/client/pages/PostForm.js +55 -0
  197. package/lib/client/pages/Posts.d.ts +1 -0
  198. package/lib/client/pages/Posts.js +35 -0
  199. package/lib/client/pages/Profile.d.ts +1 -0
  200. package/lib/client/pages/Profile.js +153 -0
  201. package/lib/client/pages/ResetPassword.d.ts +8 -0
  202. package/lib/client/pages/ResetPassword.js +52 -0
  203. package/lib/client/pages/Routing.d.ts +1 -0
  204. package/lib/client/pages/Routing.js +192 -0
  205. package/lib/client/pages/Storage.d.ts +1 -0
  206. package/lib/client/pages/Storage.js +54 -0
  207. package/lib/client/pages/Testing.d.ts +1 -0
  208. package/lib/client/pages/Testing.js +141 -0
  209. package/lib/client/pages/Validation.d.ts +1 -0
  210. package/lib/client/pages/Validation.js +123 -0
  211. package/lib/client/pages/admin/Categories.d.ts +2 -0
  212. package/lib/client/pages/admin/Categories.js +75 -0
  213. package/lib/client/pages/admin/Comments.d.ts +11 -0
  214. package/lib/client/pages/admin/Comments.js +247 -0
  215. package/lib/client/pages/admin/ContentTypes.d.ts +2 -0
  216. package/lib/client/pages/admin/ContentTypes.js +163 -0
  217. package/lib/client/pages/admin/Dashboard.d.ts +2 -0
  218. package/lib/client/pages/admin/Dashboard.js +66 -0
  219. package/lib/client/pages/admin/Health.d.ts +12 -0
  220. package/lib/client/pages/admin/Health.js +148 -0
  221. package/lib/client/pages/admin/Media.d.ts +2 -0
  222. package/lib/client/pages/admin/Media.js +101 -0
  223. package/lib/client/pages/admin/Navigation.d.ts +9 -0
  224. package/lib/client/pages/admin/Navigation.js +230 -0
  225. package/lib/client/pages/admin/Pages.d.ts +2 -0
  226. package/lib/client/pages/admin/Pages.js +53 -0
  227. package/lib/client/pages/admin/PostEditor.d.ts +17 -0
  228. package/lib/client/pages/admin/PostEditor.js +532 -0
  229. package/lib/client/pages/admin/Posts.d.ts +2 -0
  230. package/lib/client/pages/admin/Posts.js +152 -0
  231. package/lib/client/pages/admin/Redirects.d.ts +10 -0
  232. package/lib/client/pages/admin/Redirects.js +87 -0
  233. package/lib/client/pages/admin/Settings.d.ts +2 -0
  234. package/lib/client/pages/admin/Settings.js +111 -0
  235. package/lib/client/pages/admin/Snippets.d.ts +14 -0
  236. package/lib/client/pages/admin/Snippets.js +85 -0
  237. package/lib/client/pages/admin/Tags.d.ts +2 -0
  238. package/lib/client/pages/admin/Tags.js +74 -0
  239. package/lib/client/pages/admin/Taxonomies.d.ts +2 -0
  240. package/lib/client/pages/admin/Taxonomies.js +130 -0
  241. package/lib/client/pages/admin/Tokens.d.ts +9 -0
  242. package/lib/client/pages/admin/Tokens.js +260 -0
  243. package/lib/client/pages/admin/Tools.d.ts +12 -0
  244. package/lib/client/pages/admin/Tools.js +111 -0
  245. package/lib/client/pages/admin/Users.d.ts +13 -0
  246. package/lib/client/pages/admin/Users.js +313 -0
  247. package/lib/client/pages/api-reference.d.ts +33 -0
  248. package/lib/client/pages/api-reference.js +198 -0
  249. package/lib/client/styles.css +37 -0
  250. package/lib/config.d.ts +24 -0
  251. package/lib/config.js +39 -0
  252. package/lib/controllers/AdminController.d.ts +46 -0
  253. package/lib/controllers/AdminController.js +134 -0
  254. package/lib/controllers/AuthController.d.ts +15 -0
  255. package/lib/controllers/AuthController.js +194 -0
  256. package/lib/controllers/AuthorController.d.ts +17 -0
  257. package/lib/controllers/AuthorController.js +19 -0
  258. package/lib/controllers/CategoryController.d.ts +10 -0
  259. package/lib/controllers/CategoryController.js +88 -0
  260. package/lib/controllers/CommentController.d.ts +68 -0
  261. package/lib/controllers/CommentController.js +438 -0
  262. package/lib/controllers/ContentTypeController.d.ts +24 -0
  263. package/lib/controllers/ContentTypeController.js +91 -0
  264. package/lib/controllers/EmailVerificationController.d.ts +33 -0
  265. package/lib/controllers/EmailVerificationController.js +116 -0
  266. package/lib/controllers/ExportController.d.ts +15 -0
  267. package/lib/controllers/ExportController.js +41 -0
  268. package/lib/controllers/FeedController.d.ts +14 -0
  269. package/lib/controllers/FeedController.js +246 -0
  270. package/lib/controllers/HealthController.d.ts +21 -0
  271. package/lib/controllers/HealthController.js +176 -0
  272. package/lib/controllers/HomeController.d.ts +12 -0
  273. package/lib/controllers/HomeController.js +16 -0
  274. package/lib/controllers/MediaController.d.ts +24 -0
  275. package/lib/controllers/MediaController.js +189 -0
  276. package/lib/controllers/NavigationController.d.ts +22 -0
  277. package/lib/controllers/NavigationController.js +176 -0
  278. package/lib/controllers/PageController.d.ts +13 -0
  279. package/lib/controllers/PageController.js +172 -0
  280. package/lib/controllers/PasskeyController.d.ts +36 -0
  281. package/lib/controllers/PasskeyController.js +201 -0
  282. package/lib/controllers/PasswordResetController.d.ts +44 -0
  283. package/lib/controllers/PasswordResetController.js +160 -0
  284. package/lib/controllers/PostController.d.ts +51 -0
  285. package/lib/controllers/PostController.js +538 -0
  286. package/lib/controllers/PostLockController.d.ts +62 -0
  287. package/lib/controllers/PostLockController.js +101 -0
  288. package/lib/controllers/ProfileController.d.ts +13 -0
  289. package/lib/controllers/ProfileController.js +160 -0
  290. package/lib/controllers/PublicApiController.d.ts +23 -0
  291. package/lib/controllers/PublicApiController.js +100 -0
  292. package/lib/controllers/RedirectController.d.ts +32 -0
  293. package/lib/controllers/RedirectController.js +95 -0
  294. package/lib/controllers/SettingsController.d.ts +28 -0
  295. package/lib/controllers/SettingsController.js +105 -0
  296. package/lib/controllers/SnippetController.d.ts +27 -0
  297. package/lib/controllers/SnippetController.js +123 -0
  298. package/lib/controllers/TagController.d.ts +9 -0
  299. package/lib/controllers/TagController.js +70 -0
  300. package/lib/controllers/TaxonomyController.d.ts +24 -0
  301. package/lib/controllers/TaxonomyController.js +149 -0
  302. package/lib/controllers/TokenController.d.ts +27 -0
  303. package/lib/controllers/TokenController.js +83 -0
  304. package/lib/controllers/TwoFactorController.d.ts +31 -0
  305. package/lib/controllers/TwoFactorController.js +213 -0
  306. package/lib/controllers/UserController.d.ts +110 -0
  307. package/lib/controllers/UserController.js +504 -0
  308. package/lib/features/analytics/AnalyticsPage.d.ts +11 -0
  309. package/lib/features/analytics/AnalyticsPage.js +123 -0
  310. package/lib/features/analytics/admin.d.ts +3 -0
  311. package/lib/features/analytics/admin.js +9 -0
  312. package/lib/features/analytics/controller.d.ts +19 -0
  313. package/lib/features/analytics/controller.js +79 -0
  314. package/lib/features/analytics/helpers.d.ts +84 -0
  315. package/lib/features/analytics/helpers.js +181 -0
  316. package/lib/features/analytics/i18n/es.d.ts +4 -0
  317. package/lib/features/analytics/i18n/es.js +31 -0
  318. package/lib/features/analytics/index.d.ts +28 -0
  319. package/lib/features/analytics/index.js +91 -0
  320. package/lib/features/analytics/manifest.d.ts +8 -0
  321. package/lib/features/analytics/manifest.js +18 -0
  322. package/lib/features/analytics/model.d.ts +130 -0
  323. package/lib/features/analytics/model.js +206 -0
  324. package/lib/features/members/Member.d.ts +93 -0
  325. package/lib/features/members/Member.js +194 -0
  326. package/lib/features/members/MemberAdminController.d.ts +60 -0
  327. package/lib/features/members/MemberAdminController.js +262 -0
  328. package/lib/features/members/MemberController.d.ts +88 -0
  329. package/lib/features/members/MemberController.js +250 -0
  330. package/lib/features/members/MembersPage.d.ts +10 -0
  331. package/lib/features/members/MembersPage.js +216 -0
  332. package/lib/features/members/PostAccessBox.d.ts +15 -0
  333. package/lib/features/members/PostAccessBox.js +70 -0
  334. package/lib/features/members/admin.d.ts +3 -0
  335. package/lib/features/members/admin.js +12 -0
  336. package/lib/features/members/csv.d.ts +21 -0
  337. package/lib/features/members/csv.js +74 -0
  338. package/lib/features/members/events.d.ts +34 -0
  339. package/lib/features/members/events.js +34 -0
  340. package/lib/features/members/i18n/es.d.ts +4 -0
  341. package/lib/features/members/i18n/es.js +106 -0
  342. package/lib/features/members/index.d.ts +44 -0
  343. package/lib/features/members/index.js +106 -0
  344. package/lib/features/members/manifest.d.ts +8 -0
  345. package/lib/features/members/manifest.js +18 -0
  346. package/lib/features/members/middleware.d.ts +42 -0
  347. package/lib/features/members/middleware.js +74 -0
  348. package/lib/features/members/newsletter.d.ts +177 -0
  349. package/lib/features/members/newsletter.js +439 -0
  350. package/lib/features/members/rate-limits.d.ts +34 -0
  351. package/lib/features/members/rate-limits.js +50 -0
  352. package/lib/features/members/request.d.ts +13 -0
  353. package/lib/features/members/request.js +6 -0
  354. package/lib/features/members/routes.d.ts +15 -0
  355. package/lib/features/members/routes.js +59 -0
  356. package/lib/features/members/session.d.ts +102 -0
  357. package/lib/features/members/session.js +158 -0
  358. package/lib/features/members/settings.d.ts +14 -0
  359. package/lib/features/members/settings.js +23 -0
  360. package/lib/features/mysendbox/MySendboxSettingsCard.d.ts +7 -0
  361. package/lib/features/mysendbox/MySendboxSettingsCard.js +48 -0
  362. package/lib/features/mysendbox/admin.d.ts +3 -0
  363. package/lib/features/mysendbox/admin.js +9 -0
  364. package/lib/features/mysendbox/broadcasts.d.ts +61 -0
  365. package/lib/features/mysendbox/broadcasts.js +124 -0
  366. package/lib/features/mysendbox/client.d.ts +95 -0
  367. package/lib/features/mysendbox/client.js +61 -0
  368. package/lib/features/mysendbox/config.d.ts +27 -0
  369. package/lib/features/mysendbox/config.js +74 -0
  370. package/lib/features/mysendbox/contacts.d.ts +121 -0
  371. package/lib/features/mysendbox/contacts.js +378 -0
  372. package/lib/features/mysendbox/controller.d.ts +11 -0
  373. package/lib/features/mysendbox/controller.js +47 -0
  374. package/lib/features/mysendbox/i18n/es.d.ts +4 -0
  375. package/lib/features/mysendbox/i18n/es.js +28 -0
  376. package/lib/features/mysendbox/index.d.ts +18 -0
  377. package/lib/features/mysendbox/index.js +71 -0
  378. package/lib/features/mysendbox/manifest.d.ts +7 -0
  379. package/lib/features/mysendbox/manifest.js +6 -0
  380. package/lib/features/mysendbox/routes.d.ts +6 -0
  381. package/lib/features/mysendbox/routes.js +14 -0
  382. package/lib/features/mysendbox/webhook.d.ts +23 -0
  383. package/lib/features/mysendbox/webhook.js +104 -0
  384. package/lib/features/theme/OEmbedController.d.ts +31 -0
  385. package/lib/features/theme/OEmbedController.js +128 -0
  386. package/lib/features/theme/ThemeController.d.ts +20 -0
  387. package/lib/features/theme/ThemeController.js +256 -0
  388. package/lib/features/theme/ThemeSettingsCard.d.ts +7 -0
  389. package/lib/features/theme/ThemeSettingsCard.js +12 -0
  390. package/lib/features/theme/admin.d.ts +3 -0
  391. package/lib/features/theme/admin.js +9 -0
  392. package/lib/features/theme/html.d.ts +48 -0
  393. package/lib/features/theme/html.js +97 -0
  394. package/lib/features/theme/i18n/es.d.ts +4 -0
  395. package/lib/features/theme/i18n/es.js +9 -0
  396. package/lib/features/theme/index.d.ts +11 -0
  397. package/lib/features/theme/index.js +23 -0
  398. package/lib/features/theme/manifest.d.ts +7 -0
  399. package/lib/features/theme/manifest.js +6 -0
  400. package/lib/features/theme/oembed.d.ts +36 -0
  401. package/lib/features/theme/oembed.js +58 -0
  402. package/lib/features/theme/routes.d.ts +17 -0
  403. package/lib/features/theme/routes.js +54 -0
  404. package/lib/features/theme/templates.d.ts +103 -0
  405. package/lib/features/theme/templates.js +283 -0
  406. package/lib/features.d.ts +15 -0
  407. package/lib/features.js +6 -0
  408. package/lib/features.manifest.d.ts +10 -0
  409. package/lib/features.manifest.js +6 -0
  410. package/lib/helpers/access.d.ts +62 -0
  411. package/lib/helpers/access.js +92 -0
  412. package/lib/helpers/api.d.ts +20 -0
  413. package/lib/helpers/api.js +44 -0
  414. package/lib/helpers/comment-guard.d.ts +145 -0
  415. package/lib/helpers/comment-guard.js +253 -0
  416. package/lib/helpers/comment-mail.d.ts +53 -0
  417. package/lib/helpers/comment-mail.js +188 -0
  418. package/lib/helpers/content-model.d.ts +50 -0
  419. package/lib/helpers/content-model.js +84 -0
  420. package/lib/helpers/content-paths.d.ts +107 -0
  421. package/lib/helpers/content-paths.js +200 -0
  422. package/lib/helpers/export-data.d.ts +85 -0
  423. package/lib/helpers/export-data.js +229 -0
  424. package/lib/helpers/gating.d.ts +53 -0
  425. package/lib/helpers/gating.js +83 -0
  426. package/lib/helpers/health.d.ts +91 -0
  427. package/lib/helpers/health.js +279 -0
  428. package/lib/helpers/heartbeat.d.ts +35 -0
  429. package/lib/helpers/heartbeat.js +55 -0
  430. package/lib/helpers/image-size.d.ts +18 -0
  431. package/lib/helpers/image-size.js +83 -0
  432. package/lib/helpers/images.d.ts +29 -0
  433. package/lib/helpers/images.js +41 -0
  434. package/lib/helpers/mail-templates.d.ts +11 -0
  435. package/lib/helpers/mail-templates.js +42 -0
  436. package/lib/helpers/publish-due.d.ts +28 -0
  437. package/lib/helpers/publish-due.js +67 -0
  438. package/lib/helpers/redirects.d.ts +43 -0
  439. package/lib/helpers/redirects.js +80 -0
  440. package/lib/helpers/seo-fields.d.ts +13 -0
  441. package/lib/helpers/seo-fields.js +52 -0
  442. package/lib/helpers/session.d.ts +30 -0
  443. package/lib/helpers/session.js +27 -0
  444. package/lib/helpers/site-settings.d.ts +98 -0
  445. package/lib/helpers/site-settings.js +232 -0
  446. package/lib/helpers/site.d.ts +14 -0
  447. package/lib/helpers/site.js +23 -0
  448. package/lib/helpers/write-hooks.d.ts +33 -0
  449. package/lib/helpers/write-hooks.js +37 -0
  450. package/lib/hooks.d.ts +17 -0
  451. package/lib/hooks.js +101 -0
  452. package/lib/host/core-tasks.d.ts +4 -0
  453. package/lib/host/core-tasks.js +26 -0
  454. package/lib/host/cron.d.ts +39 -0
  455. package/lib/host/cron.js +85 -0
  456. package/lib/host/enabled.d.ts +4 -0
  457. package/lib/host/enabled.js +40 -0
  458. package/lib/host/index.d.ts +81 -0
  459. package/lib/host/index.js +87 -0
  460. package/lib/host/manifest.d.ts +34 -0
  461. package/lib/host/manifest.js +7 -0
  462. package/lib/host/menu.d.ts +18 -0
  463. package/lib/host/menu.js +15 -0
  464. package/lib/main.d.ts +1 -0
  465. package/lib/main.js +24 -0
  466. package/lib/middleware/api-auth.d.ts +59 -0
  467. package/lib/middleware/api-auth.js +164 -0
  468. package/lib/middleware/auth.d.ts +49 -0
  469. package/lib/middleware/auth.js +112 -0
  470. package/lib/middleware/cache.d.ts +17 -0
  471. package/lib/middleware/cache.js +52 -0
  472. package/lib/middleware/rate-limits.d.ts +199 -0
  473. package/lib/middleware/rate-limits.js +276 -0
  474. package/lib/middleware/viewer.d.ts +13 -0
  475. package/lib/middleware/viewer.js +16 -0
  476. package/lib/models/Category.d.ts +24 -0
  477. package/lib/models/Category.js +102 -0
  478. package/lib/models/Comment.d.ts +120 -0
  479. package/lib/models/Comment.js +283 -0
  480. package/lib/models/ContentType.d.ts +142 -0
  481. package/lib/models/ContentType.js +462 -0
  482. package/lib/models/Credential.d.ts +21 -0
  483. package/lib/models/Credential.js +31 -0
  484. package/lib/models/Media.d.ts +53 -0
  485. package/lib/models/Media.js +132 -0
  486. package/lib/models/Menu.d.ts +131 -0
  487. package/lib/models/Menu.js +312 -0
  488. package/lib/models/Page.d.ts +55 -0
  489. package/lib/models/Page.js +218 -0
  490. package/lib/models/Post.d.ts +136 -0
  491. package/lib/models/Post.js +406 -0
  492. package/lib/models/PostLock.d.ts +67 -0
  493. package/lib/models/PostLock.js +112 -0
  494. package/lib/models/PostRevision.d.ts +45 -0
  495. package/lib/models/PostRevision.js +82 -0
  496. package/lib/models/PublicContent.d.ts +283 -0
  497. package/lib/models/PublicContent.js +577 -0
  498. package/lib/models/Redirect.d.ts +123 -0
  499. package/lib/models/Redirect.js +225 -0
  500. package/lib/models/Settings.d.ts +61 -0
  501. package/lib/models/Settings.js +128 -0
  502. package/lib/models/Snippet.d.ts +36 -0
  503. package/lib/models/Snippet.js +64 -0
  504. package/lib/models/Tag.d.ts +23 -0
  505. package/lib/models/Tag.js +117 -0
  506. package/lib/models/Taxonomy.d.ts +127 -0
  507. package/lib/models/Taxonomy.js +321 -0
  508. package/lib/models/TwoFactor.d.ts +26 -0
  509. package/lib/models/TwoFactor.js +60 -0
  510. package/lib/models/User.d.ts +49 -0
  511. package/lib/models/User.js +128 -0
  512. package/lib/models/derive.d.ts +69 -0
  513. package/lib/models/derive.js +81 -0
  514. package/lib/models/pagination.d.ts +30 -0
  515. package/lib/models/pagination.js +36 -0
  516. package/lib/models/visibility.d.ts +31 -0
  517. package/lib/models/visibility.js +47 -0
  518. package/lib/routes/App.d.ts +2 -0
  519. package/lib/routes/App.js +146 -0
  520. package/lib/routes/api/admin.d.ts +6 -0
  521. package/lib/routes/api/admin.js +11 -0
  522. package/lib/routes/api/auth.d.ts +6 -0
  523. package/lib/routes/api/auth.js +24 -0
  524. package/lib/routes/api/authors.d.ts +5 -0
  525. package/lib/routes/api/authors.js +8 -0
  526. package/lib/routes/api/categories.d.ts +8 -0
  527. package/lib/routes/api/categories.js +15 -0
  528. package/lib/routes/api/comments.d.ts +8 -0
  529. package/lib/routes/api/comments.js +35 -0
  530. package/lib/routes/api/content-model.d.ts +17 -0
  531. package/lib/routes/api/content-model.js +67 -0
  532. package/lib/routes/api/cron.d.ts +6 -0
  533. package/lib/routes/api/cron.js +9 -0
  534. package/lib/routes/api/export.d.ts +5 -0
  535. package/lib/routes/api/export.js +11 -0
  536. package/lib/routes/api/feed.d.ts +5 -0
  537. package/lib/routes/api/feed.js +16 -0
  538. package/lib/routes/api/media.d.ts +8 -0
  539. package/lib/routes/api/media.js +25 -0
  540. package/lib/routes/api/navigation.d.ts +12 -0
  541. package/lib/routes/api/navigation.js +17 -0
  542. package/lib/routes/api/ops.d.ts +9 -0
  543. package/lib/routes/api/ops.js +19 -0
  544. package/lib/routes/api/pages.d.ts +8 -0
  545. package/lib/routes/api/pages.js +21 -0
  546. package/lib/routes/api/passkeys.d.ts +7 -0
  547. package/lib/routes/api/passkeys.js +13 -0
  548. package/lib/routes/api/posts.d.ts +8 -0
  549. package/lib/routes/api/posts.js +39 -0
  550. package/lib/routes/api/profile.d.ts +6 -0
  551. package/lib/routes/api/profile.js +8 -0
  552. package/lib/routes/api/redirects.d.ts +12 -0
  553. package/lib/routes/api/redirects.js +13 -0
  554. package/lib/routes/api/settings.d.ts +8 -0
  555. package/lib/routes/api/settings.js +15 -0
  556. package/lib/routes/api/snippets.d.ts +15 -0
  557. package/lib/routes/api/snippets.js +16 -0
  558. package/lib/routes/api/tags.d.ts +8 -0
  559. package/lib/routes/api/tags.js +14 -0
  560. package/lib/routes/api/tokens.d.ts +7 -0
  561. package/lib/routes/api/tokens.js +15 -0
  562. package/lib/routes/api/two-factor.d.ts +7 -0
  563. package/lib/routes/api/two-factor.js +15 -0
  564. package/lib/routes/api/users.d.ts +8 -0
  565. package/lib/routes/api/users.js +25 -0
  566. package/lib/routes/api/v1.d.ts +12 -0
  567. package/lib/routes/api/v1.js +55 -0
  568. package/lib/routes/api/verification.d.ts +6 -0
  569. package/lib/routes/api/verification.js +11 -0
  570. package/lib/server/index.d.ts +24 -0
  571. package/lib/server/index.js +110 -0
  572. package/lib/types/index.d.ts +298 -0
  573. package/lib/types/index.js +1 -0
  574. package/lib/vite.d.ts +2 -0
  575. package/lib/vite.js +101 -0
  576. package/mail/comment-moderation.html +27 -0
  577. package/mail/comment-moderation.txt +13 -0
  578. package/mail/comment-reply.html +28 -0
  579. package/mail/comment-reply.txt +14 -0
  580. package/mail/invitation.html +25 -0
  581. package/mail/invitation.txt +11 -0
  582. package/mail/member-magic-link.html +23 -0
  583. package/mail/member-magic-link.txt +10 -0
  584. package/mail/newsletter.html +26 -0
  585. package/mail/newsletter.txt +13 -0
  586. package/mail/password-reset.html +26 -0
  587. package/mail/password-reset.txt +10 -0
  588. package/mail/verify-email.html +25 -0
  589. package/mail/verify-email.txt +8 -0
  590. package/package.json +85 -4
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Page-view counts: recording a hit, purging what must not be kept, and the
3
+ * summaries the admin reads.
4
+ *
5
+ * Every function takes an optional `db` so the logic runs against an
6
+ * in-memory database in tests; in the app it is always `getDb()`. The privacy
7
+ * model — what is stored, for how long, and why — is in migration 036 and
8
+ * src/features/analytics/README.md; this file is where it is enforced.
9
+ */
10
+ /** The heartbeat the purge records; the analytics health check reads it. */
11
+ export declare const PURGE_HEARTBEAT = "analytics_purge";
12
+ export interface AnalyticsDb {
13
+ driver?: string;
14
+ get: (sql: string, params?: unknown[]) => any;
15
+ all: (sql: string, params?: unknown[]) => any;
16
+ run: (sql: string, params?: unknown[]) => any;
17
+ }
18
+ /**
19
+ * Distinct paths (and referrer domains) counted per day before the rest are
20
+ * folded into `(other)`.
21
+ *
22
+ * The ingest endpoint is public, so without a cap anyone could add a row per
23
+ * request by inventing paths, and the table would grow without bound. A real
24
+ * blog has nowhere near this many pages read in one day.
25
+ */
26
+ export declare const MAX_PATHS_PER_DAY = 5000;
27
+ export declare const MAX_REFERRERS_PER_DAY = 1000;
28
+ export declare const OTHER = "(other)";
29
+ export declare const DEFAULT_DEDUP_HOURS = 24;
30
+ export interface AnalyticsSettings {
31
+ enabled: boolean;
32
+ dedupHours: number;
33
+ retentionDays: number;
34
+ }
35
+ /** The three analytics settings, with their defaults applied. */
36
+ export declare function analyticsSettings(db?: AnalyticsDb): Promise<AnalyticsSettings>;
37
+ /**
38
+ * The day's salt, creating it if this is the day's first hit.
39
+ *
40
+ * Insert-if-absent then read, so two instances racing on the first hit of the
41
+ * day agree on whichever salt landed first. Random rather than derived from
42
+ * APP_KEY: a derived salt can be derived again after the day is over, and the
43
+ * point of rotating it is that once it is deleted, yesterday's hashes cannot
44
+ * be matched to anyone. (APP_KEY is still mixed into the hash by the caller,
45
+ * so a database leak alone does not hand out today's salt in usable form.)
46
+ */
47
+ export declare function saltFor(day: string, db?: AnalyticsDb): Promise<string>;
48
+ /** Forget cached salts. For tests, and after a purge deletes them. */
49
+ export declare function clearSaltCache(): void;
50
+ export interface Hit {
51
+ /** Already normalised by `normalizeAnalyticsPath`. */
52
+ path: string;
53
+ /** Already reduced by `referrerDomain`, or null. */
54
+ referrer: string | null;
55
+ /** The client address as the rate limiter sees it (IPv6 as its /64). */
56
+ address: string;
57
+ userAgent: string;
58
+ /** Extra key material mixed into every hash: APP_KEY in the app. */
59
+ pepper?: string;
60
+ now?: Date;
61
+ }
62
+ /**
63
+ * Count one page view.
64
+ *
65
+ * Neither the address nor the user agent is written anywhere: they go into a
66
+ * hash with the day's salt, and only the hash is stored, in a table purged
67
+ * once the UTC day is over (sooner, with a shorter dedup window). What is kept is the increment.
68
+ */
69
+ export declare function recordHit(hit: Hit, db?: AnalyticsDb): Promise<{
70
+ newVisitor: boolean;
71
+ path: string;
72
+ }>;
73
+ export interface PurgeResult {
74
+ seen: number;
75
+ salts: number;
76
+ aggregates: number;
77
+ }
78
+ /**
79
+ * Delete what the privacy model says must not be kept.
80
+ *
81
+ * - visitor hashes older than the dedup window;
82
+ * - every salt from before today, which makes any hash that survived
83
+ * unmatchable;
84
+ * - daily counts older than the retention setting, when one is set.
85
+ *
86
+ * Runs from the ingest endpoint and the admin summary (throttled), and from
87
+ * `GET /api/cron/maintenance`, so a site with no traffic still forgets on time.
88
+ */
89
+ export declare function purge(options?: {
90
+ now?: Date;
91
+ dedupHours?: number;
92
+ retentionDays?: number;
93
+ }, db?: AnalyticsDb): Promise<PurgeResult>;
94
+ /** `purge`, at most every ten minutes per instance. Never throws. */
95
+ export declare function purgeOpportunistically(db?: AnalyticsDb): Promise<void>;
96
+ export interface AnalyticsSummary {
97
+ days: number;
98
+ from: string;
99
+ to: string;
100
+ totals: {
101
+ views: number;
102
+ visitors: number;
103
+ };
104
+ series: Array<{
105
+ day: string;
106
+ views: number;
107
+ visitors: number;
108
+ }>;
109
+ top_paths: Array<{
110
+ path: string;
111
+ views: number;
112
+ visitors: number;
113
+ }>;
114
+ top_referrers: Array<{
115
+ domain: string;
116
+ views: number;
117
+ }>;
118
+ }
119
+ /**
120
+ * The admin's view of the last `days` days, today included.
121
+ *
122
+ * `totals.visitors` is the sum of daily uniques: a reader who came on three
123
+ * days counts three times. Uniques across a range would need the hashes the
124
+ * privacy model deletes, and that is the trade — the page says so.
125
+ */
126
+ export declare function summary(options: {
127
+ days: number;
128
+ now?: Date;
129
+ limit?: number;
130
+ }, db?: AnalyticsDb): Promise<AnalyticsSummary>;
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Page-view counts: recording a hit, purging what must not be kept, and the
3
+ * summaries the admin reads.
4
+ *
5
+ * Every function takes an optional `db` so the logic runs against an
6
+ * in-memory database in tests; in the app it is always `getDb()`. The privacy
7
+ * model — what is stored, for how long, and why — is in migration 036 and
8
+ * src/features/analytics/README.md; this file is where it is enforced.
9
+ */
10
+ import { randomBytes } from 'node:crypto';
11
+ import { getDb } from '@basicbenframework/core/db';
12
+ import { utcDay, daysBefore, visitorHash, fillSeries } from "./helpers.js";
13
+ import { recordHeartbeat } from "../../helpers/heartbeat.js";
14
+ /** The heartbeat the purge records; the analytics health check reads it. */
15
+ export const PURGE_HEARTBEAT = 'analytics_purge';
16
+ const conn = async (db) => db ?? (await getDb());
17
+ /**
18
+ * Distinct paths (and referrer domains) counted per day before the rest are
19
+ * folded into `(other)`.
20
+ *
21
+ * The ingest endpoint is public, so without a cap anyone could add a row per
22
+ * request by inventing paths, and the table would grow without bound. A real
23
+ * blog has nowhere near this many pages read in one day.
24
+ */
25
+ export const MAX_PATHS_PER_DAY = 5000;
26
+ export const MAX_REFERRERS_PER_DAY = 1000;
27
+ export const OTHER = '(other)';
28
+ export const DEFAULT_DEDUP_HOURS = 24;
29
+ /** The three analytics settings, with their defaults applied. */
30
+ export async function analyticsSettings(db) {
31
+ const d = await conn(db);
32
+ const rows = (await d.all("SELECT key, value FROM settings WHERE key IN ('analytics_enabled', 'analytics_dedup_hours', 'analytics_retention_days')"));
33
+ const value = (key) => rows.find((row) => row.key === key)?.value ?? null;
34
+ const hours = Number(value('analytics_dedup_hours'));
35
+ const retention = Number(value('analytics_retention_days'));
36
+ return {
37
+ enabled: value('analytics_enabled') !== 'false',
38
+ dedupHours: Number.isInteger(hours) && hours >= 1 && hours <= 24 ? hours : DEFAULT_DEDUP_HOURS,
39
+ retentionDays: Number.isInteger(retention) && retention >= 0 ? retention : 0
40
+ };
41
+ }
42
+ // One salt per day, cached per instance. The cache is an optimisation only:
43
+ // the row is the source of truth, so every instance hashes with the same salt.
44
+ const saltCache = new Map();
45
+ /**
46
+ * The day's salt, creating it if this is the day's first hit.
47
+ *
48
+ * Insert-if-absent then read, so two instances racing on the first hit of the
49
+ * day agree on whichever salt landed first. Random rather than derived from
50
+ * APP_KEY: a derived salt can be derived again after the day is over, and the
51
+ * point of rotating it is that once it is deleted, yesterday's hashes cannot
52
+ * be matched to anyone. (APP_KEY is still mixed into the hash by the caller,
53
+ * so a database leak alone does not hand out today's salt in usable form.)
54
+ */
55
+ export async function saltFor(day, db) {
56
+ const cached = saltCache.get(day);
57
+ if (cached)
58
+ return cached;
59
+ const d = await conn(db);
60
+ await d.run('INSERT INTO analytics_salts (day, salt) VALUES (?, ?) ON CONFLICT(day) DO NOTHING', [day, randomBytes(32).toString('hex')]);
61
+ const row = await d.get('SELECT salt FROM analytics_salts WHERE day = ?', [day]);
62
+ const salt = String(row.salt);
63
+ // Only today's (and at the boundary, yesterday's) salt is ever wanted.
64
+ if (saltCache.size > 4)
65
+ saltCache.clear();
66
+ saltCache.set(day, salt);
67
+ return salt;
68
+ }
69
+ /** Forget cached salts. For tests, and after a purge deletes them. */
70
+ export function clearSaltCache() {
71
+ saltCache.clear();
72
+ }
73
+ /** True the first time this hash is seen; false for a repeat. */
74
+ async function firstSighting(d, hash, day, now) {
75
+ const result = await d.run('INSERT INTO analytics_seen (hash, day, created_at) VALUES (?, ?, ?) ON CONFLICT(hash) DO NOTHING', [hash, day, now]);
76
+ return Number(result?.changes ?? 0) > 0;
77
+ }
78
+ /**
79
+ * Count one page view.
80
+ *
81
+ * Neither the address nor the user agent is written anywhere: they go into a
82
+ * hash with the day's salt, and only the hash is stored, in a table purged
83
+ * once the UTC day is over (sooner, with a shorter dedup window). What is kept is the increment.
84
+ */
85
+ export async function recordHit(hit, db) {
86
+ const d = await conn(db);
87
+ const now = hit.now ?? new Date();
88
+ const day = utcDay(now);
89
+ const salt = (hit.pepper ?? '') + (await saltFor(day, d));
90
+ // Fold an unseen path into (other) once the day's cap is reached.
91
+ let path = hit.path;
92
+ const existing = await d.get('SELECT 1 AS present FROM analytics_daily WHERE day = ? AND path = ?', [day, path]);
93
+ if (!existing) {
94
+ const row = await d.get('SELECT COUNT(*) AS n FROM analytics_daily WHERE day = ?', [day]);
95
+ if (Number(row?.n ?? 0) >= MAX_PATHS_PER_DAY)
96
+ path = OTHER;
97
+ }
98
+ const ms = now.getTime();
99
+ const newVisitor = await firstSighting(d, visitorHash(salt, hit.address, hit.userAgent), day, ms);
100
+ const newOnPath = await firstSighting(d, visitorHash(salt, hit.address, hit.userAgent, path), day, ms);
101
+ await d.run(`INSERT INTO analytics_totals (day, views, visitors) VALUES (?, 1, ?)
102
+ ON CONFLICT(day) DO UPDATE SET views = analytics_totals.views + 1, visitors = analytics_totals.visitors + excluded.visitors`, [day, newVisitor ? 1 : 0]);
103
+ await d.run(`INSERT INTO analytics_daily (day, path, views, visitors) VALUES (?, ?, 1, ?)
104
+ ON CONFLICT(day, path) DO UPDATE SET views = analytics_daily.views + 1, visitors = analytics_daily.visitors + excluded.visitors`, [day, path, newOnPath ? 1 : 0]);
105
+ if (hit.referrer) {
106
+ let domain = hit.referrer;
107
+ const known = await d.get('SELECT 1 AS present FROM analytics_referrers WHERE day = ? AND domain = ?', [day, domain]);
108
+ if (!known) {
109
+ const row = await d.get('SELECT COUNT(*) AS n FROM analytics_referrers WHERE day = ?', [day]);
110
+ if (Number(row?.n ?? 0) >= MAX_REFERRERS_PER_DAY)
111
+ domain = OTHER;
112
+ }
113
+ await d.run(`INSERT INTO analytics_referrers (day, domain, views) VALUES (?, ?, 1)
114
+ ON CONFLICT(day, domain) DO UPDATE SET views = analytics_referrers.views + 1`, [day, domain]);
115
+ }
116
+ return { newVisitor, path };
117
+ }
118
+ /**
119
+ * Delete what the privacy model says must not be kept.
120
+ *
121
+ * - visitor hashes older than the dedup window;
122
+ * - every salt from before today, which makes any hash that survived
123
+ * unmatchable;
124
+ * - daily counts older than the retention setting, when one is set.
125
+ *
126
+ * Runs from the ingest endpoint and the admin summary (throttled), and from
127
+ * `GET /api/cron/maintenance`, so a site with no traffic still forgets on time.
128
+ */
129
+ export async function purge(options = {}, db) {
130
+ const d = await conn(db);
131
+ const now = options.now ?? new Date();
132
+ const settings = options.dedupHours === undefined || options.retentionDays === undefined
133
+ ? await analyticsSettings(d)
134
+ : null;
135
+ const dedupHours = Math.min(24, options.dedupHours ?? settings.dedupHours);
136
+ const retentionDays = options.retentionDays ?? settings.retentionDays;
137
+ const today = utcDay(now);
138
+ const seen = await d.run('DELETE FROM analytics_seen WHERE created_at < ?', [now.getTime() - dedupHours * 3_600_000]);
139
+ // Hashes from an earlier day can never match again — its salt goes in the
140
+ // next statement — so whatever the window, they are only liability now.
141
+ const stale = await d.run('DELETE FROM analytics_seen WHERE day < ?', [today]);
142
+ const salts = await d.run('DELETE FROM analytics_salts WHERE day < ?', [today]);
143
+ clearSaltCache();
144
+ let aggregates = 0;
145
+ if (retentionDays > 0) {
146
+ const cutoff = daysBefore(now, retentionDays);
147
+ for (const table of ['analytics_totals', 'analytics_daily', 'analytics_referrers']) {
148
+ const result = await d.run(`DELETE FROM ${table} WHERE day < ?`, [cutoff]);
149
+ aggregates += Number(result?.changes ?? 0);
150
+ }
151
+ }
152
+ const result = {
153
+ seen: Number(seen?.changes ?? 0) + Number(stale?.changes ?? 0),
154
+ salts: Number(salts?.changes ?? 0),
155
+ aggregates
156
+ };
157
+ await recordHeartbeat(d, PURGE_HEARTBEAT, { ...result }, now);
158
+ return result;
159
+ }
160
+ let lastPurge = 0;
161
+ /** `purge`, at most every ten minutes per instance. Never throws. */
162
+ export async function purgeOpportunistically(db) {
163
+ if (Date.now() - lastPurge < 10 * 60_000)
164
+ return;
165
+ lastPurge = Date.now();
166
+ try {
167
+ await purge({}, db);
168
+ }
169
+ catch (err) {
170
+ console.error('[analytics] purge failed:', err.message);
171
+ }
172
+ }
173
+ /**
174
+ * The admin's view of the last `days` days, today included.
175
+ *
176
+ * `totals.visitors` is the sum of daily uniques: a reader who came on three
177
+ * days counts three times. Uniques across a range would need the hashes the
178
+ * privacy model deletes, and that is the trade — the page says so.
179
+ */
180
+ export async function summary(options, db) {
181
+ const d = await conn(db);
182
+ const now = options.now ?? new Date();
183
+ const days = options.days;
184
+ const limit = options.limit ?? 20;
185
+ const from = daysBefore(now, days - 1);
186
+ const to = utcDay(now);
187
+ const rows = (await d.all('SELECT day, views, visitors FROM analytics_totals WHERE day >= ? AND day <= ? ORDER BY day', [from, to]));
188
+ const series = fillSeries(rows, days, now);
189
+ const topPaths = (await d.all(`SELECT path, SUM(views) AS views, SUM(visitors) AS visitors FROM analytics_daily
190
+ WHERE day >= ? AND day <= ? GROUP BY path ORDER BY SUM(views) DESC, path LIMIT ?`, [from, to, limit]));
191
+ const topReferrers = (await d.all(`SELECT domain, SUM(views) AS views FROM analytics_referrers
192
+ WHERE day >= ? AND day <= ? GROUP BY domain ORDER BY SUM(views) DESC, domain LIMIT ?`, [from, to, limit]));
193
+ return {
194
+ days,
195
+ from,
196
+ to,
197
+ totals: {
198
+ views: series.reduce((sum, day) => sum + day.views, 0),
199
+ visitors: series.reduce((sum, day) => sum + day.visitors, 0)
200
+ },
201
+ series,
202
+ // SUM() comes back as a string on Postgres (bigint) — numbers for JSON.
203
+ top_paths: topPaths.map((row) => ({ path: row.path, views: Number(row.views), visitors: Number(row.visitors) })),
204
+ top_referrers: topReferrers.map((row) => ({ domain: row.domain, views: Number(row.views) }))
205
+ };
206
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Members: readers with an email address and, optionally, a newsletter
3
+ * subscription. See migration 033 for why they are not `users`.
4
+ *
5
+ * Imported (indirectly) by middleware, which the framework loads through
6
+ * Node's own `import()` — so relative imports here carry their extension.
7
+ */
8
+ export type MemberStatus = 'active' | 'unsubscribed';
9
+ export declare const MEMBER_STATUSES: MemberStatus[];
10
+ export type MemberSource = 'signup' | 'admin' | 'import';
11
+ export interface MemberRow {
12
+ id: number;
13
+ email: string;
14
+ name: string | null;
15
+ status: MemberStatus;
16
+ note: string | null;
17
+ labels: string | null;
18
+ source: MemberSource;
19
+ session_version: number;
20
+ email_verified_at: string | null;
21
+ unsubscribed_at: string | null;
22
+ last_seen_at: string | null;
23
+ created_at: string;
24
+ updated_at: string;
25
+ }
26
+ /** What a member is shown about themselves. No session counter, no admin note. */
27
+ export interface MemberProfile {
28
+ id: number;
29
+ email: string;
30
+ name: string | null;
31
+ /** Whether newsletters are mailed to them. */
32
+ newsletter: boolean;
33
+ email_verified: boolean;
34
+ created_at: string;
35
+ }
36
+ export declare function memberProfile(row: MemberRow): MemberProfile;
37
+ /** Labels as stored: trimmed, de-duplicated, comma separated, or null. */
38
+ export declare function normalizeLabels(value: unknown): string | null;
39
+ /** A cheap shape check. Real proof of an address is the magic link. */
40
+ export declare function looksLikeEmail(value: string): boolean;
41
+ export declare const Member: {
42
+ find(id: number): Promise<MemberRow | undefined>;
43
+ findByEmail(email: string): Promise<MemberRow | undefined>;
44
+ create(data: {
45
+ email: string;
46
+ name?: string | null;
47
+ status?: MemberStatus;
48
+ note?: string | null;
49
+ labels?: string | null;
50
+ source?: MemberSource;
51
+ email_verified_at?: string | null;
52
+ }): Promise<MemberRow>;
53
+ /** Write the fields a member or an admin may change. Absent keys are left alone. */
54
+ update(id: number, changes: {
55
+ name?: string | null;
56
+ status?: MemberStatus;
57
+ note?: string | null;
58
+ labels?: string | null;
59
+ email?: string;
60
+ }, { origin }?: {
61
+ origin?: string;
62
+ }): Promise<MemberRow | undefined>;
63
+ /** Following a magic link proves the address and counts as a visit. */
64
+ markVerified(id: number): Promise<void>;
65
+ /**
66
+ * Record a visit, at most once an hour.
67
+ *
68
+ * Every member read would otherwise be a write, on the hottest path the
69
+ * public API has. An hour is fine-grained enough for "last seen".
70
+ */
71
+ touch(row: MemberRow): Promise<void>;
72
+ /** End every session the member holds. */
73
+ revokeSessions(id: number): Promise<void>;
74
+ delete(id: number): Promise<void>;
75
+ /** The admin listing: search over address, name and labels, optionally one status. */
76
+ paginate({ perPage, offset, search, status }: {
77
+ perPage: number;
78
+ offset: number;
79
+ search?: string;
80
+ status?: MemberStatus;
81
+ }): Promise<{
82
+ members: MemberRow[];
83
+ total: number;
84
+ }>;
85
+ /** Totals for the counters above the list. */
86
+ counts(): Promise<{
87
+ total: number;
88
+ active: number;
89
+ unsubscribed: number;
90
+ }>;
91
+ /** Everyone, for the CSV export. Ordered so two exports diff cleanly. */
92
+ all(): Promise<MemberRow[]>;
93
+ };
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Members: readers with an email address and, optionally, a newsletter
3
+ * subscription. See migration 033 for why they are not `users`.
4
+ *
5
+ * Imported (indirectly) by middleware, which the framework loads through
6
+ * Node's own `import()` — so relative imports here carry their extension.
7
+ */
8
+ import { hooks } from '@basicbenframework/core/hooks';
9
+ import { MEMBER_HOOKS } from "./events.js";
10
+ import { getDb, query } from '@basicbenframework/core/db';
11
+ import { normalizeEmail } from "./session.js";
12
+ import { parseStoredTimestamp } from "../../models/visibility.js";
13
+ export const MEMBER_STATUSES = ['active', 'unsubscribed'];
14
+ export function memberProfile(row) {
15
+ return {
16
+ id: row.id,
17
+ email: row.email,
18
+ name: row.name,
19
+ newsletter: row.status === 'active',
20
+ email_verified: Boolean(row.email_verified_at),
21
+ created_at: row.created_at
22
+ };
23
+ }
24
+ /** Labels as stored: trimmed, de-duplicated, comma separated, or null. */
25
+ export function normalizeLabels(value) {
26
+ const list = Array.isArray(value) ? value : String(value ?? '').split(',');
27
+ const labels = [...new Set(list.map(label => String(label).trim()).filter(Boolean).map(label => label.slice(0, 50)))];
28
+ return labels.length ? labels.slice(0, 20).join(', ') : null;
29
+ }
30
+ /** A cheap shape check. Real proof of an address is the magic link. */
31
+ export function looksLikeEmail(value) {
32
+ return value.length <= 254 && /^[^\s@<>,;"]+@[^\s@<>,;"]+\.[^\s@<>,;"]+$/.test(value);
33
+ }
34
+ /** Tell listeners, never letting one fail a member write. `hooks.fire` contains a throwing listener. */
35
+ async function tell(hook, payload) {
36
+ await hooks.fire(hook, payload);
37
+ }
38
+ export const Member = {
39
+ async find(id) {
40
+ const db = await getDb();
41
+ return db.get('SELECT * FROM members WHERE id = ?', [id]);
42
+ },
43
+ async findByEmail(email) {
44
+ const db = await getDb();
45
+ return db.get('SELECT * FROM members WHERE email = ?', [normalizeEmail(email)]);
46
+ },
47
+ async create(data) {
48
+ const now = new Date().toISOString();
49
+ const status = data.status ?? 'active';
50
+ // Through the query builder for RETURNING id on Postgres — see Post.create.
51
+ const result = await (await query('members')).insert({
52
+ email: normalizeEmail(data.email),
53
+ name: data.name ?? null,
54
+ status,
55
+ note: data.note ?? null,
56
+ labels: data.labels ?? null,
57
+ source: data.source ?? 'signup',
58
+ session_version: 0,
59
+ email_verified_at: data.email_verified_at ?? null,
60
+ unsubscribed_at: status === 'unsubscribed' ? now : null,
61
+ created_at: now,
62
+ updated_at: now
63
+ });
64
+ const member = (await this.find(Number(result.lastInsertRowid)));
65
+ await tell(MEMBER_HOOKS.CREATED, { member });
66
+ return member;
67
+ },
68
+ /** Write the fields a member or an admin may change. Absent keys are left alone. */
69
+ async update(id, changes, { origin = 'admin' } = {}) {
70
+ const db = await getDb();
71
+ const existing = await this.find(id);
72
+ if (!existing)
73
+ return undefined;
74
+ const sets = [];
75
+ const params = [];
76
+ const now = new Date().toISOString();
77
+ if (changes.name !== undefined) {
78
+ sets.push('name = ?');
79
+ params.push(changes.name);
80
+ }
81
+ if (changes.note !== undefined) {
82
+ sets.push('note = ?');
83
+ params.push(changes.note);
84
+ }
85
+ if (changes.labels !== undefined) {
86
+ sets.push('labels = ?');
87
+ params.push(changes.labels);
88
+ }
89
+ if (changes.email !== undefined && normalizeEmail(changes.email) !== existing.email) {
90
+ // A changed address has not been proved; nor has any session that was
91
+ // proving the old one, so they end.
92
+ sets.push('email = ?', 'email_verified_at = NULL', 'session_version = session_version + 1');
93
+ params.push(normalizeEmail(changes.email));
94
+ }
95
+ if (changes.status !== undefined && changes.status !== existing.status) {
96
+ sets.push('status = ?', 'unsubscribed_at = ?');
97
+ params.push(changes.status, changes.status === 'unsubscribed' ? now : null);
98
+ }
99
+ if (sets.length) {
100
+ sets.push('updated_at = ?');
101
+ params.push(now);
102
+ await db.run(`UPDATE members SET ${sets.join(', ')} WHERE id = ?`, [...params, id]);
103
+ const member = await this.find(id);
104
+ // Announced only when something a listener could care about differs:
105
+ // re-saving the same values is not news.
106
+ const changed = member && ['email', 'name', 'status', 'note', 'labels', 'email_verified_at']
107
+ .some((key) => (member[key] ?? null) !== (existing[key] ?? null));
108
+ if (member && changed)
109
+ await tell(MEMBER_HOOKS.UPDATED, { member, previous: existing, origin });
110
+ return member;
111
+ }
112
+ return existing;
113
+ },
114
+ /** Following a magic link proves the address and counts as a visit. */
115
+ async markVerified(id) {
116
+ const db = await getDb();
117
+ const now = new Date().toISOString();
118
+ const previous = await this.find(id);
119
+ await db.run('UPDATE members SET email_verified_at = COALESCE(email_verified_at, ?), last_seen_at = ? WHERE id = ?', [now, now, id]);
120
+ // A newly proved address is news to a provider: it may now be sent mail.
121
+ if (previous && !previous.email_verified_at) {
122
+ const member = await this.find(id);
123
+ if (member)
124
+ await tell(MEMBER_HOOKS.UPDATED, { member, previous, origin: 'member' });
125
+ }
126
+ },
127
+ /**
128
+ * Record a visit, at most once an hour.
129
+ *
130
+ * Every member read would otherwise be a write, on the hottest path the
131
+ * public API has. An hour is fine-grained enough for "last seen".
132
+ */
133
+ async touch(row) {
134
+ // Through parseStoredTimestamp: SQLite hands back text, Postgres a Date.
135
+ const last = parseStoredTimestamp(row.last_seen_at);
136
+ if (Date.now() - (Number.isNaN(last) ? 0 : last) < 60 * 60 * 1000)
137
+ return;
138
+ const db = await getDb();
139
+ await db.run('UPDATE members SET last_seen_at = ? WHERE id = ?', [new Date().toISOString(), row.id]);
140
+ },
141
+ /** End every session the member holds. */
142
+ async revokeSessions(id) {
143
+ const db = await getDb();
144
+ await db.run('UPDATE members SET session_version = session_version + 1 WHERE id = ?', [id]);
145
+ },
146
+ async delete(id) {
147
+ const db = await getDb();
148
+ const member = await this.find(id);
149
+ // Queue rows and tokens go with it by cascade on Postgres; SQLite only
150
+ // honours ON DELETE when foreign keys are switched on, so say it here too.
151
+ await db.run('DELETE FROM newsletter_queue WHERE member_id = ? AND status IN (?, ?)', [id, 'pending', 'sending']);
152
+ await db.run('DELETE FROM member_tokens WHERE member_id = ?', [id]);
153
+ await db.run('DELETE FROM members WHERE id = ?', [id]);
154
+ if (member)
155
+ await tell(MEMBER_HOOKS.DELETED, { member });
156
+ },
157
+ /** The admin listing: search over address, name and labels, optionally one status. */
158
+ async paginate({ perPage, offset, search, status }) {
159
+ const db = await getDb();
160
+ const where = [];
161
+ const params = [];
162
+ if (status) {
163
+ where.push('status = ?');
164
+ params.push(status);
165
+ }
166
+ if (search) {
167
+ // Lowered on both sides for Postgres, as Post.paginate does, and `%`/`_`
168
+ // in the search are literal.
169
+ const needle = `%${search.toLowerCase().replace(/[\\%_]/g, (c) => '\\' + c)}%`;
170
+ where.push("(LOWER(email) LIKE ? ESCAPE '\\' OR LOWER(COALESCE(name, '')) LIKE ? ESCAPE '\\' OR LOWER(COALESCE(labels, '')) LIKE ? ESCAPE '\\')");
171
+ params.push(needle, needle, needle);
172
+ }
173
+ const clause = where.length ? `WHERE ${where.join(' AND ')}` : '';
174
+ const members = (await db.all(`SELECT * FROM members ${clause} ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?`, [...params, perPage, offset]));
175
+ const counted = await db.get(`SELECT COUNT(*) AS total FROM members ${clause}`, params);
176
+ return { members, total: Number(counted?.total) || 0 };
177
+ },
178
+ /** Totals for the counters above the list. */
179
+ async counts() {
180
+ const db = await getDb();
181
+ const rows = (await db.all('SELECT status, COUNT(*) AS total FROM members GROUP BY status'));
182
+ const of = (status) => Number(rows.find(row => row.status === status)?.total) || 0;
183
+ return {
184
+ total: rows.reduce((sum, row) => sum + (Number(row.total) || 0), 0),
185
+ active: of('active'),
186
+ unsubscribed: of('unsubscribed')
187
+ };
188
+ },
189
+ /** Everyone, for the CSV export. Ordered so two exports diff cleanly. */
190
+ async all() {
191
+ const db = await getDb();
192
+ return db.all('SELECT * FROM members ORDER BY id ASC');
193
+ }
194
+ };
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Members and newsletters, from the admin.
3
+ *
4
+ * Member management is behind `user.manage` — only the admin role holds it —
5
+ * because a member list is a list of other people's email addresses: who may
6
+ * read it, export it or import into it is the same question as who may manage
7
+ * accounts. Newsletter status and test sends are per post, behind the post's
8
+ * own edit rule (see the route file).
9
+ */
10
+ import type { Request, Response } from '../../types/index.ts';
11
+ /** Rows one import request may carry. Sequential inserts on a remote database are not free. */
12
+ export declare const MAX_IMPORT_ROWS = 5000;
13
+ export declare const MemberAdminController: {
14
+ /** `GET /api/members?search=&status=&page=` — a page, and the counts above it. */
15
+ index(req: Request, res: Response): Promise<void>;
16
+ /** `POST /api/members` — add one by hand. No mail is sent; they sign in when they choose. */
17
+ store(req: Request, res: Response): Promise<void>;
18
+ /** `PUT /api/members/:id`. */
19
+ update(req: Request, res: Response): Promise<void>;
20
+ /** `DELETE /api/members/:id` — gone, with their sessions and any mail not yet sent to them. */
21
+ destroy(req: Request, res: Response): Promise<void>;
22
+ /**
23
+ * `POST /api/members/import` — `{ csv: "<text>" }`.
24
+ *
25
+ * A header row naming the columns is required, with at least `email`;
26
+ * `name`, `note`, `labels` and `subscribed` (yes/no, true/false) are read if
27
+ * present, in any order, and anything else is ignored. An address that is
28
+ * already a member is skipped, not overwritten: an import is for adding
29
+ * people, and silently re-subscribing someone who unsubscribed would be the
30
+ * worst thing it could do.
31
+ *
32
+ * The CSV travels as a JSON string rather than a multipart upload: the body
33
+ * parser already handles JSON, and a member list fits comfortably in its
34
+ * 1 MB limit. Larger lists go in several requests.
35
+ */
36
+ import(req: Request, res: Response): Promise<void>;
37
+ /**
38
+ * `GET /api/members/export` — every member, as CSV.
39
+ *
40
+ * The same columns the import reads, so an export can be imported
41
+ * elsewhere. Cells are defused against spreadsheet formulas (csv.ts).
42
+ */
43
+ export(_req: Request, res: Response): Promise<void>;
44
+ /** `GET /api/newsletters` — recent sends, newest first, for the Members page. */
45
+ sends(_req: Request, res: Response): Promise<void>;
46
+ /**
47
+ * `GET /api/posts/:id/newsletter` — has this post been mailed, and how far along.
48
+ *
49
+ * Also nudges the queue: an editor watching a send's progress is traffic,
50
+ * and on a serverless host without a cron it is what moves the send along.
51
+ */
52
+ status(req: Request, res: Response): Promise<void>;
53
+ /**
54
+ * `POST /api/posts/:id/newsletter/test` — mail it to yourself, as members will see it.
55
+ *
56
+ * To the signed-in account's own address and nowhere else: a test send that
57
+ * took a recipient would be a way to mail anyone anything from the site.
58
+ */
59
+ test(req: Request, res: Response): Promise<void>;
60
+ };