@humanonlyweb/create-nuxtflare 0.1.3 → 0.2.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 (70) hide show
  1. package/README.md +3 -1
  2. package/dist/cli.js +3 -1
  3. package/dist/template/.github/workflows/ci.yml +3 -1
  4. package/dist/template/CLAUDE.md +4 -2
  5. package/dist/template/app/components/turnstile-widget.vue +81 -0
  6. package/dist/template/app/composables/use-auth.ts +418 -0
  7. package/dist/template/app/pages/account.vue +125 -11
  8. package/dist/template/app/pages/email/[token].vue +18 -0
  9. package/dist/template/app/pages/forgot-password.vue +28 -0
  10. package/dist/template/app/pages/login.vue +9 -73
  11. package/dist/template/app/pages/register.vue +4 -26
  12. package/dist/template/app/pages/reset/[token].vue +31 -0
  13. package/dist/template/app/pages/verify/[token].vue +18 -0
  14. package/dist/template/nuxt.config.ts +4 -0
  15. package/dist/template/package.json +2 -0
  16. package/dist/template/scripts/admin-password.ts +13 -6
  17. package/dist/template/scripts/migrate.ts +67 -0
  18. package/dist/template/server/api/account/email/index.post.ts +1 -1
  19. package/dist/template/server/api/account/index.delete.ts +2 -2
  20. package/dist/template/server/api/account/password.post.ts +8 -0
  21. package/dist/template/server/api/auth/email/index.post.ts +1 -1
  22. package/dist/template/server/api/auth/login/totp.post.ts +6 -2
  23. package/dist/template/server/api/auth/login.post.ts +4 -2
  24. package/dist/template/server/api/auth/register.post.ts +1 -1
  25. package/dist/template/server/api/auth/verify/index.post.ts +1 -1
  26. package/dist/template/server/app/admin/auth.ts +2 -1
  27. package/dist/template/server/app/features.ts +4 -3
  28. package/dist/template/server/app/identity/email-change.ts +44 -7
  29. package/dist/template/server/app/identity/identity.test.ts +70 -0
  30. package/dist/template/server/app/identity/lockout.ts +8 -3
  31. package/dist/template/server/app/identity/password-reset.ts +3 -1
  32. package/dist/template/server/app/identity/service.ts +149 -30
  33. package/dist/template/server/app/identity/sessions.ts +43 -20
  34. package/dist/template/server/app/identity/totp-crypto.ts +12 -5
  35. package/dist/template/server/app/identity/totp.ts +24 -15
  36. package/dist/template/server/app/identity/verification.ts +3 -1
  37. package/dist/template/server/app/maintenance/cleanup.test.ts +56 -0
  38. package/dist/template/server/app/maintenance/cleanup.ts +63 -0
  39. package/dist/template/server/core/db/atomic.ts +9 -11
  40. package/dist/template/server/core/db/migrations.ts +7 -0
  41. package/dist/template/server/core/db/migrator.ts +5 -1
  42. package/dist/template/server/core/http/body.ts +1 -1
  43. package/dist/template/server/core/http/handle.ts +89 -81
  44. package/dist/template/server/core/http/security.test.ts +38 -0
  45. package/dist/template/server/core/http/security.ts +17 -5
  46. package/dist/template/server/core/http/session.ts +15 -0
  47. package/dist/template/server/core/platform/crypto-and-window.test.ts +75 -0
  48. package/dist/template/server/core/platform/database.ts +16 -1
  49. package/dist/template/server/core/platform/pii.ts +5 -8
  50. package/dist/template/server/core/platform/rate-limiter-strict.ts +35 -5
  51. package/dist/template/server/core/platform/rate-limiter.ts +2 -2
  52. package/dist/template/server/core/platform/seal.ts +20 -21
  53. package/dist/template/server/core/platform/sliding-window.ts +11 -2
  54. package/dist/template/server/core/platform/tokens.ts +3 -1
  55. package/dist/template/server/middleware/00-security-headers.ts +8 -4
  56. package/dist/template/server/middleware/01-user-session.ts +17 -5
  57. package/dist/template/server/plugins/page-csp.ts +24 -4
  58. package/dist/template/server/plugins/sessions.ts +4 -2
  59. package/dist/template/server/routes/auth/github.get.ts +4 -3
  60. package/dist/template/server/routes/auth/google.get.ts +4 -2
  61. package/dist/template/server/tasks/cleanup.ts +15 -0
  62. package/dist/template/server/test/invariants.test.ts +4 -2
  63. package/dist/template/server/utils/define-validated-handler.ts +14 -12
  64. package/dist/template/shared/domain/errors.ts +1 -0
  65. package/dist/template/shared/types/auth.d.ts +1 -1
  66. package/dist/template/shared/utils/auth.ts +10 -4
  67. package/dist/template/shared/utils/paths.ts +2 -0
  68. package/dist/template/shared/utils/schema-validation.ts +1 -1
  69. package/dist/template/wrangler.json +17 -0
  70. package/package.json +1 -1
@@ -7,6 +7,7 @@ import { TotpCryptoError } from '#server/utils/errors'
7
7
  const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
8
8
  const STEP_SECONDS = 30
9
9
  const DIGITS = 6
10
+ const encoder = new TextEncoder()
10
11
 
11
12
  export const base32Encode = (bytes: Uint8Array): string => {
12
13
  let bits = 0
@@ -48,11 +49,9 @@ export const base32Decode = (text: string): Effect.Effect<Uint8Array, TotpCrypto
48
49
  return Effect.succeed(new Uint8Array(out))
49
50
  })
50
51
 
51
- /** One-time password for a counter (RFC 4226) using HMAC-SHA1 as authenticator apps expect. */
52
- export const hotp = (secret: Uint8Array, counter: number, digits = DIGITS): Effect.Effect<string, CryptoError.CryptoError, Mac.Mac> =>
52
+ const hotpWithKey = (key: Mac.Key, counter: number, digits = DIGITS): Effect.Effect<string, CryptoError.CryptoError, Mac.Mac> =>
53
53
  Effect.gen(function* () {
54
54
  const mac = yield* Mac.Mac
55
- const key = yield* Mac.key(Mac.hmacSha1, secret)
56
55
  const message = new Uint8Array(8)
57
56
 
58
57
  new DataView(message.buffer).setUint32(4, counter >>> 0)
@@ -65,6 +64,10 @@ export const hotp = (secret: Uint8Array, counter: number, digits = DIGITS): Effe
65
64
  return String(code % 10 ** digits).padStart(digits, '0')
66
65
  })
67
66
 
67
+ /** One-time password for a counter (RFC 4226) using HMAC-SHA1 as authenticator apps expect. */
68
+ export const hotp = (secret: Uint8Array, counter: number, digits = DIGITS): Effect.Effect<string, CryptoError.CryptoError, Mac.Mac> =>
69
+ Effect.flatMap(Mac.key(Mac.hmacSha1, secret), (key) => hotpWithKey(key, counter, digits))
70
+
68
71
  export const stepOf = (nowMs: number) => Math.floor(nowMs / 1000 / STEP_SECONDS)
69
72
 
70
73
  /**
@@ -77,8 +80,12 @@ export const verifyTotp = (secret: Uint8Array, code: string, lastStep: number):
77
80
 
78
81
  const now = stepOf(yield* nowMillis)
79
82
  const candidates = [now, now - 1, now + 1].filter((step) => step > lastStep)
80
- const codes = yield* Effect.forEach(candidates, (step) => hotp(secret, step), { concurrency: 'unbounded' })
81
- const matchedIndex = codes.indexOf(code)
83
+ if (!candidates.length) return undefined
84
+
85
+ const key = yield* Mac.key(Mac.hmacSha1, secret)
86
+ const codes = yield* Effect.forEach(candidates, (step) => hotpWithKey(key, step), { concurrency: 'unbounded' })
87
+ const provided = encoder.encode(code)
88
+ const matchedIndex = codes.findIndex((candidate) => Mac.timingSafeEqual(encoder.encode(candidate), provided))
82
89
 
83
90
  return matchedIndex === -1 ? undefined : candidates[matchedIndex]
84
91
  })
@@ -1,6 +1,6 @@
1
1
  import { Context, Effect, Layer, Redacted, Schema } from 'effect'
2
- import { Mac, SecureRandom } from 'effect/crypto'
3
- import { Base64Url } from 'effect/encoding'
2
+ import { Kdf, Mac, SecureRandom } from 'effect/crypto'
3
+ import { Base64Url, Hex } from 'effect/encoding'
4
4
 
5
5
  import type { RateLimited } from '#shared/domain/errors'
6
6
  import type { TotpStatus } from '#shared/utils/auth'
@@ -12,7 +12,6 @@ import { Database } from '#server/core/platform/database'
12
12
  import { PasswordHasher } from '#server/core/platform/password-hasher'
13
13
  import { Pii } from '#server/core/platform/pii'
14
14
  import { Seal } from '#server/core/platform/seal'
15
- import { Tokens } from '#server/core/platform/tokens'
16
15
  import { Conflict, Forbidden, Unauthorized, Unprocessable } from '#shared/domain/errors'
17
16
 
18
17
  import type { AuthUser } from './state'
@@ -91,18 +90,30 @@ export class Totp extends Context.Service<
91
90
  const hasher = yield* PasswordHasher
92
91
  const pii = yield* Pii
93
92
  const seal = yield* Seal
94
- const tokens = yield* Tokens
95
93
  const lockout = yield* LoginLockout
96
94
  const random = yield* SecureRandom.SecureRandom
97
95
  const mac = yield* Mac.Mac
98
-
99
- const challengeKey = yield* Effect.cached(seal.sha256(encoder.encode(`totp-challenge:${Redacted.value(config.appSecret)}`)))
96
+ const kdf = yield* Kdf.Kdf
97
+
98
+ const rawAppSecret = Redacted.value(config.appSecret)
99
+ if (rawAppSecret.length < 32) {
100
+ return yield* Effect.die(new Error('NUXT_APP_SECRET must be at least 32 characters (generate with `openssl rand -hex 32`).'))
101
+ }
102
+ const challengeKey = Hex.encode(
103
+ yield* kdf
104
+ .derive(Kdf.hkdfSha256, encoder.encode(rawAppSecret), {
105
+ salt: encoder.encode('nuxtflare:v1'),
106
+ info: encoder.encode(CHALLENGE_CONTEXT),
107
+ length: 32,
108
+ })
109
+ .pipe(Effect.orDie),
110
+ )
100
111
 
101
112
  const assertFeatureOn = () => (config.features.totp ? Effect.void : Effect.fail(new Forbidden({ message: 'Two-factor authentication is disabled.' })))
102
113
 
103
114
  const lockKey = (userId: string) => `totp:${userId}`
104
115
 
105
- const hashRecoveryCode = (code: string) => tokens.hash(`recovery:${code.trim().toLowerCase().replace(/[\s-]/g, '')}`)
116
+ const hashRecoveryCode = (code: string) => pii.index(`recovery:${code.trim().toLowerCase().replace(/[\s-]/g, '')}`)
106
117
 
107
118
  const loadUser = (userId: string) => db.first(UserTotpRow, `SELECT ${USER_COLUMNS} FROM users WHERE id = ?`, [userId]).pipe(Effect.orDie)
108
119
 
@@ -218,10 +229,10 @@ export class Totp extends Context.Service<
218
229
  }
219
230
 
220
231
  const recoveryCodes = yield* Effect.forEach(Array.from({ length: RECOVERY_CODES_COUNT }), () =>
221
- random.randomBytes(5).pipe(
232
+ random.randomBytes(10).pipe(
222
233
  Effect.map((bytes) => {
223
- const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')
224
- return `${hex.slice(0, 5)}-${hex.slice(5)}`
234
+ const hex = Hex.encode(bytes)
235
+ return `${hex.slice(0, 5)}-${hex.slice(5, 10)}-${hex.slice(10, 15)}-${hex.slice(15)}`
225
236
  }),
226
237
  ),
227
238
  )
@@ -290,9 +301,8 @@ export class Totp extends Context.Service<
290
301
 
291
302
  const issueChallenge = Effect.fn('Totp.issueChallenge')(function* (userId: string) {
292
303
  yield* assertFeatureOn()
293
- const key = yield* challengeKey
294
304
  const exp = (yield* nowMillis) + CHALLENGE_TTL_MS
295
- const bytes = yield* seal.seal(encoder.encode(JSON.stringify({ userId, exp })), key, CHALLENGE_CONTEXT).pipe(Effect.orDie)
305
+ const bytes = yield* seal.seal(encoder.encode(JSON.stringify({ userId, exp })), challengeKey, CHALLENGE_CONTEXT).pipe(Effect.orDie)
296
306
  return Base64Url.encode(bytes)
297
307
  })
298
308
 
@@ -320,8 +330,7 @@ export class Totp extends Context.Service<
320
330
  const raw = Base64Url.decode(challenge)
321
331
  if (raw._tag === 'Failure') return yield* invalid
322
332
 
323
- const key = yield* challengeKey
324
- const opened = yield* seal.open(raw.success, key, CHALLENGE_CONTEXT).pipe(Effect.option)
333
+ const opened = yield* seal.open(raw.success, challengeKey, CHALLENGE_CONTEXT).pipe(Effect.option)
325
334
  if (opened._tag === 'None') return yield* invalid
326
335
 
327
336
  const parsed = yield* Schema.decodeEffect(ChallengePayload)(decoder.decode(opened.value)).pipe(Effect.option)
@@ -357,5 +366,5 @@ export class Totp extends Context.Service<
357
366
  verifySecondFactor,
358
367
  })
359
368
  }),
360
- ).pipe(Layer.provide(Layer.mergeAll(SecureRandom.layerWebCrypto, Mac.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto)))))
369
+ ).pipe(Layer.provide(Layer.mergeAll(SecureRandom.layerWebCrypto, Kdf.layerWebCrypto, Mac.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto)))))
361
370
  }
@@ -76,7 +76,9 @@ export class EmailVerification extends Context.Service<
76
76
  .pipe(Effect.orDie)
77
77
 
78
78
  const rendered = yield* renderer.render(verificationEmail(`${config.appUrl}/verify/${token}`, config.appName))
79
- yield* mailer.send({ to: user.email, ...rendered }).pipe(Effect.ignore)
79
+ yield* mailer
80
+ .send({ to: user.email, ...rendered })
81
+ .pipe(Effect.catch((error) => Effect.logWarning(`Verification email failed (${error._tag}): ${error.message}`)))
80
82
  })
81
83
 
82
84
  const confirm = Effect.fn('EmailVerification.confirm')(function* (token: string) {
@@ -0,0 +1,56 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { LoginLockout } from '#server/app/identity/lockout'
4
+ import { makeTestLayer } from '#server/test/kit'
5
+
6
+ import { Maintenance } from './cleanup'
7
+
8
+ describe('maintenance cleanup and lockout decay', () => {
9
+ it('purges expired sessions, tokens, stale login failures, and abandoned unverified users while keeping active rows', async () => {
10
+ const { run, db } = await makeTestLayer()
11
+ const now = new Date().toISOString()
12
+ const past = new Date(Date.now() - 8 * 24 * 60 * 60_000).toISOString()
13
+ const staleLock = new Date(Date.now() - 20 * 60_000).toISOString()
14
+ const future = new Date(Date.now() + 24 * 60 * 60_000).toISOString()
15
+
16
+ await db.exec(
17
+ `INSERT INTO users (id, username, email, password_hash, email_status, email_verified_at, totp_status, created_at, last_active_at)
18
+ VALUES ('usr_old', 'olduser', 'old@example.com', 'fake:pw', 'unverified', NULL, 'off', '${past}', '${past}'),
19
+ ('usr_live', 'liveuser', 'live@example.com', 'fake:pw', 'verified', '${past}', 'off', '${past}', '${now}')`,
20
+ )
21
+ await db.exec(
22
+ `INSERT INTO sessions (id, user_id, device, created_at, last_seen_at, expires_at)
23
+ VALUES ('ses_expired', 'usr_live', 'Chrome', '${past}', '${past}', '${staleLock}'),
24
+ ('ses_active', 'usr_live', 'Chrome', '${now}', '${now}', '${future}')`,
25
+ )
26
+ await db.exec(
27
+ `INSERT INTO login_failures (subject, status, failures, locked_until, updated_at)
28
+ VALUES ('identity:stale', 'counting', 4, NULL, '${staleLock}'),
29
+ ('identity:fresh', 'counting', 2, NULL, '${now}')`,
30
+ )
31
+
32
+ const summary = await run(Maintenance.use((m) => m.purgeExpired))
33
+ expect(summary.sessions).toBe(1)
34
+ expect(summary.loginFailures).toBe(1)
35
+ expect(summary.staleUnverifiedUsers).toBe(1)
36
+
37
+ const remainingSessions = await db.prepare(`SELECT id FROM sessions`).all()
38
+ expect(remainingSessions).toHaveLength(1)
39
+ const remainingUsers = await db.prepare(`SELECT id FROM users`).all()
40
+ expect(remainingUsers).toHaveLength(1)
41
+ })
42
+
43
+ it('decays stale counting login_failures rows instead of locking on the next attempt', async () => {
44
+ const { run, db } = await makeTestLayer()
45
+ const stale = new Date(Date.now() - 20 * 60_000).toISOString()
46
+
47
+ await db.exec(
48
+ `INSERT INTO login_failures (subject, status, failures, locked_until, updated_at)
49
+ VALUES ('user:decay', 'counting', 4, NULL, '${stale}')`,
50
+ )
51
+
52
+ // Recording one more failure after the decay window resets count to 1 instead of locking
53
+ await run(LoginLockout.use((l) => l.recordFailure('user:decay')))
54
+ await expect(run(LoginLockout.use((l) => l.assertUnlocked('user:decay')))).resolves.toBeUndefined()
55
+ })
56
+ })
@@ -0,0 +1,63 @@
1
+ import { Context, DateTime, Effect, Layer } from 'effect'
2
+
3
+ import { AtomicBatch } from '#server/core/db/atomic'
4
+
5
+ const LOCKOUT_DECAY_MINUTES = 15
6
+ const UNVERIFIED_USER_RETENTION_DAYS = 7
7
+
8
+ export interface CleanupSummary {
9
+ readonly sessions: number
10
+ readonly adminSessions: number
11
+ readonly verificationTokens: number
12
+ readonly resetTokens: number
13
+ readonly emailChangeTokens: number
14
+ readonly loginFailures: number
15
+ readonly staleUnverifiedUsers: number
16
+ }
17
+
18
+ /** Purges expired sessions, tokens, stale lockout counters, and abandoned unverified accounts in one atomic D1 batch. */
19
+ export class Maintenance extends Context.Service<Maintenance, { readonly purgeExpired: Effect.Effect<CleanupSummary> }>()('app/maintenance/Maintenance') {
20
+ static readonly layer = Layer.effect(
21
+ Maintenance,
22
+ Effect.gen(function* () {
23
+ const atomic = yield* AtomicBatch
24
+
25
+ const purgeExpired = Effect.gen(function* () {
26
+ const now = yield* DateTime.now
27
+ const nowStr = DateTime.formatIso(now)
28
+ const lockoutCutoff = DateTime.formatIso(DateTime.subtract(now, { minutes: LOCKOUT_DECAY_MINUTES }))
29
+ const unverifiedCutoff = DateTime.formatIso(DateTime.subtract(now, { days: UNVERIFIED_USER_RETENTION_DAYS }))
30
+
31
+ const [sessions, adminSessions, verificationTokens, resetTokens, emailChangeTokens, loginFailures, staleUnverifiedUsers] = yield* atomic
32
+ .run([
33
+ { sql: `DELETE FROM sessions WHERE expires_at <= ?`, params: [nowStr] },
34
+ { sql: `DELETE FROM admin_sessions WHERE expires_at <= ?`, params: [nowStr] },
35
+ { sql: `DELETE FROM email_verification_tokens WHERE expires_at <= ?`, params: [nowStr] },
36
+ { sql: `DELETE FROM password_reset_tokens WHERE expires_at <= ?`, params: [nowStr] },
37
+ { sql: `DELETE FROM email_change_tokens WHERE expires_at <= ?`, params: [nowStr] },
38
+ {
39
+ sql: `DELETE FROM login_failures WHERE (status = 'locked' AND locked_until <= ?) OR (status = 'counting' AND updated_at <= ?)`,
40
+ params: [nowStr, lockoutCutoff],
41
+ },
42
+ {
43
+ sql: `DELETE FROM users WHERE email_status = 'unverified' AND google_sub IS NULL AND github_id IS NULL AND created_at <= ?`,
44
+ params: [unverifiedCutoff],
45
+ },
46
+ ])
47
+ .pipe(Effect.orDie)
48
+
49
+ return {
50
+ sessions: sessions?.changes ?? 0,
51
+ adminSessions: adminSessions?.changes ?? 0,
52
+ verificationTokens: verificationTokens?.changes ?? 0,
53
+ resetTokens: resetTokens?.changes ?? 0,
54
+ emailChangeTokens: emailChangeTokens?.changes ?? 0,
55
+ loginFailures: loginFailures?.changes ?? 0,
56
+ staleUnverifiedUsers: staleUnverifiedUsers?.changes ?? 0,
57
+ } satisfies CleanupSummary
58
+ }).pipe(Effect.withSpan('Maintenance.purgeExpired'))
59
+
60
+ return Maintenance.of({ purgeExpired })
61
+ }),
62
+ )
63
+ }
@@ -1,6 +1,6 @@
1
1
  import type { Database as Db0 } from 'db0'
2
2
 
3
- import { Context, Effect, Layer, Schema } from 'effect'
3
+ import { Context, Effect, Layer, Schema, Semaphore } from 'effect'
4
4
 
5
5
  import { DatabaseError } from '#server/core/platform/database'
6
6
  import { readKey } from '#shared/utils/unknown'
@@ -50,11 +50,11 @@ export class AtomicBatch extends Context.Service<
50
50
  AtomicBatch.of({ run, runGuarded: makeRunGuarded(run) })
51
51
 
52
52
  static readonly layerFor = (db: Db0) => {
53
- let queue: Promise<unknown> = Promise.resolve()
53
+ const lock = Semaphore.makeUnsafe(1)
54
54
  const run = (statements: ReadonlyArray<Statement>) =>
55
- Effect.tryPromise({
56
- try: () => {
57
- const job = queue.then(async () => {
55
+ lock.withPermit(
56
+ Effect.tryPromise({
57
+ try: async () => {
58
58
  await db.exec('BEGIN')
59
59
  try {
60
60
  const applied: Applied[] = []
@@ -74,12 +74,10 @@ export class AtomicBatch extends Context.Service<
74
74
  await db.exec('ROLLBACK')
75
75
  throw error
76
76
  }
77
- })
78
- queue = job.catch(() => undefined)
79
- return job
80
- },
81
- catch: failure,
82
- })
77
+ },
78
+ catch: failure,
79
+ }),
80
+ )
83
81
 
84
82
  return Layer.succeed(AtomicBatch, AtomicBatch.make(run))
85
83
  }
@@ -68,11 +68,13 @@ export const migrations: ReadonlyArray<Migration> = [
68
68
  status TEXT NOT NULL CHECK (status IN ('counting', 'locked')),
69
69
  failures INTEGER NOT NULL CHECK (failures >= 0),
70
70
  locked_until TEXT,
71
+ updated_at TEXT NOT NULL,
71
72
  CHECK (
72
73
  (status = 'counting' AND failures > 0 AND locked_until IS NULL) OR
73
74
  (status = 'locked' AND failures = 0 AND locked_until IS NOT NULL)
74
75
  )
75
76
  )`,
77
+ `CREATE INDEX idx_login_failures_updated ON login_failures (updated_at)`,
76
78
  `CREATE TABLE email_verification_tokens (
77
79
  token_hash TEXT PRIMARY KEY,
78
80
  user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
@@ -90,6 +92,7 @@ export const migrations: ReadonlyArray<Migration> = [
90
92
  )
91
93
  )`,
92
94
  `CREATE INDEX idx_email_verification_user ON email_verification_tokens (user_id, status)`,
95
+ `CREATE INDEX idx_email_verification_expires ON email_verification_tokens (expires_at)`,
93
96
  `CREATE TABLE password_reset_tokens (
94
97
  token_hash TEXT PRIMARY KEY,
95
98
  user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
@@ -106,6 +109,7 @@ export const migrations: ReadonlyArray<Migration> = [
106
109
  )
107
110
  )`,
108
111
  `CREATE INDEX idx_password_reset_user ON password_reset_tokens (user_id, status)`,
112
+ `CREATE INDEX idx_password_reset_expires ON password_reset_tokens (expires_at)`,
109
113
  `CREATE TABLE email_change_tokens (
110
114
  token_hash TEXT PRIMARY KEY,
111
115
  user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
@@ -123,6 +127,7 @@ export const migrations: ReadonlyArray<Migration> = [
123
127
  )
124
128
  )`,
125
129
  `CREATE INDEX idx_email_change_user ON email_change_tokens (user_id, status)`,
130
+ `CREATE INDEX idx_email_change_expires ON email_change_tokens (expires_at)`,
126
131
  `CREATE TABLE admins (
127
132
  email TEXT PRIMARY KEY CHECK (email = lower(trim(email))),
128
133
  password_hash TEXT NOT NULL,
@@ -136,6 +141,7 @@ export const migrations: ReadonlyArray<Migration> = [
136
141
  CHECK (expires_at > created_at)
137
142
  )`,
138
143
  `CREATE INDEX idx_admin_sessions_email ON admin_sessions (email)`,
144
+ `CREATE INDEX idx_admin_sessions_expires ON admin_sessions (expires_at)`,
139
145
  `CREATE TABLE admin_audit (
140
146
  id INTEGER PRIMARY KEY AUTOINCREMENT,
141
147
  actor_email TEXT NOT NULL,
@@ -144,6 +150,7 @@ export const migrations: ReadonlyArray<Migration> = [
144
150
  detail TEXT,
145
151
  created_at TEXT NOT NULL
146
152
  )`,
153
+ `CREATE INDEX idx_admin_audit_created ON admin_audit (created_at DESC)`,
147
154
  ],
148
155
  },
149
156
  ]
@@ -14,9 +14,13 @@ const Applied = Schema.Struct({ id: Schema.String })
14
14
  */
15
15
  const RACE_RETRY = Schedule.exponential('100 millis').pipe(Schedule.jittered)
16
16
 
17
- /** Applies pending migrations in order when the app layer is first built. Each migration and its record commit atomically. */
17
+ /**
18
+ * Applies pending migrations automatically in local `nuxt dev` so local work stays zero-config.
19
+ * Production Workers skip cold-start DDL writes — apply migrations at deploy time via `bun run db:migrate:remote`.
20
+ */
18
21
  export const MigratorLive = Layer.effectDiscard(
19
22
  Effect.gen(function* () {
23
+ if (!import.meta.dev) return
20
24
  const db = yield* Database
21
25
  const atomic = yield* AtomicBatch
22
26
  yield* db.run(`CREATE TABLE IF NOT EXISTS _migrations (id TEXT PRIMARY KEY, applied_at TEXT NOT NULL)`)
@@ -9,7 +9,7 @@ const JSON_LIMIT = 1024 * 1024
9
9
 
10
10
  /** Maximum body size in bytes for API writes, or undefined when the route reads no body. */
11
11
  export const bodyLimitFor = (method: string, path: string): number | undefined => {
12
- if (!['POST', 'PUT', 'PATCH'].includes(method) || !path.startsWith('/api/')) return undefined
12
+ if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) || !path.startsWith('/api/')) return undefined
13
13
  return JSON_LIMIT
14
14
  }
15
15
 
@@ -1,7 +1,7 @@
1
1
  import type { EventHandler, RequestEvent } from 'nuxt/server'
2
2
 
3
3
  import { getAccessIdentity } from '@humanonlyweb/cf-access'
4
- import { Cause, Effect, Exit, Schema } from 'effect'
4
+ import { Cause, Data, Effect, Exit, Schema } from 'effect'
5
5
  import { createError, defineHandler, deleteCookie, getCookie, setCookie, setResponseStatus } from 'nuxt/server'
6
6
 
7
7
  import type { AppServices } from '#server/core/app-layer'
@@ -13,7 +13,7 @@ import { AdminActor, AdminAuth, isLocalHost } from '#server/app/admin/auth'
13
13
  import { AppConfig } from '#server/core/platform/app-config'
14
14
  import { RateLimiter } from '#server/core/platform/rate-limiter'
15
15
  import { Turnstile } from '#server/core/platform/turnstile'
16
- import { defineValidatedHandler } from '#server/utils/define-validated-handler'
16
+ import { validateRequest } from '#server/utils/define-validated-handler'
17
17
  import { Forbidden, Unauthorized } from '#shared/domain/errors'
18
18
  import { ADMIN_COOKIE, ADMIN_SESSION_HOURS } from '#shared/utils/admin'
19
19
  import { readKey } from '#shared/utils/unknown'
@@ -87,7 +87,7 @@ export const compile = (schemas: RouteSchemas) => ({
87
87
  /** Redacts 64-hex single-use tokens from request paths before logging. */
88
88
  export const logPath = (url: string) => new URL(url).pathname.replace(/^(\/(?:verify|reset|email)\/)[0-9a-f]{64}/, '$1[token]')
89
89
 
90
- const crossSite = (event: RequestEvent) => UNSAFE_METHODS.has(event.req.method) && !isSameOriginRequest(event.req.headers, new URL(event.req.url).host)
90
+ const crossSite = (event: RequestEvent) => UNSAFE_METHODS.has(event.req.method) && !isSameOriginRequest(event.req.headers, new URL(event.req.url).origin)
91
91
 
92
92
  const crossSiteError = () => new Forbidden({ message: 'Cross-site requests are not allowed.' })
93
93
 
@@ -100,17 +100,35 @@ export const guards = (schemas: RouteSchemas, event: RequestEvent) =>
100
100
  if (schemas.captcha) yield* Turnstile.use((turnstile) => turnstile.verify(event.req.headers.get('x-turnstile-token') ?? undefined, ip))
101
101
  })
102
102
 
103
- const runEffect = async <A>(event: RequestEvent, program: Effect.Effect<A, ApiFailure | Schema.SchemaError, AppServices>, audience: Audience): Promise<A> => {
103
+ class RequestValidationError extends Data.TaggedError('RequestValidationError')<{ readonly httpError: unknown }> {}
104
+
105
+ const parseInput = (event: RequestEvent, validate: ReturnType<typeof compile>['validate']) =>
106
+ Effect.tryPromise({
107
+ try: () => validateRequest(event, validate),
108
+ catch: (httpError) => new RequestValidationError({ httpError }),
109
+ })
110
+
111
+ const runEffect = async <A>(
112
+ event: RequestEvent,
113
+ program: Effect.Effect<A, ApiFailure | Schema.SchemaError | RequestValidationError, AppServices>,
114
+ audience: Audience,
115
+ ): Promise<A> => {
104
116
  const exit = await runtime.runPromiseExit(program.pipe(Effect.annotateLogs({ method: event.req.method, path: logPath(event.req.url) })))
105
117
 
106
118
  if (Exit.isSuccess(exit)) return exit.value
107
119
 
108
120
  const failure = Cause.findError(exit.cause)
109
- if (failure._tag === 'Success' && isApiFailure(failure.success)) {
110
- if (audience === 'public' && isWithheld(failure.success._tag)) {
111
- await runtime.runPromise(Effect.logWarning(`${logPath(event.req.url)}: ${failure.success._tag}: ${failure.success.message}`))
121
+ if (failure._tag === 'Success') {
122
+ if (failure.success._tag === 'RequestValidationError') throw failure.success.httpError
123
+ if (isApiFailure(failure.success)) {
124
+ if (failure.success._tag === 'RateLimited' && failure.success.retryAfterSeconds !== undefined) {
125
+ event.res.headers.set('retry-after', String(failure.success.retryAfterSeconds))
126
+ }
127
+ if (audience === 'public' && isWithheld(failure.success._tag)) {
128
+ await runtime.runPromise(Effect.logWarning(`${logPath(event.req.url)}: ${failure.success._tag}: ${failure.success.message}`))
129
+ }
130
+ throw toHttpError(failure.success, audience)
112
131
  }
113
- throw toHttpError(failure.success, audience)
114
132
  }
115
133
 
116
134
  await runtime.runPromise(Effect.logError(Cause.pretty(exit.cause)))
@@ -119,7 +137,7 @@ const runEffect = async <A>(event: RequestEvent, program: Effect.Effect<A, ApiFa
119
137
 
120
138
  export const respond = async <D extends RouteSchemas>(
121
139
  event: RequestEvent,
122
- program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError, AppServices>,
140
+ program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError | RequestValidationError, AppServices>,
123
141
  audience: Audience,
124
142
  ): Promise<OutputOf<D>> => {
125
143
  const value = await runEffect(event, program, audience)
@@ -128,28 +146,28 @@ export const respond = async <D extends RouteSchemas>(
128
146
  return value as OutputOf<D>
129
147
  }
130
148
 
131
- /** Public route: same-origin check on unsafe methods, rate limit + Turnstile before body parsing, then schema validation and Effect program. */
149
+ /** Public route: same-origin check on unsafe methods, then single Effect pass for rate limit + Turnstile, input validation, handler, and response encoding. */
132
150
  export const handlePublic = <const D extends RouteSchemas>(
133
151
  schemas: D,
134
152
  run: (input: InputOf<D>, event: RequestEvent) => Effect.Effect<OutputOf<D>, ApiFailure, AppServices>,
135
153
  ): EventHandler<Promise<OutputOf<D>>> => {
136
154
  const { validate, encode } = compile(schemas)
137
- const validated = defineValidatedHandler({
138
- validate,
139
- handler: async (event, input) => {
140
- // `validate` was compiled from the same schemas.
141
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion
142
- const ran = crossSite(event) ? Effect.fail(crossSiteError()) : run(input as InputOf<D>, event)
143
- const program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError, AppServices> = encode ? Effect.flatMap(ran, encode) : ran
144
- const value = await respond<D>(event, program, 'public')
145
- if (!schemas.response) setResponseStatus(event, 204)
146
- return value
147
- },
148
- })
149
155
  return defineHandler<Promise<OutputOf<D>>>(async (event) => {
150
- if (crossSite(event)) return respond<D>(event, Effect.fail(crossSiteError()), 'public')
151
- if (schemas.limit || schemas.captcha) await respond<D>(event, guards(schemas, event), 'public')
152
- return validated(event)
156
+ if (crossSite(event)) throw toHttpError(crossSiteError(), 'public')
157
+ const value = await respond<D>(
158
+ event,
159
+ Effect.gen(function* () {
160
+ if (schemas.limit || schemas.captcha) yield* guards(schemas, event)
161
+ const input = yield* parseInput(event, validate)
162
+ // `validate` was compiled from the same schemas.
163
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
164
+ const out = yield* run(input as InputOf<D>, event)
165
+ return encode ? yield* encode(out) : out
166
+ }),
167
+ 'public',
168
+ )
169
+ if (!schemas.response) setResponseStatus(event, 204)
170
+ return value
153
171
  })
154
172
  }
155
173
 
@@ -169,40 +187,28 @@ export const handleAuthed = <const D extends RouteSchemas>(
169
187
  const verificationPolicy: VerificationPolicy = options.verification ?? 'required'
170
188
  const { validate, encode } = compile(schemas)
171
189
 
172
- const checkAccess = (event: RequestEvent) =>
173
- Effect.gen(function* () {
174
- const user = requestUser(event)
175
- if (!user) return yield* new Unauthorized({ message: 'Please sign in again.' })
176
- const config = yield* AppConfig
177
- if (verificationPolicy === 'required' && config.features.emailVerificationRequired && user.emailStatus !== 'verified') {
178
- return yield* new Forbidden({ message: UNCONFIRMED })
179
- }
180
- return user
181
- })
182
-
183
- const validated = defineValidatedHandler({
184
- validate,
185
- handler: async (event, input) => {
186
- const program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError, AppServices> = Effect.gen(function* () {
187
- const user = yield* checkAccess(event)
188
- // `validate` was compiled from the same schemas.
189
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion
190
- const value = yield* run(input as InputOf<D>, event).pipe(Effect.provideService(UserActor, user))
191
- return encode ? yield* encode(value) : value
192
- })
193
- const value = await respond<D>(event, program, 'authed')
194
- if (!schemas.response) setResponseStatus(event, 204)
195
- return value
196
- },
197
- })
198
-
199
190
  return defineHandler<Promise<OutputOf<D>>>(async (event) => {
200
- if (crossSite(event)) return respond<D>(event, Effect.fail(crossSiteError()), 'public')
191
+ if (crossSite(event)) throw toHttpError(crossSiteError(), 'public')
201
192
  const user = requestUser(event)
202
- if (!user) return respond<D>(event, Effect.fail(new Unauthorized({ message: 'Please sign in again.' })), 'public')
203
- await runEffect(event, checkAccess(event), 'authed')
204
- if (schemas.limit || schemas.captcha) await respond<D>(event, guards(schemas, event), 'authed')
205
- return validated(event)
193
+ if (!user) throw toHttpError(new Unauthorized({ message: 'Please sign in again.' }), 'public')
194
+ const value = await respond<D>(
195
+ event,
196
+ Effect.gen(function* () {
197
+ const config = yield* AppConfig
198
+ if (verificationPolicy === 'required' && config.features.emailVerificationRequired && user.emailStatus !== 'verified') {
199
+ return yield* new Forbidden({ message: UNCONFIRMED })
200
+ }
201
+ if (schemas.limit || schemas.captcha) yield* guards(schemas, event)
202
+ const input = yield* parseInput(event, validate)
203
+ // `validate` was compiled from the same schemas.
204
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
205
+ const out = yield* run(input as InputOf<D>, event).pipe(Effect.provideService(UserActor, user))
206
+ return encode ? yield* encode(out) : out
207
+ }),
208
+ 'authed',
209
+ )
210
+ if (!schemas.response) setResponseStatus(event, 204)
211
+ return value
206
212
  })
207
213
  }
208
214
 
@@ -219,39 +225,26 @@ export const handleAdmin = <const D extends RouteSchemas>(
219
225
  ): EventHandler<Promise<OutputOf<D>>> => {
220
226
  const gate: AdminGate = options.gate ?? 'access-and-session'
221
227
  const { validate, encode } = compile(schemas)
222
- const actors = new WeakMap<RequestEvent, { readonly email: string }>()
223
-
224
- const validated = defineValidatedHandler({
225
- validate,
226
- handler: async (event, input) => {
227
- const program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError, AppServices> = Effect.gen(function* () {
228
- const actor = actors.get(event)
229
- if (!actor) return yield* new Unauthorized({ message: 'Sign in to the admin.' })
230
- // `validate` was compiled from the same schemas.
231
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion
232
- const value = yield* run(input as InputOf<D>, event).pipe(Effect.provideService(AdminActor, actor))
233
- return encode ? yield* encode(value) : value
234
- })
235
- const value = await respond<D>(event, program, 'authed')
236
- if (!schemas.response) setResponseStatus(event, 204)
237
- return value
238
- },
239
- })
240
228
 
241
229
  return defineHandler<Promise<OutputOf<D>>>(async (event) => {
242
- if (crossSite(event)) return respond<D>(event, Effect.fail(crossSiteError()), 'public')
243
- const actor = await runEffect(
230
+ if (crossSite(event)) throw toHttpError(crossSiteError(), 'public')
231
+ const value = await respond<D>(
244
232
  event,
245
233
  Effect.gen(function* () {
246
234
  const auth = yield* AdminAuth
247
235
  const accessEmail = yield* auth.gate(getAccessIdentity(event))
248
- return gate === 'access-only' ? { email: accessEmail } : yield* auth.session(accessEmail, getCookie(event, ADMIN_COOKIE))
236
+ const actor = gate === 'access-only' ? { email: accessEmail } : yield* auth.session(accessEmail, getCookie(event, ADMIN_COOKIE))
237
+ if (schemas.limit || schemas.captcha) yield* guards(schemas, event)
238
+ const input = yield* parseInput(event, validate)
239
+ // `validate` was compiled from the same schemas.
240
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
241
+ const out = yield* run(input as InputOf<D>, event).pipe(Effect.provideService(AdminActor, actor))
242
+ return encode ? yield* encode(out) : out
249
243
  }),
250
244
  'authed',
251
245
  )
252
- actors.set(event, actor)
253
- if (schemas.limit || schemas.captcha) await respond<D>(event, guards(schemas, event), 'authed')
254
- return validated(event)
246
+ if (!schemas.response) setResponseStatus(event, 204)
247
+ return value
255
248
  })
256
249
  }
257
250
 
@@ -266,3 +259,18 @@ export const setAdminCookie = (event: RequestEvent, token: string) =>
266
259
 
267
260
  export const clearAdminCookie = (event: RequestEvent) => deleteCookie(event, ADMIN_COOKIE, { path: '/api/admin' })
268
261
  export const adminCookieOf = (event: RequestEvent) => getCookie(event, ADMIN_COOKIE)
262
+
263
+ export const TOTP_CHALLENGE_COOKIE = 'app_totp'
264
+
265
+ /** Short-lived HttpOnly cookie carrying the AEAD-sealed 2FA login challenge so OAuth redirects never put tokens in URLs. */
266
+ export const setTotpChallengeCookie = (event: RequestEvent, challenge: string) =>
267
+ setCookie(event, TOTP_CHALLENGE_COOKIE, challenge, {
268
+ httpOnly: true,
269
+ secure: !isLocalHost(event.req.url),
270
+ sameSite: 'lax',
271
+ path: '/api/auth/login/totp',
272
+ maxAge: 5 * 60,
273
+ })
274
+
275
+ export const clearTotpChallengeCookie = (event: RequestEvent) => deleteCookie(event, TOTP_CHALLENGE_COOKIE, { path: '/api/auth/login/totp' })
276
+ export const totpChallengeCookieOf = (event: RequestEvent) => getCookie(event, TOTP_CHALLENGE_COOKIE)