@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.
- package/assets/dashboard/BeechLogo.svg +18 -18
- package/assets/dashboard/BeechLogoLIght.svg +48 -48
- package/assets/dashboard/assets/index-CH13idU1.js +554 -0
- package/assets/dashboard/assets/index-CewtCjom.css +1 -0
- package/assets/dashboard/beechLogoDark.svg +48 -48
- package/assets/dashboard/index.html +18 -18
- package/assets/dashboard/sol.svg +3 -3
- package/assets/dashboard/undraw_enter_nwx3.svg +36 -36
- package/migrations/0000_v040_base.sql +213 -213
- package/package.json +2 -2
- package/src/auth/bcrypt-hash-provider.ts +20 -0
- package/src/auth/constants.ts +10 -10
- package/src/auth/generate-refresh-token.test.ts +19 -0
- package/src/auth/hash-provider.test.ts +46 -0
- package/src/auth/in-memory-hash-provider.ts +13 -0
- package/src/auth/jose-token-service.ts +55 -0
- package/src/auth/login.test.ts +92 -0
- package/src/auth/login.ts +74 -91
- package/src/auth/refresh.ts +5 -127
- package/src/auth/static-token-service.ts +18 -0
- package/src/auth/token-service.test.ts +82 -0
- package/src/factory.ts +339 -303
- package/src/features/content/constants.ts +10 -0
- package/src/features/content/handlers/create.ts +157 -0
- package/src/features/content/handlers/delete.ts +80 -0
- package/src/features/content/handlers/facets.ts +45 -0
- package/src/features/content/handlers/get.ts +116 -0
- package/src/features/content/handlers/list.ts +88 -0
- package/src/features/content/handlers/update.ts +211 -0
- package/src/features/content/index.ts +20 -0
- package/src/features/draft/draft.handler.ts +283 -198
- package/src/features/draft/index.ts +1 -1
- package/src/features/email/email.provider.ts +38 -38
- package/src/features/email/email.service.ts +80 -80
- package/src/features/email/email.types.ts +98 -98
- package/src/features/email/index.ts +28 -28
- package/src/features/email/providers/resend.ts +63 -63
- package/src/features/email/templates/password-changed.ts +59 -59
- package/src/features/email/templates/password-reset.ts +64 -64
- package/src/features/email/templates/shell.ts +92 -93
- package/src/features/notifications/index.ts +1 -1
- package/src/features/notifications/notifications.handler.ts +101 -88
- package/src/features/password-reset/index.ts +15 -15
- package/src/features/password-reset/request.ts +82 -88
- package/src/features/password-reset/reset.ts +92 -110
- package/src/features/rotate-field/index.ts +1 -1
- package/src/features/rotate-field/rotate-field.handler.ts +128 -82
- package/src/features/rotate-field/rotate-field.schema.ts +13 -9
- package/src/features/schema/schema.handler.ts +16 -16
- package/src/features/settings/settings.handler.ts +301 -249
- package/src/features/setup/index.ts +91 -59
- package/src/features/stats/index.ts +1 -1
- package/src/features/stats/stats.handler.ts +430 -395
- package/src/index.ts +24 -11
- package/src/media-utils.ts +78 -78
- package/src/middleware/auth-providers.middleware.ts +32 -0
- package/src/middleware/observability.middleware.ts +52 -0
- package/src/middleware/rate-limit.middleware.ts +41 -0
- package/src/middleware/repository.middleware.ts +60 -0
- package/src/middleware/storage.middleware.ts +21 -0
- package/src/middleware.ts +47 -67
- package/src/public/access-policy.ts +23 -23
- package/src/public/api-key-middleware.ts +53 -53
- package/src/public/index.ts +12 -12
- package/src/public/problem-details.ts +48 -42
- package/src/public/public-add.ts +156 -183
- package/src/public/public-edit.ts +159 -183
- package/src/public/public-errors.ts +15 -15
- package/src/public/public-read.ts +216 -217
- package/src/public/public-routes.ts +84 -31
- package/src/public/query-builder.test.ts +220 -0
- package/src/public/query-builder.ts +152 -241
- package/src/public/rate-limit-middleware.ts +30 -42
- package/src/public/response-builder.ts +26 -26
- package/src/public/sanitize.ts +65 -65
- package/src/public/slug-utils.ts +14 -14
- package/src/rate-limit/cloudflare-rate-limiter.test.ts +26 -0
- package/src/rate-limit/cloudflare-rate-limiter.ts +11 -0
- package/src/rate-limit/in-memory-rate-limiter.test.ts +33 -0
- package/src/rate-limit/in-memory-rate-limiter.ts +13 -0
- package/src/rate-limit/no-op-rate-limiter.test.ts +18 -0
- package/src/rate-limit/no-op-rate-limiter.ts +7 -0
- package/src/search-utils.test.ts +207 -0
- package/src/search-utils.ts +209 -192
- package/src/search.ts +61 -72
- package/src/shared/apply-policies.test.ts +77 -0
- package/src/shared/apply-policies.ts +63 -63
- package/src/shared/background-notification-service.test.ts +58 -0
- package/src/shared/background-notification-service.ts +48 -0
- package/src/shared/base.repository.d1.ts +28 -0
- package/src/shared/content-utils.test.ts +161 -0
- package/src/shared/content-utils.ts +82 -108
- package/src/shared/content.repository.d1.test.ts +312 -0
- package/src/shared/content.repository.d1.ts +382 -0
- package/src/shared/d1-activity-log.repository.test.ts +136 -0
- package/src/shared/d1-activity-log.repository.ts +101 -0
- package/src/shared/d1-activity-logger.test.ts +82 -0
- package/src/shared/d1-activity-logger.ts +63 -0
- package/src/shared/d1-analytics.repository.test.ts +74 -0
- package/src/shared/d1-analytics.repository.ts +81 -0
- package/src/shared/d1-content-scan.repository.ts +29 -0
- package/src/shared/d1-notification.repository.test.ts +124 -0
- package/src/shared/d1-notification.repository.ts +114 -0
- package/src/shared/d1-password-reset-token.repository.test.ts +77 -0
- package/src/shared/d1-password-reset-token.repository.ts +52 -0
- package/src/shared/d1-search.repository.test.ts +83 -0
- package/src/shared/d1-search.repository.ts +84 -0
- package/src/shared/d1-session.repository.test.ts +121 -0
- package/src/shared/d1-session.repository.ts +98 -0
- package/src/shared/d1-user.repository.test.ts +147 -0
- package/src/shared/d1-user.repository.ts +109 -0
- package/src/shared/d1-widget.repository.test.ts +217 -0
- package/src/shared/d1-widget.repository.ts +337 -0
- package/src/shared/fixed-clock.ts +21 -0
- package/src/shared/fts-sync.ts +4 -4
- package/src/shared/idempotency.repository.d1.test.ts +79 -0
- package/src/shared/idempotency.repository.d1.ts +56 -0
- package/src/shared/in-memory-activity-logger.ts +15 -0
- package/src/shared/in-memory-notification-service.ts +15 -0
- package/src/shared/media.repository.d1.test.ts +103 -0
- package/src/shared/media.repository.d1.ts +64 -0
- package/src/shared/query-utils.ts +137 -137
- package/src/shared/request-utils.ts +22 -0
- package/src/shared/sequential-id-generator.ts +22 -0
- package/src/shared/storage/factory.ts +40 -0
- package/src/shared/storage/r2-binding-bucket.ts +81 -0
- package/src/shared/storage/s3-bucket.ts +163 -0
- package/src/shared/storage-utils.ts +36 -36
- package/src/shared/system-stats.repository.d1.test.ts +54 -0
- package/src/shared/system-stats.repository.d1.ts +44 -0
- package/src/types.ts +63 -36
- package/src/upload.ts +186 -335
- package/src/widget.ts +208 -349
- package/assets/dashboard/assets/index-CC-jbp6g.js +0 -554
- package/assets/dashboard/assets/index-CQODXprH.css +0 -1
- package/src/content.ts +0 -502
- package/src/features/draft/draft.test.ts +0 -315
- package/src/features/rotate-field/rotate-field.test.ts +0 -297
- package/src/shared/activity-logger.ts +0 -79
- package/src/shared/notification-service.ts +0 -56
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest'
|
|
2
|
+
import type { Seed } from '@beechcms/core'
|
|
3
|
+
import { D1WidgetRepository } from './d1-widget.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(() => ({ all: allMock, first: firstMock, bind: bindMock }))
|
|
10
|
+
return { db: { prepare: prepareMock } as any, prepareMock, bindMock, allMock, firstMock }
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const seed: Seed = {
|
|
14
|
+
slug: 'posts',
|
|
15
|
+
label: 'Post',
|
|
16
|
+
displayNameAlias: 'title',
|
|
17
|
+
branches: [
|
|
18
|
+
{ id: 'br_01', alias: 'title', type: 'text', label: 'Title' },
|
|
19
|
+
{ id: 'br_02', alias: 'price', type: 'number', label: 'Price' },
|
|
20
|
+
],
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
describe('D1WidgetRepository', () => {
|
|
24
|
+
describe('aggregate', () => {
|
|
25
|
+
it('returns 0 when no rows match', async () => {
|
|
26
|
+
const { db } = makeMockDb([], null)
|
|
27
|
+
const value = await new D1WidgetRepository(db).aggregate(seed, { op: 'count' }, 'all')
|
|
28
|
+
expect(value).toBe(0)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('builds COUNT(*) for op=count', async () => {
|
|
32
|
+
const { db, prepareMock } = makeMockDb([], { computed_value: 7 })
|
|
33
|
+
const value = await new D1WidgetRepository(db).aggregate(seed, { op: 'count' }, 'week')
|
|
34
|
+
expect(value).toBe(7)
|
|
35
|
+
const sql = prepareMock.mock.calls[0]![0] as string
|
|
36
|
+
expect(sql).toMatch(/COUNT\(\*\)/)
|
|
37
|
+
expect(sql).toMatch(/FROM content_posts/)
|
|
38
|
+
expect(sql).toMatch(/created_at > unixepoch\('now', '-7 days'\)/)
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('throws UNSAFE_COLUMN when column alias is unknown', async () => {
|
|
42
|
+
const { db } = makeMockDb()
|
|
43
|
+
await expect(
|
|
44
|
+
new D1WidgetRepository(db).aggregate(seed, { op: 'sum', column: 'unknown' }, 'all'),
|
|
45
|
+
).rejects.toThrow('UNSAFE_COLUMN')
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('builds SUM(CAST(... AS REAL)) for valid column', async () => {
|
|
49
|
+
const { db, prepareMock } = makeMockDb([], { computed_value: 42 })
|
|
50
|
+
await new D1WidgetRepository(db).aggregate(seed, { op: 'sum', column: 'price' }, 'all')
|
|
51
|
+
expect(prepareMock.mock.calls[0]![0] as string).toMatch(/SUM\(CAST\(price AS REAL\)\)/)
|
|
52
|
+
})
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
describe('growth', () => {
|
|
56
|
+
it('runs two queries with current and previous filters', async () => {
|
|
57
|
+
const allMock = vi.fn().mockResolvedValue({ results: [] })
|
|
58
|
+
const firstMock = vi
|
|
59
|
+
.fn()
|
|
60
|
+
.mockResolvedValueOnce({ computed_value: 10 })
|
|
61
|
+
.mockResolvedValueOnce({ computed_value: 5 })
|
|
62
|
+
const bindMock = vi.fn(() => ({ all: allMock, first: firstMock }))
|
|
63
|
+
const prepareMock = vi.fn(() => ({ all: allMock, first: firstMock, bind: bindMock }))
|
|
64
|
+
const db = { prepare: prepareMock } as any
|
|
65
|
+
|
|
66
|
+
const result = await new D1WidgetRepository(db).growth(seed, { op: 'count' }, 'month')
|
|
67
|
+
expect(result).toEqual({ currentValue: 10, previousValue: 5 })
|
|
68
|
+
expect(prepareMock).toHaveBeenCalledTimes(2)
|
|
69
|
+
const sql0 = prepareMock.mock.calls[0]![0] as string
|
|
70
|
+
const sql1 = prepareMock.mock.calls[1]![0] as string
|
|
71
|
+
expect(sql0).toMatch(/-1 month/)
|
|
72
|
+
expect(sql1).toMatch(/-2 months/)
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
it('returns zeros when both queries are empty', async () => {
|
|
76
|
+
const { db } = makeMockDb([], null)
|
|
77
|
+
const result = await new D1WidgetRepository(db).growth(seed, { op: 'count' }, 'all')
|
|
78
|
+
expect(result).toEqual({ currentValue: 0, previousValue: 0 })
|
|
79
|
+
})
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
describe('leaderboard', () => {
|
|
83
|
+
it('uses ORDER BY DESC by default and binds only the limit', async () => {
|
|
84
|
+
const { db, prepareMock, bindMock } = makeMockDb([
|
|
85
|
+
{ id: 'a', label: 'A', score: 9 },
|
|
86
|
+
])
|
|
87
|
+
const entries = await new D1WidgetRepository(db).leaderboard(seed, {
|
|
88
|
+
scoreColumn: 'price',
|
|
89
|
+
limit: 5,
|
|
90
|
+
orderDirection: 'DESC',
|
|
91
|
+
})
|
|
92
|
+
expect(entries).toEqual([{ id: 'a', label: 'A', score: 9 }])
|
|
93
|
+
const sql = prepareMock.mock.calls[0]![0] as string
|
|
94
|
+
expect(sql).toMatch(/ORDER BY CAST\(price AS REAL\) DESC/)
|
|
95
|
+
expect(bindMock).toHaveBeenCalledWith(5)
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
it('uses ORDER BY ASC when requested', async () => {
|
|
99
|
+
const { db, prepareMock } = makeMockDb([])
|
|
100
|
+
await new D1WidgetRepository(db).leaderboard(seed, {
|
|
101
|
+
scoreColumn: 'price',
|
|
102
|
+
limit: 3,
|
|
103
|
+
orderDirection: 'ASC',
|
|
104
|
+
})
|
|
105
|
+
expect(prepareMock.mock.calls[0]![0] as string).toMatch(/ORDER BY CAST\(price AS REAL\) ASC/)
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
it('falls back to id when label is null', async () => {
|
|
109
|
+
const { db } = makeMockDb([{ id: 'x', label: null, score: 1 }])
|
|
110
|
+
const [entry] = await new D1WidgetRepository(db).leaderboard(seed, {
|
|
111
|
+
scoreColumn: 'price',
|
|
112
|
+
limit: 1,
|
|
113
|
+
orderDirection: 'DESC',
|
|
114
|
+
})
|
|
115
|
+
expect(entry).toEqual({ id: 'x', label: 'x', score: 1 })
|
|
116
|
+
})
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
describe('list', () => {
|
|
120
|
+
it('returns raw rows and totalCount', async () => {
|
|
121
|
+
const allMock = vi.fn().mockResolvedValue({ results: [{ id: '1', slug: 's', status: 'published', created_at: 1, updated_at: 2, title: 'T', price: 10 }] })
|
|
122
|
+
const firstMock = vi.fn().mockResolvedValue({ total: 7 })
|
|
123
|
+
const bindMock = vi.fn(() => ({ all: allMock, first: firstMock }))
|
|
124
|
+
const prepareMock = vi.fn(() => ({ all: allMock, first: firstMock, bind: bindMock }))
|
|
125
|
+
const db = { prepare: prepareMock } as any
|
|
126
|
+
|
|
127
|
+
const result = await new D1WidgetRepository(db).list(seed, { limit: 10, offset: 0 })
|
|
128
|
+
expect(result.totalCount).toBe(7)
|
|
129
|
+
expect(result.entries[0]?.title).toBe('T')
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
it('appends search LIKE filter against displayNameAlias column', async () => {
|
|
133
|
+
const { db, prepareMock, bindMock } = makeMockDb([], { total: 0 })
|
|
134
|
+
await new D1WidgetRepository(db).list(seed, { limit: 5, offset: 0, search: 'hello' })
|
|
135
|
+
const sql = (prepareMock.mock.calls[1]?.[0] ?? prepareMock.mock.calls[0]![0]) as string
|
|
136
|
+
expect(sql).toMatch(/title LIKE \?/)
|
|
137
|
+
expect(bindMock).toHaveBeenCalledWith('%hello%', 5, 0)
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
it('skips filters with unknown operator', async () => {
|
|
141
|
+
const { db, prepareMock } = makeMockDb([], { total: 0 })
|
|
142
|
+
await new D1WidgetRepository(db).list(seed, {
|
|
143
|
+
limit: 5,
|
|
144
|
+
offset: 0,
|
|
145
|
+
filters: [{ column: 'price', op: 'haxx', value: 1 }],
|
|
146
|
+
})
|
|
147
|
+
const dataSql = prepareMock.mock.calls[1]![0] as string
|
|
148
|
+
expect(dataSql).not.toMatch(/haxx/)
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
it('skips filters with unsafe column', async () => {
|
|
152
|
+
const { db, prepareMock } = makeMockDb([], { total: 0 })
|
|
153
|
+
await new D1WidgetRepository(db).list(seed, {
|
|
154
|
+
limit: 5,
|
|
155
|
+
offset: 0,
|
|
156
|
+
filters: [{ column: 'evil', op: 'eq', value: 1 }],
|
|
157
|
+
})
|
|
158
|
+
const dataSql = prepareMock.mock.calls[1]![0] as string
|
|
159
|
+
expect(dataSql).not.toMatch(/evil/)
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
it('uses ORDER BY DESC branch when requested', async () => {
|
|
163
|
+
const { db, prepareMock } = makeMockDb([], { total: 0 })
|
|
164
|
+
await new D1WidgetRepository(db).list(seed, {
|
|
165
|
+
limit: 5,
|
|
166
|
+
offset: 0,
|
|
167
|
+
orderByColumn: 'price',
|
|
168
|
+
orderDirection: 'DESC',
|
|
169
|
+
})
|
|
170
|
+
const dataSql = prepareMock.mock.calls[1]![0] as string
|
|
171
|
+
expect(dataSql).toMatch(/ORDER BY price DESC/)
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
it('falls back to created_at when orderByColumn is unsafe', async () => {
|
|
175
|
+
const { db, prepareMock } = makeMockDb([], { total: 0 })
|
|
176
|
+
await new D1WidgetRepository(db).list(seed, {
|
|
177
|
+
limit: 5,
|
|
178
|
+
offset: 0,
|
|
179
|
+
orderByColumn: 'evil',
|
|
180
|
+
})
|
|
181
|
+
const dataSql = prepareMock.mock.calls[1]![0] as string
|
|
182
|
+
expect(dataSql).toMatch(/ORDER BY created_at/)
|
|
183
|
+
})
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
describe('timeseries', () => {
|
|
187
|
+
it('groups by date bucket on created_at', async () => {
|
|
188
|
+
const { db, prepareMock } = makeMockDb([
|
|
189
|
+
{ bucket_label: '2026-01-01', bucket_value: 3 },
|
|
190
|
+
])
|
|
191
|
+
const points = await new D1WidgetRepository(db).timeseries(
|
|
192
|
+
seed,
|
|
193
|
+
{ op: 'count' },
|
|
194
|
+
'all',
|
|
195
|
+
'created_at',
|
|
196
|
+
)
|
|
197
|
+
expect(points).toEqual([{ label: '2026-01-01', value: 3 }])
|
|
198
|
+
const sql = prepareMock.mock.calls[0]![0] as string
|
|
199
|
+
expect(sql).toMatch(/strftime\('%Y-%m-%d', created_at, 'unixepoch'\)/)
|
|
200
|
+
expect(sql).toMatch(/GROUP BY bucket_label/)
|
|
201
|
+
})
|
|
202
|
+
|
|
203
|
+
it('CASTs non-system group columns as INTEGER', async () => {
|
|
204
|
+
const { db, prepareMock } = makeMockDb([])
|
|
205
|
+
await new D1WidgetRepository(db).timeseries(seed, { op: 'count' }, 'all', 'price')
|
|
206
|
+
const sql = prepareMock.mock.calls[0]![0] as string
|
|
207
|
+
expect(sql).toMatch(/CAST\(price AS INTEGER\)/)
|
|
208
|
+
})
|
|
209
|
+
|
|
210
|
+
it('throws UNSAFE_COLUMN for invalid groupColumn', async () => {
|
|
211
|
+
const { db } = makeMockDb()
|
|
212
|
+
await expect(
|
|
213
|
+
new D1WidgetRepository(db).timeseries(seed, { op: 'count' }, 'all', 'evil'),
|
|
214
|
+
).rejects.toThrow('UNSAFE_COLUMN')
|
|
215
|
+
})
|
|
216
|
+
})
|
|
217
|
+
})
|