@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
@@ -0,0 +1,124 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { D1NotificationRepository } from './d1-notification.repository'
3
+ import { FixedClock } from './fixed-clock'
4
+ import { SequentialIdGenerator } from './sequential-id-generator'
5
+
6
+ const clock = new FixedClock(1700000000_000)
7
+ const makeIdGen = () => new SequentialIdGenerator()
8
+
9
+ function makeMockDb(opts: { firstResult?: unknown; allResults?: unknown[] } = {}) {
10
+ const { firstResult = null, allResults = [] } = opts
11
+ const runMock = vi.fn().mockResolvedValue({ success: true })
12
+ const firstMock = vi.fn().mockResolvedValue(firstResult)
13
+ const allMock = vi.fn().mockResolvedValue({ results: allResults })
14
+ const bindMock = vi.fn(() => ({ first: firstMock, all: allMock, run: runMock }))
15
+ const prepareMock = vi.fn(() => ({
16
+ bind: bindMock,
17
+ first: firstMock,
18
+ all: allMock,
19
+ run: runMock,
20
+ }))
21
+ return { db: { prepare: prepareMock } as any, prepareMock, bindMock, runMock, firstMock, allMock }
22
+ }
23
+
24
+ describe('D1NotificationRepository', () => {
25
+ describe('list', () => {
26
+ it('maps rows to NotificationRecord with isRead boolean', async () => {
27
+ const { db } = makeMockDb({
28
+ allResults: [
29
+ {
30
+ id: 'n-1',
31
+ title: 'T',
32
+ message: 'M',
33
+ type: 'success',
34
+ is_read: 0,
35
+ created_at: 100,
36
+ },
37
+ {
38
+ id: 'n-2',
39
+ title: 'T2',
40
+ message: 'M2',
41
+ type: 'info',
42
+ is_read: 1,
43
+ created_at: 99,
44
+ },
45
+ ],
46
+ })
47
+ const records = await new D1NotificationRepository(db, clock, makeIdGen()).list(10)
48
+ expect(records).toEqual([
49
+ { id: 'n-1', title: 'T', message: 'M', type: 'success', isRead: false, createdAt: 100 },
50
+ { id: 'n-2', title: 'T2', message: 'M2', type: 'info', isRead: true, createdAt: 99 },
51
+ ])
52
+ })
53
+
54
+ it('orders by created_at DESC with LIMIT bound', async () => {
55
+ const { db, prepareMock, bindMock } = makeMockDb()
56
+ await new D1NotificationRepository(db, clock, makeIdGen()).list(25)
57
+ expect(prepareMock.mock.calls[0][0]).toMatch(/ORDER BY created_at DESC/)
58
+ expect(bindMock).toHaveBeenCalledWith(25)
59
+ })
60
+ })
61
+
62
+ describe('stats', () => {
63
+ it('returns aggregate counters mapped to camelCase', async () => {
64
+ const { db } = makeMockDb({
65
+ firstResult: { total_count: 7, latest_created_at: 1234, read_count: 3 },
66
+ })
67
+ const stats = await new D1NotificationRepository(db, clock, makeIdGen()).stats()
68
+ expect(stats).toEqual({ totalCount: 7, latestCreatedAt: 1234, readCount: 3 })
69
+ })
70
+
71
+ it('returns zeros when the table is empty', async () => {
72
+ const { db } = makeMockDb({
73
+ firstResult: { total_count: 0, latest_created_at: null, read_count: null },
74
+ })
75
+ const stats = await new D1NotificationRepository(db, clock, makeIdGen()).stats()
76
+ expect(stats).toEqual({ totalCount: 0, latestCreatedAt: 0, readCount: 0 })
77
+ })
78
+ })
79
+
80
+ describe('create', () => {
81
+ it('inserts a new notification and returns the generated id', async () => {
82
+ const { db, prepareMock, bindMock } = makeMockDb()
83
+ const id = await new D1NotificationRepository(db, clock, makeIdGen()).create({
84
+ title: 'Hello',
85
+ message: 'World',
86
+ type: 'info',
87
+ })
88
+ expect(typeof id).toBe('string')
89
+ expect(id.length).toBeGreaterThan(0)
90
+ expect(prepareMock.mock.calls[0][0]).toMatch(/INSERT INTO notifications/)
91
+ expect(bindMock).toHaveBeenCalledWith(id, 'Hello', 'World', 'info')
92
+ })
93
+ })
94
+
95
+ describe('markRead / markUnread / delete / markAllRead', () => {
96
+ it('markRead binds the given id', async () => {
97
+ const { db, prepareMock, bindMock } = makeMockDb()
98
+ await new D1NotificationRepository(db, clock, makeIdGen()).markRead('n-1')
99
+ expect(prepareMock.mock.calls[0][0]).toMatch(/UPDATE notifications SET is_read = 1 WHERE id = \?/)
100
+ expect(bindMock).toHaveBeenCalledWith('n-1')
101
+ })
102
+
103
+ it('markUnread binds the given id', async () => {
104
+ const { db, prepareMock, bindMock } = makeMockDb()
105
+ await new D1NotificationRepository(db, clock, makeIdGen()).markUnread('n-2')
106
+ expect(prepareMock.mock.calls[0][0]).toMatch(/UPDATE notifications SET is_read = 0 WHERE id = \?/)
107
+ expect(bindMock).toHaveBeenCalledWith('n-2')
108
+ })
109
+
110
+ it('delete binds the given id', async () => {
111
+ const { db, prepareMock, bindMock } = makeMockDb()
112
+ await new D1NotificationRepository(db, clock, makeIdGen()).delete('n-3')
113
+ expect(prepareMock.mock.calls[0][0]).toMatch(/DELETE FROM notifications WHERE id = \?/)
114
+ expect(bindMock).toHaveBeenCalledWith('n-3')
115
+ })
116
+
117
+ it('markAllRead runs without bindings', async () => {
118
+ const { db, prepareMock, runMock } = makeMockDb()
119
+ await new D1NotificationRepository(db, clock, makeIdGen()).markAllRead()
120
+ expect(prepareMock.mock.calls[0][0]).toMatch(/^UPDATE notifications SET is_read = 1$/)
121
+ expect(runMock).toHaveBeenCalled()
122
+ })
123
+ })
124
+ })
@@ -0,0 +1,114 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import type {
3
+ INotificationRepository,
4
+ NotificationRecord,
5
+ NotificationStats,
6
+ NotificationType,
7
+ IClock,
8
+ IIdGenerator,
9
+ } from '@beechcms/core'
10
+
11
+ interface NotificationRow {
12
+ id: string
13
+ title: string
14
+ message: string
15
+ type: string
16
+ is_read: number
17
+ created_at: number
18
+ }
19
+
20
+ interface NotificationStatsRow {
21
+ total_count: number | null
22
+ latest_created_at: number | null
23
+ read_count: number | null
24
+ }
25
+
26
+ /**
27
+ * D1-backed implementation of {@link INotificationRepository}.
28
+ */
29
+ export class D1NotificationRepository implements INotificationRepository {
30
+ constructor(
31
+ private readonly database: D1Database,
32
+ private readonly clock: IClock,
33
+ private readonly idGenerator: IIdGenerator,
34
+ ) {}
35
+
36
+ async list(limit: number): Promise<NotificationRecord[]> {
37
+ const queryResult = await this.database
38
+ .prepare(
39
+ `SELECT id, title, message, type, is_read, created_at
40
+ FROM notifications
41
+ ORDER BY created_at DESC
42
+ LIMIT ?`
43
+ )
44
+ .bind(limit)
45
+ .all<NotificationRow>()
46
+
47
+ return (queryResult.results ?? []).map(mapRowToRecord)
48
+ }
49
+
50
+ async stats(): Promise<NotificationStats> {
51
+ const statsRow = await this.database
52
+ .prepare(
53
+ `SELECT COUNT(*) as total_count,
54
+ MAX(created_at) as latest_created_at,
55
+ SUM(is_read) as read_count
56
+ FROM notifications`
57
+ )
58
+ .first<NotificationStatsRow>()
59
+
60
+ return {
61
+ totalCount: statsRow?.total_count ?? 0,
62
+ latestCreatedAt: statsRow?.latest_created_at ?? 0,
63
+ readCount: statsRow?.read_count ?? 0,
64
+ }
65
+ }
66
+
67
+ async create(record: Omit<NotificationRecord, 'id' | 'createdAt' | 'isRead'>): Promise<string> {
68
+ const generatedId = this.idGenerator.uuid()
69
+ await this.database
70
+ .prepare(
71
+ `INSERT INTO notifications (id, title, message, type)
72
+ VALUES (?, ?, ?, ?)`
73
+ )
74
+ .bind(generatedId, record.title, record.message, record.type)
75
+ .run()
76
+ return generatedId
77
+ }
78
+
79
+ async markRead(notificationId: string): Promise<void> {
80
+ await this.database
81
+ .prepare('UPDATE notifications SET is_read = 1 WHERE id = ?')
82
+ .bind(notificationId)
83
+ .run()
84
+ }
85
+
86
+ async markUnread(notificationId: string): Promise<void> {
87
+ await this.database
88
+ .prepare('UPDATE notifications SET is_read = 0 WHERE id = ?')
89
+ .bind(notificationId)
90
+ .run()
91
+ }
92
+
93
+ async markAllRead(): Promise<void> {
94
+ await this.database.prepare('UPDATE notifications SET is_read = 1').run()
95
+ }
96
+
97
+ async delete(notificationId: string): Promise<void> {
98
+ await this.database
99
+ .prepare('DELETE FROM notifications WHERE id = ?')
100
+ .bind(notificationId)
101
+ .run()
102
+ }
103
+ }
104
+
105
+ function mapRowToRecord(row: NotificationRow): NotificationRecord {
106
+ return {
107
+ id: row.id,
108
+ title: row.title,
109
+ message: row.message,
110
+ type: row.type as NotificationType,
111
+ isRead: row.is_read === 1,
112
+ createdAt: row.created_at,
113
+ }
114
+ }
@@ -0,0 +1,77 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { D1PasswordResetTokenRepository } from './d1-password-reset-token.repository'
3
+
4
+ const NOW = Math.floor(Date.now() / 1000)
5
+ const fixedIdGen = { uuid: () => 'prt-1' }
6
+
7
+ function makeMockDb(opts: { firstResult?: unknown; runChanges?: number } = {}) {
8
+ const { firstResult = null, runChanges = 1 } = opts
9
+ const runMock = vi.fn().mockResolvedValue({ success: true, meta: { changes: runChanges } })
10
+ const firstMock = vi.fn().mockResolvedValue(firstResult)
11
+ const bindMock = vi.fn(() => ({ first: firstMock, run: runMock }))
12
+ const prepareMock = vi.fn(() => ({ bind: bindMock }))
13
+ return { db: { prepare: prepareMock } as any, prepareMock, bindMock, runMock }
14
+ }
15
+
16
+ describe('D1PasswordResetTokenRepository', () => {
17
+ describe('create', () => {
18
+ it('calls INSERT INTO password_reset_tokens', async () => {
19
+ const { db, prepareMock } = makeMockDb()
20
+ await new D1PasswordResetTokenRepository(db, fixedIdGen).create({
21
+ userId: 'u1', tokenHash: 'h', expiresAt: NOW + 1800,
22
+ })
23
+ expect(prepareMock).toHaveBeenCalledWith(expect.stringContaining('INSERT INTO password_reset_tokens'))
24
+ })
25
+
26
+ it('binds id, userId, tokenHash, and expiresAt in the correct order', async () => {
27
+ const { db, bindMock } = makeMockDb()
28
+ await new D1PasswordResetTokenRepository(db, fixedIdGen).create({
29
+ userId: 'u1', tokenHash: 'h', expiresAt: NOW + 1800,
30
+ })
31
+ expect(bindMock).toHaveBeenCalledWith('prt-1', 'u1', 'h', NOW + 1800)
32
+ })
33
+ })
34
+
35
+ describe('findValidByHashWithEmail', () => {
36
+ it('returns a ValidatedResetToken with the userId and email from the JOIN', async () => {
37
+ const row = { id: 'prt-1', user_id: 'u1', email: 'user@test.com' }
38
+ const { db } = makeMockDb({ firstResult: row })
39
+ const result = await new D1PasswordResetTokenRepository(db, fixedIdGen).findValidByHashWithEmail('h', NOW)
40
+ expect(result).toEqual({ id: 'prt-1', userId: 'u1', email: 'user@test.com' })
41
+ })
42
+
43
+ it('returns null when the token is not found, expired, or already used', async () => {
44
+ const { db } = makeMockDb({ firstResult: null })
45
+ expect(await new D1PasswordResetTokenRepository(db, fixedIdGen).findValidByHashWithEmail('bad-hash', NOW)).toBeNull()
46
+ })
47
+
48
+ it('passes tokenHash and nowTimestamp as bound values', async () => {
49
+ const { db, bindMock } = makeMockDb()
50
+ await new D1PasswordResetTokenRepository(db, fixedIdGen).findValidByHashWithEmail('my-hash', NOW)
51
+ expect(bindMock).toHaveBeenCalledWith('my-hash', NOW)
52
+ })
53
+ })
54
+
55
+ describe('markUsed', () => {
56
+ it('calls UPDATE password_reset_tokens SET used_at', async () => {
57
+ const { db, prepareMock } = makeMockDb()
58
+ await new D1PasswordResetTokenRepository(db, fixedIdGen).markUsed('prt-1', NOW)
59
+ expect(prepareMock).toHaveBeenCalledWith(expect.stringContaining('used_at'))
60
+ })
61
+
62
+ it('binds nowTimestamp and tokenId in the correct order', async () => {
63
+ const { db, bindMock } = makeMockDb()
64
+ await new D1PasswordResetTokenRepository(db, fixedIdGen).markUsed('prt-1', NOW)
65
+ expect(bindMock).toHaveBeenCalledWith(NOW, 'prt-1')
66
+ })
67
+ })
68
+
69
+ describe('invalidatePending', () => {
70
+ it('calls UPDATE password_reset_tokens and includes the userId in the bound values', async () => {
71
+ const { db, prepareMock, bindMock } = makeMockDb()
72
+ await new D1PasswordResetTokenRepository(db, fixedIdGen).invalidatePending('u1', NOW)
73
+ expect(prepareMock).toHaveBeenCalledWith(expect.stringContaining('UPDATE password_reset_tokens'))
74
+ expect((bindMock.mock.calls[0] as unknown[]).includes('u1')).toBe(true)
75
+ })
76
+ })
77
+ })
@@ -0,0 +1,52 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import type { IPasswordResetTokenRepository, NewPasswordResetToken, ValidatedResetToken, IIdGenerator } from '@beechcms/core'
3
+
4
+ type ValidatedResetTokenRow = {
5
+ id: string
6
+ user_id: string
7
+ email: string
8
+ }
9
+
10
+ export class D1PasswordResetTokenRepository implements IPasswordResetTokenRepository {
11
+ constructor(
12
+ private readonly db: D1Database,
13
+ private readonly idGenerator: IIdGenerator,
14
+ ) {}
15
+
16
+ async invalidatePending(userId: string, nowTimestamp: number): Promise<void> {
17
+ await this.db
18
+ .prepare('UPDATE password_reset_tokens SET used_at = ? WHERE user_id = ? AND used_at IS NULL')
19
+ .bind(nowTimestamp, userId)
20
+ .run()
21
+ }
22
+
23
+ async create(record: NewPasswordResetToken): Promise<void> {
24
+ const generatedId = this.idGenerator.uuid()
25
+ await this.db
26
+ .prepare('INSERT INTO password_reset_tokens (id, user_id, token_hash, expires_at) VALUES (?, ?, ?, ?)')
27
+ .bind(generatedId, record.userId, record.tokenHash, record.expiresAt)
28
+ .run()
29
+ }
30
+
31
+ async findValidByHashWithEmail(tokenHash: string, nowTimestamp: number): Promise<ValidatedResetToken | null> {
32
+ const row = await this.db
33
+ .prepare(
34
+ `SELECT prt.id, prt.user_id, u.email
35
+ FROM password_reset_tokens prt
36
+ JOIN users u ON u.id = prt.user_id
37
+ WHERE prt.token_hash = ? AND prt.expires_at > ? AND prt.used_at IS NULL`
38
+ )
39
+ .bind(tokenHash, nowTimestamp)
40
+ .first<ValidatedResetTokenRow>()
41
+
42
+ if (!row) return null
43
+ return { id: row.id, userId: row.user_id, email: row.email }
44
+ }
45
+
46
+ async markUsed(tokenId: string, nowTimestamp: number): Promise<void> {
47
+ await this.db
48
+ .prepare('UPDATE password_reset_tokens SET used_at = ? WHERE id = ?')
49
+ .bind(nowTimestamp, tokenId)
50
+ .run()
51
+ }
52
+ }
@@ -0,0 +1,83 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import type { Seed } from '@beechcms/core'
3
+ import { D1SearchRepository } from './d1-search.repository'
4
+
5
+ function makeMockDb(allResults: unknown[] = [], firstResult: unknown = null) {
6
+ const allMock = vi.fn().mockResolvedValue({ results: allResults })
7
+ const firstMock = vi.fn().mockResolvedValue(firstResult)
8
+ const bindMock = vi.fn(() => ({ all: allMock, first: firstMock }))
9
+ const prepareMock = vi.fn(() => ({ bind: bindMock }))
10
+ return { db: { prepare: prepareMock } as any, prepareMock, bindMock, allMock, firstMock }
11
+ }
12
+
13
+ const seeds: Seed[] = [
14
+ {
15
+ slug: 'posts',
16
+ label: 'Post',
17
+ displayNameAlias: 'title',
18
+ branches: [
19
+ { id: 'br_01', alias: 'title', type: 'text', label: 'Title' },
20
+ { id: 'br_02', alias: 'body', type: 'richtext', label: 'Body' },
21
+ ],
22
+ },
23
+ ]
24
+
25
+ describe('D1SearchRepository', () => {
26
+ it('maps FtsRow to camelCase SearchResultRow', async () => {
27
+ const ftsRow = {
28
+ entry_id: 'e1',
29
+ schema_slug: 'posts',
30
+ slug: 'hello',
31
+ status: 'published',
32
+ title: 'Hello',
33
+ excerpt: '<mark>Hi</mark>',
34
+ rank: -3.2,
35
+ }
36
+ const { db } = makeMockDb([ftsRow])
37
+ const result = await new D1SearchRepository(db).search(
38
+ { queryText: 'hello world', schemaSlug: null, statusFilter: null, limit: 10, cursor: null },
39
+ seeds,
40
+ )
41
+ expect(result).toEqual([
42
+ {
43
+ entryId: 'e1',
44
+ schemaSlug: 'posts',
45
+ slug: 'hello',
46
+ status: 'published',
47
+ title: 'Hello',
48
+ excerpt: '<mark>Hi</mark>',
49
+ rank: -3.2,
50
+ },
51
+ ])
52
+ })
53
+
54
+ it('returns [] on EMPTY_QUERY (single-character terms)', async () => {
55
+ const { db, prepareMock } = makeMockDb()
56
+ const result = await new D1SearchRepository(db).search(
57
+ { queryText: 'a', schemaSlug: null, statusFilter: null, limit: 10, cursor: null },
58
+ seeds,
59
+ )
60
+ expect(result).toEqual([])
61
+ expect(prepareMock).not.toHaveBeenCalled()
62
+ })
63
+
64
+ it('count returns { total: 0 } on EMPTY_QUERY', async () => {
65
+ const { db } = makeMockDb()
66
+ const result = await new D1SearchRepository(db).count(
67
+ { queryText: 'a', schemaSlug: null, statusFilter: null },
68
+ seeds,
69
+ )
70
+ expect(result).toEqual({ total: 0 })
71
+ })
72
+
73
+ it('count returns total from countSql', async () => {
74
+ const { db, prepareMock } = makeMockDb([], { total: 17 })
75
+ const result = await new D1SearchRepository(db).count(
76
+ { queryText: 'hello', schemaSlug: null, statusFilter: null },
77
+ seeds,
78
+ )
79
+ expect(result).toEqual({ total: 17 })
80
+ const sql = prepareMock.mock.calls[0]![0] as string
81
+ expect(sql).toMatch(/SUM\(c\)/)
82
+ })
83
+ })
@@ -0,0 +1,84 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import type {
3
+ Seed,
4
+ ISearchRepository,
5
+ SearchQueryOptions,
6
+ SearchResultRow,
7
+ SearchCountResult,
8
+ } from '@beechcms/core'
9
+ import { buildFtsQuery, type FtsRow } from '../search-utils'
10
+
11
+ const EMPTY_QUERY_ERROR = 'EMPTY_QUERY'
12
+
13
+ /**
14
+ * D1-backed implementation of {@link ISearchRepository}.
15
+ *
16
+ * Delegates SQL composition to the pure `buildFtsQuery` helper to keep this
17
+ * class focused on D1 wiring. Returns raw rows; the route handler is
18
+ * responsible for mapping them via `mapFtsRow`.
19
+ */
20
+ export class D1SearchRepository implements ISearchRepository {
21
+ constructor(private readonly database: D1Database) {}
22
+
23
+ async search(options: SearchQueryOptions, seeds: Seed[]): Promise<SearchResultRow[]> {
24
+ let queryParts
25
+ try {
26
+ queryParts = buildFtsQuery(
27
+ {
28
+ q: options.queryText,
29
+ schemaSlug: options.schemaSlug,
30
+ status: options.statusFilter,
31
+ limit: options.limit,
32
+ cursor: options.cursor,
33
+ },
34
+ seeds,
35
+ )
36
+ } catch (error) {
37
+ if (error instanceof Error && error.message === EMPTY_QUERY_ERROR) return []
38
+ throw error
39
+ }
40
+
41
+ const result = await this.database.prepare(queryParts.sql).bind(...queryParts.binds).all<FtsRow>()
42
+ return (result.results ?? []).map(mapFtsRowToResultRow)
43
+ }
44
+
45
+ async count(
46
+ options: Omit<SearchQueryOptions, 'limit' | 'cursor'>,
47
+ seeds: Seed[],
48
+ ): Promise<SearchCountResult> {
49
+ let queryParts
50
+ try {
51
+ queryParts = buildFtsQuery(
52
+ {
53
+ q: options.queryText,
54
+ schemaSlug: options.schemaSlug,
55
+ status: options.statusFilter,
56
+ limit: 0,
57
+ cursor: null,
58
+ },
59
+ seeds,
60
+ )
61
+ } catch (error) {
62
+ if (error instanceof Error && error.message === EMPTY_QUERY_ERROR) return { total: 0 }
63
+ throw error
64
+ }
65
+
66
+ const row = await this.database
67
+ .prepare(queryParts.countSql)
68
+ .bind(...queryParts.countBinds)
69
+ .first<{ total: number }>()
70
+ return { total: row?.total ?? 0 }
71
+ }
72
+ }
73
+
74
+ function mapFtsRowToResultRow(row: FtsRow): SearchResultRow {
75
+ return {
76
+ entryId: row.entry_id,
77
+ schemaSlug: row.schema_slug,
78
+ slug: row.slug,
79
+ status: row.status,
80
+ title: row.title,
81
+ excerpt: row.excerpt,
82
+ rank: row.rank,
83
+ }
84
+ }
@@ -0,0 +1,121 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { D1SessionRepository } from './d1-session.repository'
3
+ import { FixedClock } from './fixed-clock'
4
+
5
+ const FIXED_NOW_MS = 1700000000_000
6
+ const NOW = Math.floor(FIXED_NOW_MS / 1000)
7
+ const FUTURE = NOW + 7 * 24 * 3600
8
+ const clock = new FixedClock(FIXED_NOW_MS)
9
+
10
+ function makeMockDb(opts: {
11
+ firstResult?: unknown
12
+ runChanges?: number
13
+ allResults?: unknown[]
14
+ } = {}) {
15
+ const { firstResult = null, runChanges = 1, allResults = [] } = opts
16
+ const runMock = vi.fn().mockResolvedValue({ success: true, meta: { changes: runChanges } })
17
+ const firstMock = vi.fn().mockResolvedValue(firstResult)
18
+ const allMock = vi.fn().mockResolvedValue({ results: allResults })
19
+ const bindMock = vi.fn(() => ({ first: firstMock, all: allMock, run: runMock }))
20
+ const prepareMock = vi.fn(() => ({ bind: bindMock }))
21
+ return { db: { prepare: prepareMock } as any, prepareMock, bindMock, runMock, firstMock, allMock }
22
+ }
23
+
24
+ describe('D1SessionRepository', () => {
25
+ describe('saveRefreshToken', () => {
26
+ it('calls INSERT INTO refresh_tokens with the correct bound values', async () => {
27
+ const { db, prepareMock, bindMock } = makeMockDb()
28
+ await new D1SessionRepository(db, clock).saveRefreshToken({
29
+ id: 'rt-1', userId: 'u1', tokenHash: 'h', expiresAt: FUTURE,
30
+ })
31
+ expect(prepareMock).toHaveBeenCalledWith(expect.stringContaining('INSERT INTO refresh_tokens'))
32
+ expect(bindMock).toHaveBeenCalledWith('rt-1', 'u1', 'h', FUTURE, NOW)
33
+ })
34
+ })
35
+
36
+ describe('findActiveByHash', () => {
37
+ it('returns a RefreshTokenRecord with camelCase keys mapped from the snake_case row', async () => {
38
+ const row = {
39
+ id: 'rt-1', user_id: 'u1', token_hash: 'h',
40
+ expires_at: FUTURE, created_at: NOW, revoked_at: null,
41
+ }
42
+ const { db } = makeMockDb({ firstResult: row })
43
+ const result = await new D1SessionRepository(db, clock).findActiveByHash('h', NOW)
44
+ expect(result).toEqual({
45
+ id: 'rt-1', userId: 'u1', tokenHash: 'h',
46
+ expiresAt: FUTURE, createdAt: NOW, revokedAt: null,
47
+ })
48
+ })
49
+
50
+ it('returns null when no active token is found', async () => {
51
+ const { db } = makeMockDb({ firstResult: null })
52
+ expect(await new D1SessionRepository(db, clock).findActiveByHash('missing', NOW)).toBeNull()
53
+ })
54
+
55
+ it('passes tokenHash and nowTimestamp as bound values', async () => {
56
+ const { db, bindMock } = makeMockDb()
57
+ await new D1SessionRepository(db, clock).findActiveByHash('my-hash', NOW)
58
+ expect(bindMock).toHaveBeenCalledWith('my-hash', NOW)
59
+ })
60
+ })
61
+
62
+ describe('revokeByHash', () => {
63
+ it('returns true when one row is updated (changes = 1)', async () => {
64
+ const { db } = makeMockDb({ runChanges: 1 })
65
+ expect(await new D1SessionRepository(db, clock).revokeByHash('h', NOW)).toBe(true)
66
+ })
67
+
68
+ it('returns false when no row is updated (token already revoked or not found)', async () => {
69
+ const { db } = makeMockDb({ runChanges: 0 })
70
+ expect(await new D1SessionRepository(db, clock).revokeByHash('h', NOW)).toBe(false)
71
+ })
72
+ })
73
+
74
+ describe('revokeAllForUser', () => {
75
+ it('calls UPDATE refresh_tokens and includes the userId in the bound values', async () => {
76
+ const { db, prepareMock, bindMock } = makeMockDb()
77
+ await new D1SessionRepository(db, clock).revokeAllForUser('u1', NOW)
78
+ expect(prepareMock).toHaveBeenCalledWith(expect.stringContaining('UPDATE refresh_tokens'))
79
+ expect((bindMock.mock.calls[0] as unknown[]).includes('u1')).toBe(true)
80
+ })
81
+ })
82
+
83
+ describe('listActiveForUser', () => {
84
+ it('returns mapped ActiveSessionSummary objects in the original order', async () => {
85
+ const rows = [
86
+ { id: 's1', created_at: NOW - 100, expires_at: FUTURE },
87
+ { id: 's2', created_at: NOW - 200, expires_at: FUTURE },
88
+ ]
89
+ const { db } = makeMockDb({ allResults: rows })
90
+ const sessions = await new D1SessionRepository(db, clock).listActiveForUser('u1', NOW, 20)
91
+ expect(sessions).toHaveLength(2)
92
+ expect(sessions[0]).toEqual({ id: 's1', createdAt: NOW - 100, expiresAt: FUTURE })
93
+ expect(sessions[1]).toEqual({ id: 's2', createdAt: NOW - 200, expiresAt: FUTURE })
94
+ })
95
+
96
+ it('returns an empty array when no active sessions exist', async () => {
97
+ const { db } = makeMockDb({ allResults: [] })
98
+ expect(await new D1SessionRepository(db, clock).listActiveForUser('u1', NOW, 20)).toEqual([])
99
+ })
100
+ })
101
+
102
+ describe('revokeById', () => {
103
+ it('returns true when the session is revoked (changes = 1)', async () => {
104
+ const { db } = makeMockDb({ runChanges: 1 })
105
+ expect(await new D1SessionRepository(db, clock).revokeById('s1', 'u1', NOW)).toBe(true)
106
+ })
107
+
108
+ it('returns false when the session is not found or belongs to another user (changes = 0)', async () => {
109
+ const { db } = makeMockDb({ runChanges: 0 })
110
+ expect(await new D1SessionRepository(db, clock).revokeById('s1', 'other-user', NOW)).toBe(false)
111
+ })
112
+
113
+ it('binds both sessionId and userId to prevent cross-user revocation', async () => {
114
+ const { db, bindMock } = makeMockDb({ runChanges: 1 })
115
+ await new D1SessionRepository(db, clock).revokeById('my-session', 'my-user', NOW)
116
+ const args = bindMock.mock.calls[0] as unknown[]
117
+ expect(args).toContain('my-session')
118
+ expect(args).toContain('my-user')
119
+ })
120
+ })
121
+ })