@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,92 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { parseLoginBody, validateLoginInput, verifyPassword, DUMMY_PASSWORD_HASH } from './login'
|
|
3
|
+
import { InMemoryHashProvider } from './in-memory-hash-provider'
|
|
4
|
+
|
|
5
|
+
describe('parseLoginBody', () => {
|
|
6
|
+
it('returns credentials for a valid object body', () => {
|
|
7
|
+
expect(parseLoginBody({ email: 'user@test.com', password: 'pass1234' }))
|
|
8
|
+
.toEqual({ email: 'user@test.com', password: 'pass1234' })
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
it('trims leading and trailing whitespace from email', () => {
|
|
12
|
+
expect(parseLoginBody({ email: ' user@test.com ', password: 'pass' }))
|
|
13
|
+
.toEqual({ email: 'user@test.com', password: 'pass' })
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
it('returns null for non-object input', () => {
|
|
17
|
+
expect(parseLoginBody(null)).toBeNull()
|
|
18
|
+
expect(parseLoginBody('string')).toBeNull()
|
|
19
|
+
expect(parseLoginBody(42)).toBeNull()
|
|
20
|
+
expect(parseLoginBody(undefined)).toBeNull()
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('returns null when email field is missing', () => {
|
|
24
|
+
expect(parseLoginBody({ password: 'pass' })).toBeNull()
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('returns null when password field is missing', () => {
|
|
28
|
+
expect(parseLoginBody({ email: 'x@x.com' })).toBeNull()
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('returns null when email is an empty string after trimming', () => {
|
|
32
|
+
expect(parseLoginBody({ email: ' ', password: 'pass' })).toBeNull()
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('returns null when email is not a string', () => {
|
|
36
|
+
expect(parseLoginBody({ email: 42, password: 'pass' })).toBeNull()
|
|
37
|
+
})
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
describe('validateLoginInput', () => {
|
|
41
|
+
it('accepts a valid email and an 8-character password', () => {
|
|
42
|
+
expect(validateLoginInput('user@test.com', '12345678')).toBe(true)
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it('rejects an email without an @ sign', () => {
|
|
46
|
+
expect(validateLoginInput('notanemail', 'password123')).toBe(false)
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it('rejects an email with nothing before the @', () => {
|
|
50
|
+
expect(validateLoginInput('@test.com', 'password123')).toBe(false)
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('rejects an email with no domain extension', () => {
|
|
54
|
+
expect(validateLoginInput('user@nodot', 'password123')).toBe(false)
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('rejects a password shorter than 8 characters', () => {
|
|
58
|
+
expect(validateLoginInput('user@test.com', '1234567')).toBe(false)
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it('rejects a password longer than 128 characters', () => {
|
|
62
|
+
expect(validateLoginInput('user@test.com', 'a'.repeat(129))).toBe(false)
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
it('accepts passwords at the lower boundary (exactly 8 characters)', () => {
|
|
66
|
+
expect(validateLoginInput('user@test.com', 'a'.repeat(8))).toBe(true)
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it('accepts passwords at the upper boundary (exactly 128 characters)', () => {
|
|
70
|
+
expect(validateLoginInput('user@test.com', 'a'.repeat(128))).toBe(true)
|
|
71
|
+
})
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
describe('verifyPassword', () => {
|
|
75
|
+
const hashProvider = new InMemoryHashProvider()
|
|
76
|
+
|
|
77
|
+
it('returns true when the plaintext matches the stored hash', async () => {
|
|
78
|
+
const hash = await hashProvider.hash('mypassword')
|
|
79
|
+
expect(await verifyPassword('mypassword', hash, hashProvider)).toBe(true)
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
it('returns false when the plaintext does not match', async () => {
|
|
83
|
+
const hash = await hashProvider.hash('correct')
|
|
84
|
+
expect(await verifyPassword('wrong', hash, hashProvider)).toBe(false)
|
|
85
|
+
})
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
describe('DUMMY_PASSWORD_HASH', () => {
|
|
89
|
+
it('has bcrypt format so constant-time comparison runs even when no user is found', () => {
|
|
90
|
+
expect(DUMMY_PASSWORD_HASH).toMatch(/^\$2[aby]\$\d+\$/)
|
|
91
|
+
})
|
|
92
|
+
})
|
package/src/auth/login.ts
CHANGED
|
@@ -1,91 +1,74 @@
|
|
|
1
|
-
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
export type LoginCredentials = {
|
|
5
|
-
email: string
|
|
6
|
-
password: string
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
*
|
|
34
|
-
* @
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
const
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
if (
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
*
|
|
49
|
-
* @param
|
|
50
|
-
* @
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
EMAIL_REGEX.test(email) &&
|
|
56
|
-
password.length >= MIN_PASSWORD_LENGTH &&
|
|
57
|
-
password.length <= MAX_PASSWORD_LENGTH
|
|
58
|
-
)
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
*
|
|
63
|
-
* @param
|
|
64
|
-
* @param
|
|
65
|
-
* @
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
)
|
|
76
|
-
const row = await stmt.bind(email).first<UserRecord>()
|
|
77
|
-
return row
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* Verifica che la password in chiaro corrisponda all'hash bcrypt salvato.
|
|
82
|
-
* @param plainPassword - Password in chiaro
|
|
83
|
-
* @param hash - Hash bcrypt salvato nel DB
|
|
84
|
-
* @returns true se la password è corretta
|
|
85
|
-
*/
|
|
86
|
-
export async function verifyPassword(
|
|
87
|
-
plainPassword: string,
|
|
88
|
-
hash: string
|
|
89
|
-
): Promise<boolean> {
|
|
90
|
-
return bcrypt.compare(plainPassword, hash)
|
|
91
|
-
}
|
|
1
|
+
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
+
import type { IHashProvider } from '@beechcms/core'
|
|
3
|
+
|
|
4
|
+
export type LoginCredentials = {
|
|
5
|
+
email: string
|
|
6
|
+
password: string
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Regex per validare formato email.
|
|
11
|
+
* Utilizza classi di caratteri che non si sovrappongono per evitare il backtracking catastrofico (ReDoS).
|
|
12
|
+
*/
|
|
13
|
+
const EMAIL_REGEX = /^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/
|
|
14
|
+
/** Lunghezza massima email secondo standard RFC 5321 */
|
|
15
|
+
const MAX_EMAIL_LENGTH = 254
|
|
16
|
+
|
|
17
|
+
/** Lunghezza minima password (caratteri) */
|
|
18
|
+
const MIN_PASSWORD_LENGTH = 8
|
|
19
|
+
|
|
20
|
+
/** Lunghezza massima password (caratteri) - limite ragionevole per evitare DoS */
|
|
21
|
+
const MAX_PASSWORD_LENGTH = 128
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Hash bcrypt dummy valido.
|
|
25
|
+
* Usato quando l'utente non esiste per evitare timing attack
|
|
26
|
+
* (stesso tempo di risposta che con password errata).
|
|
27
|
+
*/
|
|
28
|
+
export const DUMMY_PASSWORD_HASH =
|
|
29
|
+
'$2a$10$SbkRFOafACxVM2ahxerVDu3tSkCXWm29b62WdB.4WGG02Qjsfzni6'
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Estrae e valida email e password dal body della richiesta.
|
|
33
|
+
* @param body - Body grezzo (tipicamente da req.json())
|
|
34
|
+
* @returns Oggetto {email, password} se valido, null altrimenti
|
|
35
|
+
*/
|
|
36
|
+
export function parseLoginBody(body: unknown): LoginCredentials | null {
|
|
37
|
+
if (body === null || typeof body !== 'object') return null
|
|
38
|
+
const obj = body as Record<string, unknown>
|
|
39
|
+
const email = obj.email
|
|
40
|
+
const password = obj.password
|
|
41
|
+
if (typeof email !== 'string' || typeof password !== 'string') return null
|
|
42
|
+
if (!email.trim() || !password) return null
|
|
43
|
+
return { email: email.trim(), password }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Verifica che email e password rispettino i formati richiesti.
|
|
48
|
+
* @param email - Email da validare (deve contenere @ e punto dopo @)
|
|
49
|
+
* @param password - Password (8-128 caratteri)
|
|
50
|
+
* @returns true se valido
|
|
51
|
+
*/
|
|
52
|
+
export function validateLoginInput(email: string, password: string): boolean {
|
|
53
|
+
return (
|
|
54
|
+
email.length <= MAX_EMAIL_LENGTH &&
|
|
55
|
+
EMAIL_REGEX.test(email) &&
|
|
56
|
+
password.length >= MIN_PASSWORD_LENGTH &&
|
|
57
|
+
password.length <= MAX_PASSWORD_LENGTH
|
|
58
|
+
)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Verifica che la password in chiaro corrisponda all'hash salvato.
|
|
63
|
+
* @param plainPassword - Password in chiaro
|
|
64
|
+
* @param hash - Hash salvato nel DB
|
|
65
|
+
* @param hashProvider - Provider usato per la comparazione costante-time
|
|
66
|
+
* @returns true se la password è corretta
|
|
67
|
+
*/
|
|
68
|
+
export async function verifyPassword(
|
|
69
|
+
plainPassword: string,
|
|
70
|
+
hash: string,
|
|
71
|
+
hashProvider: IHashProvider
|
|
72
|
+
): Promise<boolean> {
|
|
73
|
+
return hashProvider.verify(plainPassword, hash)
|
|
74
|
+
}
|
package/src/auth/refresh.ts
CHANGED
|
@@ -1,127 +1,5 @@
|
|
|
1
|
-
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
export type JwtTokenOptions = {
|
|
8
|
-
issuer?: string
|
|
9
|
-
audience?: string
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export type RefreshTokenRecord = {
|
|
13
|
-
id: string
|
|
14
|
-
user_id: string
|
|
15
|
-
token_hash: string
|
|
16
|
-
expires_at: number
|
|
17
|
-
created_at: number
|
|
18
|
-
revoked_at: number | null
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/** Genera un refresh token sicuro (UUID v4) - usa Web Crypto API globale */
|
|
22
|
-
export function generateRefreshToken(): string {
|
|
23
|
-
return crypto.randomUUID()
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* Hash SHA-256 del refresh token per storage sicuro.
|
|
28
|
-
* Usa Web Crypto API (crypto.subtle.digest).
|
|
29
|
-
*/
|
|
30
|
-
export async function hashRefreshToken(token: string): Promise<string> {
|
|
31
|
-
const encoder = new TextEncoder()
|
|
32
|
-
const data = encoder.encode(token)
|
|
33
|
-
const hashBuffer = await crypto.subtle.digest('SHA-256', data)
|
|
34
|
-
const hashBytes = Array.from(new Uint8Array(hashBuffer))
|
|
35
|
-
return hashBytes.map((byte) => byte.toString(16).padStart(2, '0')).join('')
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Salva refresh token in DB (solo hash, mai in chiaro).
|
|
40
|
-
* @param expiresInDays - Giorni di validità (default 7)
|
|
41
|
-
*/
|
|
42
|
-
export async function saveRefreshToken(
|
|
43
|
-
db: D1Database,
|
|
44
|
-
userId: string,
|
|
45
|
-
token: string,
|
|
46
|
-
expiresInDays: number = 7
|
|
47
|
-
): Promise<void> {
|
|
48
|
-
const id = crypto.randomUUID()
|
|
49
|
-
const tokenHash = await hashRefreshToken(token)
|
|
50
|
-
const expiresAt = Math.floor(Date.now() / 1000) + expiresInDays * SECONDS_PER_DAY
|
|
51
|
-
|
|
52
|
-
await db.prepare(
|
|
53
|
-
`INSERT INTO refresh_tokens (id, user_id, token_hash, expires_at)
|
|
54
|
-
VALUES (?, ?, ?, ?)`
|
|
55
|
-
).bind(id, userId, tokenHash, expiresAt).run()
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* Valida refresh token: verifica hash in DB, scadenza e che non sia revocato.
|
|
60
|
-
* @returns { valid, userId? } - userId presente solo se valido
|
|
61
|
-
*/
|
|
62
|
-
export async function validateRefreshToken(
|
|
63
|
-
db: D1Database,
|
|
64
|
-
token: string
|
|
65
|
-
): Promise<{ valid: boolean; userId?: string }> {
|
|
66
|
-
const tokenHash = await hashRefreshToken(token)
|
|
67
|
-
const now = Math.floor(Date.now() / 1000)
|
|
68
|
-
|
|
69
|
-
const row = await db.prepare(
|
|
70
|
-
`SELECT user_id, expires_at, revoked_at
|
|
71
|
-
FROM refresh_tokens
|
|
72
|
-
WHERE token_hash = ? LIMIT 1`
|
|
73
|
-
).bind(tokenHash).first<RefreshTokenRecord>()
|
|
74
|
-
|
|
75
|
-
if (!row) return { valid: false }
|
|
76
|
-
if (row.revoked_at !== null) return { valid: false }
|
|
77
|
-
if (row.expires_at < now) return { valid: false }
|
|
78
|
-
|
|
79
|
-
return { valid: true, userId: row.user_id }
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* Revoca un refresh token impostando revoked_at.
|
|
84
|
-
* Il token non potrà più essere usato per il refresh.
|
|
85
|
-
*/
|
|
86
|
-
export async function revokeRefreshToken(
|
|
87
|
-
db: D1Database,
|
|
88
|
-
token: string
|
|
89
|
-
): Promise<boolean> {
|
|
90
|
-
const tokenHash = await hashRefreshToken(token)
|
|
91
|
-
const now = Math.floor(Date.now() / 1000)
|
|
92
|
-
|
|
93
|
-
const result = await db.prepare(
|
|
94
|
-
`UPDATE refresh_tokens
|
|
95
|
-
SET revoked_at = ?
|
|
96
|
-
WHERE token_hash = ?
|
|
97
|
-
AND revoked_at IS NULL
|
|
98
|
-
AND expires_at >= ?`
|
|
99
|
-
).bind(now, tokenHash, now).run()
|
|
100
|
-
|
|
101
|
-
const changes = (result as unknown as { meta?: { changes?: number } })?.meta?.changes ?? 0
|
|
102
|
-
return changes > 0
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
* Genera JWT access token con scadenza breve (15 min).
|
|
107
|
-
* Payload: sub (userId), email, name (opzionale). Algoritmo HS256.
|
|
108
|
-
*/
|
|
109
|
-
export async function generateAccessToken(
|
|
110
|
-
userId: string,
|
|
111
|
-
email: string,
|
|
112
|
-
secret: string,
|
|
113
|
-
options: JwtTokenOptions = {},
|
|
114
|
-
name?: string
|
|
115
|
-
): Promise<string> {
|
|
116
|
-
const payload: Record<string, string> = { email }
|
|
117
|
-
if (name) payload.name = name
|
|
118
|
-
const secretBytes = new TextEncoder().encode(secret)
|
|
119
|
-
let jwt = new SignJWT(payload)
|
|
120
|
-
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
|
|
121
|
-
.setSubject(userId)
|
|
122
|
-
.setIssuedAt()
|
|
123
|
-
.setExpirationTime('15m')
|
|
124
|
-
if (options.issuer) jwt = jwt.setIssuer(options.issuer)
|
|
125
|
-
if (options.audience) jwt = jwt.setAudience(options.audience)
|
|
126
|
-
return jwt.sign(secretBytes)
|
|
127
|
-
}
|
|
1
|
+
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
+
|
|
3
|
+
export function generateRefreshToken(): string {
|
|
4
|
+
return crypto.randomUUID()
|
|
5
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ITokenService, IssueTokenOptions, JwtClaims } from '@beechcms/core'
|
|
2
|
+
|
|
3
|
+
const TEST_TOKEN_PREFIX = 'test:'
|
|
4
|
+
|
|
5
|
+
export class StaticTokenService implements ITokenService {
|
|
6
|
+
private readonly issuedClaims = new Map<string, JwtClaims>()
|
|
7
|
+
|
|
8
|
+
async issue(claims: JwtClaims, _options?: IssueTokenOptions): Promise<string> {
|
|
9
|
+
const token = TEST_TOKEN_PREFIX + claims.sub
|
|
10
|
+
this.issuedClaims.set(token, claims)
|
|
11
|
+
return token
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async verify(token: string): Promise<JwtClaims | null> {
|
|
15
|
+
if (!token.startsWith(TEST_TOKEN_PREFIX)) return null
|
|
16
|
+
return this.issuedClaims.get(token) ?? null
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { SystemClock } from '@beechcms/core'
|
|
3
|
+
import { JoseTokenService } from './jose-token-service'
|
|
4
|
+
import { StaticTokenService } from './static-token-service'
|
|
5
|
+
|
|
6
|
+
const TEST_SECRET = 'super-secret-key-used-only-in-the-vitest-suite-min-length'
|
|
7
|
+
|
|
8
|
+
describe('JoseTokenService', () => {
|
|
9
|
+
const service = new JoseTokenService(TEST_SECRET, {}, SystemClock)
|
|
10
|
+
|
|
11
|
+
it('issue returns a three-part JWT string', async () => {
|
|
12
|
+
const token = await service.issue({ sub: 'user-1', email: 'a@b.com' })
|
|
13
|
+
expect(token.split('.')).toHaveLength(3)
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
it('verify returns the original claims for a valid token', async () => {
|
|
17
|
+
const token = await service.issue({ sub: 'user-1', email: 'a@b.com' })
|
|
18
|
+
const claims = await service.verify(token)
|
|
19
|
+
expect(claims?.sub).toBe('user-1')
|
|
20
|
+
expect(claims?.email).toBe('a@b.com')
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('verify returns null for a malformed token', async () => {
|
|
24
|
+
expect(await service.verify('not.a.valid.jwt')).toBeNull()
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('verify returns null for a token signed with a different secret', async () => {
|
|
28
|
+
const otherService = new JoseTokenService('completely-different-secret-key-xyz', {}, SystemClock)
|
|
29
|
+
const token = await otherService.issue({ sub: 'user-1' })
|
|
30
|
+
expect(await service.verify(token)).toBeNull()
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('verify returns null for an expired token (ttlSeconds = -1)', async () => {
|
|
34
|
+
const token = await service.issue({ sub: 'user-1' }, { ttlSeconds: -1 })
|
|
35
|
+
expect(await service.verify(token)).toBeNull()
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it('issuer mismatch causes verify to return null', async () => {
|
|
39
|
+
const issuerA = new JoseTokenService(TEST_SECRET, { issuer: 'issuer-a' }, SystemClock)
|
|
40
|
+
const issuerB = new JoseTokenService(TEST_SECRET, { issuer: 'issuer-b' }, SystemClock)
|
|
41
|
+
const token = await issuerA.issue({ sub: 'user-1' })
|
|
42
|
+
expect(await issuerB.verify(token)).toBeNull()
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it('custom TTL is respected — token issued with longer TTL verifies successfully', async () => {
|
|
46
|
+
const token = await service.issue({ sub: 'user-1' }, { ttlSeconds: 3600 })
|
|
47
|
+
const claims = await service.verify(token)
|
|
48
|
+
expect(claims?.sub).toBe('user-1')
|
|
49
|
+
})
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
describe('StaticTokenService', () => {
|
|
53
|
+
it('issue returns "test:" + claims.sub', async () => {
|
|
54
|
+
const service = new StaticTokenService()
|
|
55
|
+
expect(await service.issue({ sub: 'abc' })).toBe('test:abc')
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('verify returns the stored claims for an issued token', async () => {
|
|
59
|
+
const service = new StaticTokenService()
|
|
60
|
+
await service.issue({ sub: 'abc', email: 'x@y.com' })
|
|
61
|
+
const claims = await service.verify('test:abc')
|
|
62
|
+
expect(claims?.email).toBe('x@y.com')
|
|
63
|
+
expect(claims?.sub).toBe('abc')
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
it('verify returns null for an unknown test sub', async () => {
|
|
67
|
+
const service = new StaticTokenService()
|
|
68
|
+
expect(await service.verify('test:unknown')).toBeNull()
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
it('verify returns null for a token that does not start with "test:"', async () => {
|
|
72
|
+
const service = new StaticTokenService()
|
|
73
|
+
expect(await service.verify('real.jwt.token')).toBeNull()
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it('each StaticTokenService instance has its own isolated claims store', async () => {
|
|
77
|
+
const serviceA = new StaticTokenService()
|
|
78
|
+
const serviceB = new StaticTokenService()
|
|
79
|
+
await serviceA.issue({ sub: 'user-1' })
|
|
80
|
+
expect(await serviceB.verify('test:user-1')).toBeNull()
|
|
81
|
+
})
|
|
82
|
+
})
|