@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
@@ -9,7 +9,7 @@
9
9
  <!-- Poppins: pesi normali + italic. Inter: fallback con piena copertura degli stili. -->
10
10
  <link href="https://fonts.googleapis.com/css2?family=Inter:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&family=Poppins:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet" />
11
11
  <title>dashboard</title>
12
- <script type="module" crossorigin src="/admin/assets/index-FQ6JhvRH.js"></script>
12
+ <script type="module" crossorigin src="/admin/assets/index-CH13idU1.js"></script>
13
13
  <link rel="stylesheet" crossorigin href="/admin/assets/index-CewtCjom.css">
14
14
  </head>
15
15
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@beechcms/api",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/factory.ts"
@@ -22,7 +22,7 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@aws-sdk/client-s3": "^3.995.0",
25
- "@beechcms/core": "^0.4.0",
25
+ "@beechcms/core": "^0.4.1",
26
26
  "bcryptjs": "^2.4.3",
27
27
  "hono": "^4.11.9",
28
28
  "jose": "^6.1.3"
@@ -0,0 +1,20 @@
1
+ import bcrypt from 'bcryptjs'
2
+ import type { IHashProvider } from '@beechcms/core'
3
+
4
+ const DEFAULT_BCRYPT_ROUNDS = 10
5
+
6
+ export class BcryptHashProvider implements IHashProvider {
7
+ private readonly saltRounds: number
8
+
9
+ constructor(saltRounds: number = DEFAULT_BCRYPT_ROUNDS) {
10
+ this.saltRounds = saltRounds
11
+ }
12
+
13
+ async hash(plaintextPassword: string): Promise<string> {
14
+ return bcrypt.hash(plaintextPassword, this.saltRounds)
15
+ }
16
+
17
+ async verify(plaintextPassword: string, storedHash: string): Promise<boolean> {
18
+ return bcrypt.compare(plaintextPassword, storedHash)
19
+ }
20
+ }
@@ -1,10 +1,10 @@
1
- /** Messaggi di errore API auth - usati da handler e test */
1
+ /** API auth error messages - used by handlers and tests */
2
2
  export const AUTH_ERRORS = {
3
3
  INVALID_REQUEST: 'Invalid request',
4
4
  INVALID_CREDENTIALS: 'Invalid credentials',
5
5
  DATABASE_ERROR: 'Database error',
6
- /** Messaggio generico per errori 500 - non rivela dettagli del sistema */
6
+ /** Generic message for 500 errors - does not reveal system details */
7
7
  GENERIC_ERROR: 'An error occurred',
8
- /** Rate limit superato */
8
+ /** Rate limit exceeded */
9
9
  RATE_LIMIT_EXCEEDED: 'Too many requests',
10
10
  } as const
@@ -0,0 +1,19 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { generateRefreshToken } from './refresh'
3
+
4
+ describe('generateRefreshToken', () => {
5
+ it('returns a non-empty string', () => {
6
+ expect(generateRefreshToken().length).toBeGreaterThan(0)
7
+ })
8
+
9
+ it('returns a UUID-shaped value (8-4-4-4-12 hex groups)', () => {
10
+ expect(generateRefreshToken()).toMatch(
11
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
12
+ )
13
+ })
14
+
15
+ it('returns a different token on every call', () => {
16
+ const tokens = new Set(Array.from({ length: 10 }, () => generateRefreshToken()))
17
+ expect(tokens.size).toBe(10)
18
+ })
19
+ })
@@ -0,0 +1,46 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { InMemoryHashProvider } from './in-memory-hash-provider'
3
+ import { BcryptHashProvider } from './bcrypt-hash-provider'
4
+
5
+ describe('InMemoryHashProvider', () => {
6
+ const provider = new InMemoryHashProvider()
7
+
8
+ it('hash returns the HASH: prefix concatenated with the plaintext', async () => {
9
+ expect(await provider.hash('mypassword')).toBe('HASH:mypassword')
10
+ })
11
+
12
+ it('verify returns true when the plaintext matches the stored hash', async () => {
13
+ const hash = await provider.hash('correct')
14
+ expect(await provider.verify('correct', hash)).toBe(true)
15
+ })
16
+
17
+ it('verify returns false when the plaintext does not match', async () => {
18
+ const hash = await provider.hash('correct')
19
+ expect(await provider.verify('wrong', hash)).toBe(false)
20
+ })
21
+
22
+ it('verify returns false for a string that does not follow the HASH: format', async () => {
23
+ expect(await provider.verify('anything', 'not-a-prefixed-hash')).toBe(false)
24
+ })
25
+ })
26
+
27
+ describe('BcryptHashProvider', () => {
28
+ // Use 4 salt rounds so the test runs in milliseconds.
29
+ const provider = new BcryptHashProvider(4)
30
+
31
+ it('hash and verify roundtrip: correct password returns true', async () => {
32
+ const hash = await provider.hash('secure-password')
33
+ expect(await provider.verify('secure-password', hash)).toBe(true)
34
+ })
35
+
36
+ it('verify returns false for an incorrect password', async () => {
37
+ const hash = await provider.hash('correct')
38
+ expect(await provider.verify('incorrect', hash)).toBe(false)
39
+ })
40
+
41
+ it('verify returns false against the DUMMY_PASSWORD_HASH for any plaintext', async () => {
42
+ // The dummy hash is used for timing-attack mitigation; it must not match real passwords.
43
+ const dummyHash = '$2a$10$SbkRFOafACxVM2ahxerVDu3tSkCXWm29b62WdB.4WGG02Qjsfzni6'
44
+ expect(await provider.verify('password123', dummyHash)).toBe(false)
45
+ })
46
+ })
@@ -0,0 +1,13 @@
1
+ import type { IHashProvider } from '@beechcms/core'
2
+
3
+ const HASH_PREFIX = 'HASH:'
4
+
5
+ export class InMemoryHashProvider implements IHashProvider {
6
+ async hash(plaintextPassword: string): Promise<string> {
7
+ return HASH_PREFIX + plaintextPassword
8
+ }
9
+
10
+ async verify(plaintextPassword: string, storedHash: string): Promise<boolean> {
11
+ return storedHash === HASH_PREFIX + plaintextPassword
12
+ }
13
+ }
@@ -0,0 +1,55 @@
1
+ import { SignJWT, jwtVerify } from 'jose'
2
+ import type { ITokenService, IssueTokenOptions, JwtClaims, IClock } from '@beechcms/core'
3
+
4
+ const DEFAULT_TOKEN_TTL_SECONDS = 900
5
+ const DEFAULT_ALGORITHM = 'HS256' as const
6
+
7
+ export interface JoseTokenServiceConfig {
8
+ issuer?: string
9
+ audience?: string
10
+ algorithm?: 'HS256' | 'HS384' | 'HS512'
11
+ }
12
+
13
+ export class JoseTokenService implements ITokenService {
14
+ private readonly secretBytes: Uint8Array
15
+ private readonly config: JoseTokenServiceConfig
16
+ private readonly clock: IClock
17
+
18
+ constructor(secret: string, config: JoseTokenServiceConfig, clock: IClock) {
19
+ this.secretBytes = new TextEncoder().encode(secret)
20
+ this.config = config
21
+ this.clock = clock
22
+ }
23
+
24
+ async issue(claims: JwtClaims, options?: IssueTokenOptions): Promise<string> {
25
+ const { sub, ...remainingClaims } = claims
26
+ const ttlSeconds = options?.ttlSeconds ?? DEFAULT_TOKEN_TTL_SECONDS
27
+ const algorithm = this.config.algorithm ?? DEFAULT_ALGORITHM
28
+ const issuedAtSeconds = this.clock.nowSeconds()
29
+
30
+ let builder = new SignJWT(remainingClaims)
31
+ .setProtectedHeader({ alg: algorithm, typ: 'JWT' })
32
+ .setSubject(sub)
33
+ .setIssuedAt(issuedAtSeconds)
34
+ .setExpirationTime(issuedAtSeconds + ttlSeconds)
35
+
36
+ if (this.config.issuer) builder = builder.setIssuer(this.config.issuer)
37
+ if (this.config.audience) builder = builder.setAudience(this.config.audience)
38
+
39
+ return builder.sign(this.secretBytes)
40
+ }
41
+
42
+ async verify(token: string): Promise<JwtClaims | null> {
43
+ try {
44
+ const algorithm = this.config.algorithm ?? DEFAULT_ALGORITHM
45
+ const { payload } = await jwtVerify(token, this.secretBytes, {
46
+ algorithms: [algorithm],
47
+ issuer: this.config.issuer,
48
+ audience: this.config.audience,
49
+ })
50
+ return payload as JwtClaims
51
+ } catch {
52
+ return null
53
+ }
54
+ }
55
+ }
@@ -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,19 +1,18 @@
1
1
  /// <reference types="@cloudflare/workers-types" />
2
- import bcrypt from 'bcryptjs'
2
+ import type { IHashProvider } from '@beechcms/core'
3
3
 
4
4
  export type LoginCredentials = {
5
5
  email: string
6
6
  password: string
7
7
  }
8
8
 
9
- export type UserRecord = {
10
- id: string
11
- email: string
12
- password_hash: string
13
- }
14
-
15
- /** Regex per validare formato email (deve contenere @ e punto dopo @) */
16
- const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
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
17
16
 
18
17
  /** Lunghezza minima password (caratteri) */
19
18
  const MIN_PASSWORD_LENGTH = 8
@@ -52,6 +51,7 @@ export function parseLoginBody(body: unknown): LoginCredentials | null {
52
51
  */
53
52
  export function validateLoginInput(email: string, password: string): boolean {
54
53
  return (
54
+ email.length <= MAX_EMAIL_LENGTH &&
55
55
  EMAIL_REGEX.test(email) &&
56
56
  password.length >= MIN_PASSWORD_LENGTH &&
57
57
  password.length <= MAX_PASSWORD_LENGTH
@@ -59,33 +59,16 @@ export function validateLoginInput(email: string, password: string): boolean {
59
59
  }
60
60
 
61
61
  /**
62
- * Cerca un utente nel database D1 per email.
63
- * @param db - Istanza D1Database
64
- * @param email - Email dell'utente
65
- * @returns UserRecord se trovato, null altrimenti
66
- */
67
- export async function findUserByEmail(
68
- db: D1Database,
69
- email: string
70
- ): Promise<UserRecord | null> {
71
- // IMPORTANTE: non interpolare mai direttamente l'email (o altri input utente)
72
- // dentro la stringa SQL, usa sempre il placeholder "?" con .bind(...) per evitare SQL injection.
73
- const stmt = db.prepare(
74
- 'SELECT id, email, password_hash FROM users WHERE email = ? LIMIT 1'
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.
62
+ * Verifica che la password in chiaro corrisponda all'hash salvato.
82
63
  * @param plainPassword - Password in chiaro
83
- * @param hash - Hash bcrypt salvato nel DB
64
+ * @param hash - Hash salvato nel DB
65
+ * @param hashProvider - Provider usato per la comparazione costante-time
84
66
  * @returns true se la password è corretta
85
67
  */
86
68
  export async function verifyPassword(
87
69
  plainPassword: string,
88
- hash: string
70
+ hash: string,
71
+ hashProvider: IHashProvider
89
72
  ): Promise<boolean> {
90
- return bcrypt.compare(plainPassword, hash)
73
+ return hashProvider.verify(plainPassword, hash)
91
74
  }
@@ -1,127 +1,5 @@
1
1
  /// <reference types="@cloudflare/workers-types" />
2
- import { SignJWT } from 'jose'
3
2
 
4
- /** Secondi in un giorno (per calcolo scadenza) */
5
- const SECONDS_PER_DAY = 24 * 60 * 60
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
3
  export function generateRefreshToken(): string {
23
4
  return crypto.randomUUID()
24
5
  }
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
- }
@@ -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
+ })