@beechcms/api 0.4.0 → 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 (86) hide show
  1. package/assets/dashboard/assets/index-CH13idU1.js +554 -0
  2. package/assets/dashboard/index.html +1 -1
  3. package/package.json +2 -2
  4. package/src/auth/bcrypt-hash-provider.ts +20 -0
  5. package/src/auth/constants.ts +3 -3
  6. package/src/auth/generate-refresh-token.test.ts +19 -0
  7. package/src/auth/hash-provider.test.ts +46 -0
  8. package/src/auth/in-memory-hash-provider.ts +13 -0
  9. package/src/auth/jose-token-service.ts +55 -0
  10. package/src/auth/login.test.ts +92 -0
  11. package/src/auth/login.ts +15 -32
  12. package/src/auth/refresh.ts +0 -122
  13. package/src/auth/static-token-service.ts +18 -0
  14. package/src/auth/token-service.test.ts +82 -0
  15. package/src/factory.ts +70 -78
  16. package/src/features/content/handlers/create.ts +14 -10
  17. package/src/features/content/handlers/delete.ts +13 -9
  18. package/src/features/content/handlers/update.ts +13 -9
  19. package/src/features/draft/draft.handler.ts +23 -12
  20. package/src/features/notifications/notifications.handler.ts +25 -54
  21. package/src/features/password-reset/request.ts +17 -41
  22. package/src/features/password-reset/reset.ts +18 -54
  23. package/src/features/rotate-field/rotate-field.handler.ts +15 -19
  24. package/src/features/schema/schema.handler.ts +1 -1
  25. package/src/features/settings/settings.handler.ts +62 -175
  26. package/src/features/setup/index.ts +12 -17
  27. package/src/features/stats/stats.handler.ts +110 -138
  28. package/src/middleware/auth-providers.middleware.ts +32 -0
  29. package/src/middleware/observability.middleware.ts +52 -0
  30. package/src/middleware/rate-limit.middleware.ts +41 -0
  31. package/src/middleware/repository.middleware.ts +41 -5
  32. package/src/middleware.ts +15 -35
  33. package/src/public/public-add.ts +5 -15
  34. package/src/public/public-edit.ts +4 -3
  35. package/src/public/public-read.ts +3 -3
  36. package/src/public/public-routes.ts +2 -2
  37. package/src/public/query-builder.test.ts +220 -0
  38. package/src/public/rate-limit-middleware.ts +7 -19
  39. package/src/rate-limit/cloudflare-rate-limiter.test.ts +26 -0
  40. package/src/rate-limit/cloudflare-rate-limiter.ts +11 -0
  41. package/src/rate-limit/in-memory-rate-limiter.test.ts +33 -0
  42. package/src/rate-limit/in-memory-rate-limiter.ts +13 -0
  43. package/src/rate-limit/no-op-rate-limiter.test.ts +18 -0
  44. package/src/rate-limit/no-op-rate-limiter.ts +7 -0
  45. package/src/search-utils.test.ts +207 -0
  46. package/src/search-utils.ts +18 -1
  47. package/src/search.ts +24 -35
  48. package/src/shared/apply-policies.test.ts +77 -0
  49. package/src/shared/background-notification-service.test.ts +58 -0
  50. package/src/shared/background-notification-service.ts +48 -0
  51. package/src/shared/content-utils.test.ts +161 -0
  52. package/src/shared/content.repository.d1.test.ts +312 -0
  53. package/src/shared/d1-activity-log.repository.test.ts +136 -0
  54. package/src/shared/d1-activity-log.repository.ts +101 -0
  55. package/src/shared/d1-activity-logger.test.ts +82 -0
  56. package/src/shared/d1-activity-logger.ts +63 -0
  57. package/src/shared/d1-analytics.repository.test.ts +74 -0
  58. package/src/shared/d1-analytics.repository.ts +81 -0
  59. package/src/shared/d1-content-scan.repository.ts +29 -0
  60. package/src/shared/d1-notification.repository.test.ts +124 -0
  61. package/src/shared/d1-notification.repository.ts +114 -0
  62. package/src/shared/d1-password-reset-token.repository.test.ts +77 -0
  63. package/src/shared/d1-password-reset-token.repository.ts +52 -0
  64. package/src/shared/d1-search.repository.test.ts +83 -0
  65. package/src/shared/d1-search.repository.ts +84 -0
  66. package/src/shared/d1-session.repository.test.ts +121 -0
  67. package/src/shared/d1-session.repository.ts +98 -0
  68. package/src/shared/d1-user.repository.test.ts +147 -0
  69. package/src/shared/d1-user.repository.ts +109 -0
  70. package/src/shared/d1-widget.repository.test.ts +217 -0
  71. package/src/shared/d1-widget.repository.ts +337 -0
  72. package/src/shared/fixed-clock.ts +21 -0
  73. package/src/shared/idempotency.repository.d1.test.ts +79 -0
  74. package/src/shared/in-memory-activity-logger.ts +15 -0
  75. package/src/shared/in-memory-notification-service.ts +15 -0
  76. package/src/shared/media.repository.d1.test.ts +103 -0
  77. package/src/shared/media.repository.d1.ts +1 -1
  78. package/src/shared/request-utils.ts +22 -0
  79. package/src/shared/sequential-id-generator.ts +22 -0
  80. package/src/shared/system-stats.repository.d1.test.ts +54 -0
  81. package/src/types.ts +20 -3
  82. package/src/upload.ts +14 -7
  83. package/src/widget.ts +112 -253
  84. package/assets/dashboard/assets/index-FQ6JhvRH.js +0 -554
  85. package/src/shared/activity-logger.ts +0 -79
  86. package/src/shared/notification-service.ts +0 -56
@@ -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
+ })
@@ -0,0 +1,98 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import type { ISessionRepository, NewRefreshToken, RefreshTokenRecord, ActiveSessionSummary, IClock } from '@beechcms/core'
3
+
4
+ type RefreshTokenRow = {
5
+ id: string
6
+ user_id: string
7
+ token_hash: string
8
+ expires_at: number
9
+ created_at: number
10
+ revoked_at: number | null
11
+ }
12
+
13
+ type SessionSummaryRow = {
14
+ id: string
15
+ created_at: number
16
+ expires_at: number
17
+ }
18
+
19
+ function rowToRecord(row: RefreshTokenRow): RefreshTokenRecord {
20
+ return {
21
+ id: row.id,
22
+ userId: row.user_id,
23
+ tokenHash: row.token_hash,
24
+ expiresAt: row.expires_at,
25
+ createdAt: row.created_at,
26
+ revokedAt: row.revoked_at,
27
+ }
28
+ }
29
+
30
+ export class D1SessionRepository implements ISessionRepository {
31
+ constructor(
32
+ private readonly db: D1Database,
33
+ private readonly clock: IClock,
34
+ ) {}
35
+
36
+ async saveRefreshToken(record: NewRefreshToken): Promise<void> {
37
+ await this.db
38
+ .prepare('INSERT INTO refresh_tokens (id, user_id, token_hash, expires_at, created_at) VALUES (?, ?, ?, ?, ?)')
39
+ .bind(record.id, record.userId, record.tokenHash, record.expiresAt, this.clock.nowSeconds())
40
+ .run()
41
+ }
42
+
43
+ async findActiveByHash(tokenHash: string, nowTimestamp: number): Promise<RefreshTokenRecord | null> {
44
+ const row = await this.db
45
+ .prepare(
46
+ `SELECT id, user_id, token_hash, expires_at, created_at, revoked_at
47
+ FROM refresh_tokens
48
+ WHERE token_hash = ? AND expires_at > ? AND revoked_at IS NULL
49
+ LIMIT 1`
50
+ )
51
+ .bind(tokenHash, nowTimestamp)
52
+ .first<RefreshTokenRow>()
53
+ return row ? rowToRecord(row) : null
54
+ }
55
+
56
+ async revokeByHash(tokenHash: string, nowTimestamp: number): Promise<boolean> {
57
+ const result = await this.db
58
+ .prepare(
59
+ `UPDATE refresh_tokens
60
+ SET revoked_at = ?
61
+ WHERE token_hash = ? AND revoked_at IS NULL AND expires_at >= ?`
62
+ )
63
+ .bind(nowTimestamp, tokenHash, nowTimestamp)
64
+ .run()
65
+ const changes = (result as unknown as { meta?: { changes?: number } })?.meta?.changes ?? 0
66
+ return changes > 0
67
+ }
68
+
69
+ async revokeAllForUser(userId: string, nowTimestamp: number): Promise<void> {
70
+ await this.db
71
+ .prepare('UPDATE refresh_tokens SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL')
72
+ .bind(nowTimestamp, userId)
73
+ .run()
74
+ }
75
+
76
+ async listActiveForUser(userId: string, nowTimestamp: number, limit: number): Promise<ActiveSessionSummary[]> {
77
+ const { results } = await this.db
78
+ .prepare(
79
+ `SELECT id, created_at, expires_at FROM refresh_tokens
80
+ WHERE user_id = ? AND revoked_at IS NULL AND expires_at > ?
81
+ ORDER BY created_at DESC LIMIT ?`
82
+ )
83
+ .bind(userId, nowTimestamp, limit)
84
+ .all<SessionSummaryRow>()
85
+ return (results ?? []).map(row => ({ id: row.id, createdAt: row.created_at, expiresAt: row.expires_at }))
86
+ }
87
+
88
+ async revokeById(sessionId: string, userId: string, nowTimestamp: number): Promise<boolean> {
89
+ const result = await this.db
90
+ .prepare(
91
+ 'UPDATE refresh_tokens SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at IS NULL'
92
+ )
93
+ .bind(nowTimestamp, sessionId, userId)
94
+ .run()
95
+ const changes = (result as unknown as { meta?: { changes?: number } })?.meta?.changes ?? 0
96
+ return changes > 0
97
+ }
98
+ }
@@ -0,0 +1,147 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { D1UserRepository } from './d1-user.repository'
3
+
4
+ const USER_ROW = {
5
+ id: 'u1',
6
+ email: 'test@test.com',
7
+ name: 'Test User',
8
+ password_hash: 'hash-abc',
9
+ role: 'admin',
10
+ avatar_url: null,
11
+ notification_prefs: '{}',
12
+ }
13
+
14
+ function makeMockDb(opts: {
15
+ firstResult?: unknown
16
+ runChanges?: number
17
+ allResults?: unknown[]
18
+ } = {}) {
19
+ const { firstResult = null, runChanges = 1, allResults = [] } = opts
20
+ const runMock = vi.fn().mockResolvedValue({ success: true, meta: { changes: runChanges } })
21
+ const firstMock = vi.fn().mockResolvedValue(firstResult)
22
+ const allMock = vi.fn().mockResolvedValue({ results: allResults })
23
+ const bindMock = vi.fn(() => ({ first: firstMock, all: allMock, run: runMock }))
24
+ // prepare() may be called without bind() for countAll (which calls .first() directly)
25
+ const prepareMock = vi.fn(() => ({ bind: bindMock, first: firstMock, run: runMock }))
26
+ return { db: { prepare: prepareMock } as any, prepareMock, bindMock, runMock, firstMock }
27
+ }
28
+
29
+ describe('D1UserRepository', () => {
30
+ describe('countAll', () => {
31
+ it('returns the count value from the database', async () => {
32
+ const { db, firstMock } = makeMockDb()
33
+ firstMock.mockResolvedValue({ count: 5 })
34
+ expect(await new D1UserRepository(db).countAll()).toBe(5)
35
+ })
36
+
37
+ it('returns 0 when the query returns null', async () => {
38
+ const { db } = makeMockDb({ firstResult: null })
39
+ expect(await new D1UserRepository(db).countAll()).toBe(0)
40
+ })
41
+ })
42
+
43
+ describe('findByEmail', () => {
44
+ it('returns a UserRecord with camelCase keys mapped from the snake_case row', async () => {
45
+ const { db } = makeMockDb({ firstResult: USER_ROW })
46
+ const result = await new D1UserRepository(db).findByEmail('test@test.com')
47
+ expect(result).toEqual({
48
+ id: 'u1',
49
+ email: 'test@test.com',
50
+ name: 'Test User',
51
+ passwordHash: 'hash-abc',
52
+ role: 'admin',
53
+ avatarUrl: null,
54
+ notificationPreferences: '{}',
55
+ })
56
+ })
57
+
58
+ it('returns null when no user is found', async () => {
59
+ const { db } = makeMockDb({ firstResult: null })
60
+ expect(await new D1UserRepository(db).findByEmail('nobody@test.com')).toBeNull()
61
+ })
62
+ })
63
+
64
+ describe('findById', () => {
65
+ it('returns a mapped UserRecord when found', async () => {
66
+ const { db } = makeMockDb({ firstResult: USER_ROW })
67
+ const result = await new D1UserRepository(db).findById('u1')
68
+ expect(result?.id).toBe('u1')
69
+ expect(result?.passwordHash).toBe('hash-abc')
70
+ })
71
+
72
+ it('returns null when the user is not found', async () => {
73
+ const { db } = makeMockDb({ firstResult: null })
74
+ expect(await new D1UserRepository(db).findById('unknown')).toBeNull()
75
+ })
76
+ })
77
+
78
+ describe('create', () => {
79
+ it('calls prepare with an INSERT INTO users statement', async () => {
80
+ const { db, prepareMock } = makeMockDb()
81
+ await new D1UserRepository(db).create({
82
+ id: 'u1', email: 'a@b.com', passwordHash: 'hash', role: 'admin', name: 'Test',
83
+ })
84
+ expect(prepareMock).toHaveBeenCalledWith(expect.stringContaining('INSERT INTO users'))
85
+ })
86
+
87
+ it('binds id, email, passwordHash, role, name in the correct order', async () => {
88
+ const { db, bindMock } = makeMockDb()
89
+ await new D1UserRepository(db).create({
90
+ id: 'u1', email: 'a@b.com', passwordHash: 'hash', role: 'admin', name: 'Test',
91
+ })
92
+ expect(bindMock).toHaveBeenCalledWith('u1', 'a@b.com', 'hash', 'admin', 'Test')
93
+ })
94
+ })
95
+
96
+ describe('updateProfile', () => {
97
+ it('does nothing when no fields are provided', async () => {
98
+ const { db, prepareMock } = makeMockDb()
99
+ await new D1UserRepository(db).updateProfile('u1', {})
100
+ expect(prepareMock).not.toHaveBeenCalled()
101
+ })
102
+
103
+ it('generates a SET clause containing only the provided field', async () => {
104
+ const { db, prepareMock } = makeMockDb()
105
+ await new D1UserRepository(db).updateProfile('u1', { name: 'New Name' })
106
+ const sql: string = prepareMock.mock.calls[0][0]
107
+ expect(sql).toContain('name = ?')
108
+ expect(sql).not.toContain('email = ?')
109
+ })
110
+
111
+ it('includes both fields when both name and email are provided', async () => {
112
+ const { db, prepareMock } = makeMockDb()
113
+ await new D1UserRepository(db).updateProfile('u1', { name: 'N', email: 'e@e.com' })
114
+ const sql: string = prepareMock.mock.calls[0][0]
115
+ expect(sql).toContain('name = ?')
116
+ expect(sql).toContain('email = ?')
117
+ })
118
+ })
119
+
120
+ describe('updatePasswordHash', () => {
121
+ it('calls UPDATE users SET password_hash', async () => {
122
+ const { db, prepareMock } = makeMockDb()
123
+ await new D1UserRepository(db).updatePasswordHash('u1', 'new-hash')
124
+ expect(prepareMock).toHaveBeenCalledWith(expect.stringContaining('password_hash'))
125
+ })
126
+ })
127
+
128
+ describe('updateAvatarUrl', () => {
129
+ it('calls UPDATE users SET avatar_url', async () => {
130
+ const { db, prepareMock } = makeMockDb()
131
+ await new D1UserRepository(db).updateAvatarUrl('u1', 'https://cdn.example.com/avatar.jpg')
132
+ expect(prepareMock).toHaveBeenCalledWith(expect.stringContaining('avatar_url'))
133
+ })
134
+ })
135
+
136
+ describe('emailBelongsToAnotherUser', () => {
137
+ it('returns true when another user row is found with that email', async () => {
138
+ const { db } = makeMockDb({ firstResult: { id: 'other-user' } })
139
+ expect(await new D1UserRepository(db).emailBelongsToAnotherUser('taken@test.com', 'current')).toBe(true)
140
+ })
141
+
142
+ it('returns false when no other user owns the email', async () => {
143
+ const { db } = makeMockDb({ firstResult: null })
144
+ expect(await new D1UserRepository(db).emailBelongsToAnotherUser('free@test.com', 'current')).toBe(false)
145
+ })
146
+ })
147
+ })
@@ -0,0 +1,109 @@
1
+ /// <reference types="@cloudflare/workers-types" />
2
+ import type { IUserRepository, UserRecord, NewUserInput } from '@beechcms/core'
3
+
4
+ type UserRow = {
5
+ id: string
6
+ email: string
7
+ name: string | null
8
+ password_hash: string
9
+ role: string
10
+ avatar_url: string | null
11
+ notification_prefs: string
12
+ }
13
+
14
+ function rowToRecord(row: UserRow): UserRecord {
15
+ return {
16
+ id: row.id,
17
+ email: row.email,
18
+ name: row.name,
19
+ passwordHash: row.password_hash,
20
+ role: row.role,
21
+ avatarUrl: row.avatar_url,
22
+ notificationPreferences: row.notification_prefs,
23
+ }
24
+ }
25
+
26
+ export class D1UserRepository implements IUserRepository {
27
+ constructor(private readonly db: D1Database) {}
28
+
29
+ async countAll(): Promise<number> {
30
+ const result = await this.db
31
+ .prepare('SELECT COUNT(*) as count FROM users')
32
+ .first<{ count: number }>()
33
+ return result?.count ?? 0
34
+ }
35
+
36
+ async findById(userId: string): Promise<UserRecord | null> {
37
+ const row = await this.db
38
+ .prepare('SELECT id, email, name, password_hash, role, avatar_url, notification_prefs FROM users WHERE id = ? LIMIT 1')
39
+ .bind(userId)
40
+ .first<UserRow>()
41
+ return row ? rowToRecord(row) : null
42
+ }
43
+
44
+ async findByEmail(email: string): Promise<UserRecord | null> {
45
+ const row = await this.db
46
+ .prepare('SELECT id, email, name, password_hash, role, avatar_url, notification_prefs FROM users WHERE email = ? LIMIT 1')
47
+ .bind(email)
48
+ .first<UserRow>()
49
+ return row ? rowToRecord(row) : null
50
+ }
51
+
52
+ async create(user: NewUserInput): Promise<void> {
53
+ await this.db
54
+ .prepare('INSERT INTO users (id, email, password_hash, role, name) VALUES (?, ?, ?, ?, ?)')
55
+ .bind(user.id, user.email, user.passwordHash, user.role, user.name)
56
+ .run()
57
+ }
58
+
59
+ async updateProfile(userId: string, fields: { name?: string; email?: string }): Promise<void> {
60
+ const columnAssignments: string[] = []
61
+ const boundValues: unknown[] = []
62
+
63
+ if (fields.name !== undefined) {
64
+ columnAssignments.push('name = ?')
65
+ boundValues.push(fields.name)
66
+ }
67
+ if (fields.email !== undefined) {
68
+ columnAssignments.push('email = ?')
69
+ boundValues.push(fields.email)
70
+ }
71
+
72
+ if (columnAssignments.length === 0) return
73
+
74
+ boundValues.push(userId)
75
+ await this.db
76
+ .prepare(`UPDATE users SET ${columnAssignments.join(', ')} WHERE id = ?`)
77
+ .bind(...boundValues)
78
+ .run()
79
+ }
80
+
81
+ async updatePasswordHash(userId: string, newPasswordHash: string): Promise<void> {
82
+ await this.db
83
+ .prepare('UPDATE users SET password_hash = ? WHERE id = ?')
84
+ .bind(newPasswordHash, userId)
85
+ .run()
86
+ }
87
+
88
+ async updateAvatarUrl(userId: string, avatarUrl: string | null): Promise<void> {
89
+ await this.db
90
+ .prepare('UPDATE users SET avatar_url = ? WHERE id = ?')
91
+ .bind(avatarUrl, userId)
92
+ .run()
93
+ }
94
+
95
+ async updateNotificationPreferences(userId: string, preferencesJson: string): Promise<void> {
96
+ await this.db
97
+ .prepare('UPDATE users SET notification_prefs = ? WHERE id = ?')
98
+ .bind(preferencesJson, userId)
99
+ .run()
100
+ }
101
+
102
+ async emailBelongsToAnotherUser(email: string, currentUserId: string): Promise<boolean> {
103
+ const row = await this.db
104
+ .prepare('SELECT id FROM users WHERE email = ? AND id != ? LIMIT 1')
105
+ .bind(email, currentUserId)
106
+ .first()
107
+ return row !== null
108
+ }
109
+ }