@humanonlyweb/create-nuxtflare 0.1.2 → 0.2.0

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 (69) hide show
  1. package/README.md +4 -2
  2. package/dist/cli.js +9 -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 +145 -30
  33. package/dist/template/server/app/identity/sessions.ts +38 -6
  34. package/dist/template/server/app/identity/totp-crypto.ts +12 -5
  35. package/dist/template/server/app/identity/totp.ts +13 -12
  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/migrations.ts +7 -0
  40. package/dist/template/server/core/db/migrator.ts +5 -1
  41. package/dist/template/server/core/http/body.ts +1 -1
  42. package/dist/template/server/core/http/handle.ts +93 -80
  43. package/dist/template/server/core/http/security.test.ts +38 -0
  44. package/dist/template/server/core/http/security.ts +17 -5
  45. package/dist/template/server/core/http/session.ts +15 -0
  46. package/dist/template/server/core/platform/crypto-and-window.test.ts +75 -0
  47. package/dist/template/server/core/platform/database.ts +16 -1
  48. package/dist/template/server/core/platform/pii.ts +5 -8
  49. package/dist/template/server/core/platform/rate-limiter-strict.ts +35 -5
  50. package/dist/template/server/core/platform/rate-limiter.ts +2 -2
  51. package/dist/template/server/core/platform/seal.ts +13 -11
  52. package/dist/template/server/core/platform/sliding-window.ts +11 -2
  53. package/dist/template/server/core/platform/tokens.ts +3 -1
  54. package/dist/template/server/middleware/00-security-headers.ts +8 -4
  55. package/dist/template/server/middleware/01-user-session.ts +17 -5
  56. package/dist/template/server/plugins/page-csp.ts +24 -4
  57. package/dist/template/server/plugins/sessions.ts +4 -2
  58. package/dist/template/server/routes/auth/github.get.ts +4 -3
  59. package/dist/template/server/routes/auth/google.get.ts +4 -2
  60. package/dist/template/server/tasks/cleanup.ts +15 -0
  61. package/dist/template/server/test/invariants.test.ts +4 -2
  62. package/dist/template/server/utils/define-validated-handler.ts +14 -12
  63. package/dist/template/shared/domain/errors.ts +1 -0
  64. package/dist/template/shared/types/auth.d.ts +1 -1
  65. package/dist/template/shared/utils/auth.ts +10 -4
  66. package/dist/template/shared/utils/paths.ts +2 -0
  67. package/dist/template/shared/utils/schema-validation.ts +1 -1
  68. package/dist/template/wrangler.json +17 -0
  69. package/package.json +1 -1
@@ -69,7 +69,8 @@ export class AdminAuth extends Context.Service<
69
69
  const admins = allowed(config.adminEmails)
70
70
  if (!admins.length) return yield* new ServiceNotConfigured({ service: 'admin', message: 'Admin is not configured.' })
71
71
  if (identity === undefined) return yield* new ServiceNotConfigured({ service: 'admin', message: 'Admin Access gate is missing.' })
72
- // `null` is `@humanonlyweb/cf-access`'s local loopback bypass in `nuxt dev` only.
72
+ // `null` is `@humanonlyweb/cf-access`'s local loopback bypass in `nuxt dev` only; refuse in builds as defense-in-depth.
73
+ if (identity === null && !import.meta.dev) return yield* new ServiceNotConfigured({ service: 'admin', message: 'Admin Access gate is missing.' })
73
74
  const email = identity === null ? admins[0]! : identity.email.toLowerCase()
74
75
  if (!admins.includes(email)) return yield* new Forbidden({ message: 'This account is not an admin.' })
75
76
  return email
@@ -8,11 +8,12 @@ import { Identity } from './identity/service'
8
8
  import { Sessions } from './identity/sessions'
9
9
  import { Totp } from './identity/totp'
10
10
  import { EmailVerification } from './identity/verification'
11
+ import { Maintenance } from './maintenance/cleanup'
11
12
  import { EmailRenderer } from './notifications/render'
12
13
 
13
14
  const IdentityBase = Layer.mergeAll(Sessions.layer, LoginLockout.layer, EmailRenderer.layer)
14
-
15
- const IdentityFlows = Layer.mergeAll(Totp.layer, EmailVerification.layer, PasswordReset.layer, EmailChange.layer).pipe(Layer.provideMerge(IdentityBase))
15
+ const IdentityTotp = Totp.layer.pipe(Layer.provideMerge(IdentityBase))
16
+ const IdentityFlows = Layer.mergeAll(EmailVerification.layer, PasswordReset.layer, EmailChange.layer).pipe(Layer.provideMerge(IdentityTotp))
16
17
 
17
18
  /** All domain feature layers composed once and wired above `Foundation` in `server/core/app-layer.ts`. */
18
- export const Features = Layer.mergeAll(Identity.layer, AdminAuth.layer).pipe(Layer.provideMerge(IdentityFlows))
19
+ export const Features = Layer.mergeAll(Identity.layer, AdminAuth.layer, Maintenance.layer).pipe(Layer.provideMerge(IdentityFlows))
@@ -1,6 +1,6 @@
1
1
  import { Context, DateTime, Effect, Layer, Schema } from 'effect'
2
2
 
3
- import type { RateLimited } from '#shared/domain/errors'
3
+ import type { Forbidden, RateLimited } from '#shared/domain/errors'
4
4
 
5
5
  import { EmailRenderer } from '#server/app/notifications/render'
6
6
  import { emailChangeEmail } from '#server/app/notifications/templates'
@@ -15,15 +15,23 @@ import { Tokens } from '#server/core/platform/tokens'
15
15
  import { Conflict, Unauthorized, Unprocessable } from '#shared/domain/errors'
16
16
  import { EMAIL_CHANGE_DAYS } from '#shared/utils/auth'
17
17
 
18
+ import { LoginLockout } from './lockout'
18
19
  import { Sessions } from './sessions'
20
+ import { decodeTotpState } from './state'
21
+ import { Totp } from './totp'
19
22
 
20
23
  const LINK_HOURS = 24
24
+ const WRONG_CODE = 'That verification code is not valid. Use a fresh code from your authenticator app or a recovery code.'
21
25
 
22
26
  const UserRow = Schema.Struct({
23
27
  id: Schema.String,
24
28
  email: Schema.String,
25
29
  password_hash: Schema.NullOr(Schema.String),
26
30
  email_changed_at: Schema.NullOr(Schema.String),
31
+ totp_status: Schema.Literals(['off', 'pending', 'enabled']),
32
+ totp_secret: Schema.NullOr(Schema.String),
33
+ totp_enabled_at: Schema.NullOr(Schema.String),
34
+ totp_last_step: Schema.Finite,
27
35
  })
28
36
 
29
37
  const TakenRow = Schema.Struct({ taken: Schema.Finite })
@@ -38,7 +46,12 @@ const TokenRow = Schema.Struct({
38
46
  export class EmailChange extends Context.Service<
39
47
  EmailChange,
40
48
  {
41
- readonly request: (userId: string, newEmail: string, password: string) => Effect.Effect<void, Conflict | Unauthorized | Unprocessable | RateLimited>
49
+ readonly request: (
50
+ userId: string,
51
+ newEmail: string,
52
+ password: string,
53
+ code?: string,
54
+ ) => Effect.Effect<void, Conflict | Forbidden | Unauthorized | Unprocessable | RateLimited>
42
55
  readonly cancel: (userId: string) => Effect.Effect<void>
43
56
  readonly confirm: (token: string) => Effect.Effect<{ readonly userId: string }, Unauthorized | Conflict>
44
57
  }
@@ -54,17 +67,39 @@ export class EmailChange extends Context.Service<
54
67
  const mailer = yield* Mailer
55
68
  const renderer = yield* EmailRenderer
56
69
  const limiter = yield* RateLimiter
70
+ const lockout = yield* LoginLockout
57
71
  const sessions = yield* Sessions
72
+ const totp = yield* Totp
58
73
 
59
- const request = Effect.fn('EmailChange.request')(function* (userId: string, rawEmail: string, password: string) {
74
+ const request = Effect.fn('EmailChange.request')(function* (userId: string, rawEmail: string, password: string, code?: string) {
60
75
  yield* limiter.check('email-change', userId)
61
76
  const nextEmail = rawEmail.trim().toLowerCase()
62
-
63
- const user = yield* db.first(UserRow, `SELECT id, email, password_hash, email_changed_at FROM users WHERE id = ?`, [userId]).pipe(Effect.orDie)
77
+ const subject = `user:${userId}`
78
+ yield* lockout.assertUnlocked(subject)
79
+
80
+ const user = yield* db
81
+ .first(
82
+ UserRow,
83
+ `SELECT id, email, password_hash, email_changed_at, totp_status, totp_secret, totp_enabled_at, totp_last_step FROM users WHERE id = ?`,
84
+ [userId],
85
+ )
86
+ .pipe(Effect.orDie)
64
87
 
65
88
  if (!user) return yield* new Unauthorized({ message: 'Please sign in again.' })
66
89
  if (!user.password_hash) return yield* new Unprocessable({ message: 'Set a password before changing your email address.' })
67
- if (!(yield* hasher.verify(user.password_hash, password))) return yield* new Unauthorized({ message: 'The password is not right.' })
90
+ if (!(yield* hasher.verify(user.password_hash, password))) {
91
+ yield* lockout.recordFailure(subject)
92
+ return yield* new Unauthorized({ message: 'The password is not right.' })
93
+ }
94
+ yield* lockout.clear(subject)
95
+
96
+ const totpState = decodeTotpState(user)
97
+ if (config.features.totp && totpState._tag === 'Enabled') {
98
+ if (!code) return yield* new Unauthorized({ message: 'Enter your verification code to change your email address.' })
99
+ const ok = yield* totp.verifySecondFactor(user.id, code)
100
+ if (!ok) return yield* new Unauthorized({ message: WRONG_CODE })
101
+ }
102
+
68
103
  if (nextEmail === user.email) return yield* new Conflict({ field: 'email', message: 'That is already your email address.' })
69
104
 
70
105
  const now = yield* DateTime.now
@@ -94,7 +129,9 @@ export class EmailChange extends Context.Service<
94
129
  .pipe(Effect.orDie)
95
130
 
96
131
  const rendered = yield* renderer.render(emailChangeEmail(`${config.appUrl}/email/${token}`, config.appName))
97
- yield* mailer.send({ to: nextEmail, ...rendered }).pipe(Effect.ignore)
132
+ yield* mailer
133
+ .send({ to: nextEmail, ...rendered })
134
+ .pipe(Effect.catch((error) => Effect.logWarning(`Email change mail failed (${error._tag}): ${error.message}`)))
98
135
  })
99
136
 
100
137
  const cancel = Effect.fn('EmailChange.cancel')(function* (userId: string) {
@@ -104,6 +104,29 @@ describe('identity flows', () => {
104
104
  if (unverified._tag === 'Failure') expect(unverified.failure._tag).toBe('Unprocessable')
105
105
  })
106
106
 
107
+ it('prevents OAuth pre-hijacking by replacing unverified local accounts and revoking their sessions', async () => {
108
+ const { run } = await makeTestLayer({ config: { features: { googleOAuth: true } } })
109
+
110
+ const attacker = await run(Identity.use((id) => id.register({ username: 'squatter', email: 'victim@example.com', password: 'attacker-password' })))
111
+ const attackerSession = await run(Sessions.use((s) => s.start(attacker.id, 'Chrome on Linux')))
112
+ expect((await run(Sessions.use((s) => s.verify(attackerSession))))?.id).toBe(attacker.id)
113
+
114
+ const outcome = await run(
115
+ Identity.use((id) =>
116
+ id.oauth({ provider: 'google', providerId: 'google-victim-1', email: 'victim@example.com', emailVerified: true, preferredUsername: 'victim' }),
117
+ ),
118
+ )
119
+ expect(outcome.status).toBe('authenticated')
120
+ if (outcome.status !== 'authenticated') throw new Error('expected authenticated')
121
+ expect(outcome.user.id).not.toBe(attacker.id)
122
+ expect(outcome.user.emailStatus).toBe('verified')
123
+
124
+ // Attacker's session and password are completely gone
125
+ expect(await run(Sessions.use((s) => s.verify(attackerSession)))).toBeUndefined()
126
+ const attackerLogin = await run(Identity.use((id) => id.login({ identity: 'victim@example.com', password: 'attacker-password' })).pipe(Effect.result))
127
+ expect(attackerLogin._tag).toBe('Failure')
128
+ })
129
+
107
130
  it('locks account after repeated wrong passwords', async () => {
108
131
  const { run } = await makeTestLayer()
109
132
 
@@ -116,4 +139,51 @@ describe('identity flows', () => {
116
139
  expect(locked._tag).toBe('Failure')
117
140
  if (locked._tag === 'Failure') expect(locked.failure._tag).toBe('RateLimited')
118
141
  })
142
+
143
+ it('requires password re-authentication before deleting a password-backed account', async () => {
144
+ const { run } = await makeTestLayer()
145
+ const user = await run(Identity.use((id) => id.register({ username: 'dana', email: 'dana@example.com', password: 'secret-password' })))
146
+
147
+ const missingPassword = await run(Identity.use((id) => id.deleteAccount(user.id, { confirm: 'dana' })).pipe(Effect.result))
148
+ expect(missingPassword._tag).toBe('Failure')
149
+ if (missingPassword._tag === 'Failure') expect(missingPassword.failure._tag).toBe('Unauthorized')
150
+
151
+ await run(Identity.use((id) => id.deleteAccount(user.id, { confirm: 'dana', password: 'secret-password' })))
152
+ const afterDelete = await run(Identity.use((id) => id.me(user.id)).pipe(Effect.result))
153
+ expect(afterDelete._tag).toBe('Failure')
154
+ })
155
+
156
+ it('lets OAuth-only users set a password and lets password users change password while revoking other sessions', async () => {
157
+ const { run } = await makeTestLayer({ config: { features: { googleOAuth: true } } })
158
+ const oauthOutcome = await run(
159
+ Identity.use((id) => id.oauth({ provider: 'google', providerId: 'g-pw-1', email: 'oauth@example.com', emailVerified: true })),
160
+ )
161
+ expect(oauthOutcome.status).toBe('authenticated')
162
+ if (oauthOutcome.status !== 'authenticated') throw new Error('expected authenticated')
163
+ const userId = oauthOutcome.user.id
164
+
165
+ expect((await run(Identity.use((id) => id.me(userId)))).hasPassword).toBe(false)
166
+
167
+ // Set initial password on OAuth-only account
168
+ await run(Identity.use((id) => id.setPassword(userId, { newPassword: 'initial-password-1' })))
169
+ expect((await run(Identity.use((id) => id.me(userId)))).hasPassword).toBe(true)
170
+
171
+ const keptSession = await run(Sessions.use((s) => s.start(userId, 'Chrome on macOS')))
172
+ const otherSession = await run(Sessions.use((s) => s.start(userId, 'Safari on iPhone')))
173
+
174
+ // Wrong current password fails
175
+ const badChange = await run(
176
+ Identity.use((id) => id.setPassword(userId, { currentPassword: 'wrong', newPassword: 'next-password-2', keepSessionId: keptSession })).pipe(
177
+ Effect.result,
178
+ ),
179
+ )
180
+ expect(badChange._tag).toBe('Failure')
181
+
182
+ // Valid password change keeps current session and revokes other sessions
183
+ await run(
184
+ Identity.use((id) => id.setPassword(userId, { currentPassword: 'initial-password-1', newPassword: 'next-password-2', keepSessionId: keptSession })),
185
+ )
186
+ expect((await run(Sessions.use((s) => s.verify(keptSession))))?.id).toBe(userId)
187
+ expect(await run(Sessions.use((s) => s.verify(otherSession)))).toBeUndefined()
188
+ })
119
189
  })
@@ -57,30 +57,35 @@ export class LoginLockout extends Context.Service<
57
57
  Effect.gen(function* () {
58
58
  const now = yield* DateTime.now
59
59
  const nowStr = DateTime.formatIso(now)
60
+ const staleBefore = DateTime.formatIso(DateTime.subtract(now, { minutes: LOCK_MINUTES }))
60
61
  const lockUntil = DateTime.formatIso(DateTime.add(now, { minutes: LOCK_MINUTES }))
61
62
  yield* db
62
63
  .run(
63
- `INSERT INTO login_failures (subject, status, failures, locked_until) VALUES (?, 'counting', 1, NULL)
64
+ `INSERT INTO login_failures (subject, status, failures, locked_until, updated_at) VALUES (?, 'counting', 1, NULL, ?)
64
65
  ON CONFLICT(subject) DO UPDATE SET
65
66
  status = CASE
66
67
  WHEN status = 'locked' AND locked_until > ? THEN 'locked'
67
68
  WHEN status = 'locked' THEN 'counting'
69
+ WHEN updated_at <= ? THEN 'counting'
68
70
  WHEN failures + 1 >= ? THEN 'locked'
69
71
  ELSE 'counting'
70
72
  END,
71
73
  failures = CASE
72
74
  WHEN status = 'locked' AND locked_until > ? THEN 0
73
75
  WHEN status = 'locked' THEN 1
76
+ WHEN updated_at <= ? THEN 1
74
77
  WHEN failures + 1 >= ? THEN 0
75
78
  ELSE failures + 1
76
79
  END,
77
80
  locked_until = CASE
78
81
  WHEN status = 'locked' AND locked_until > ? THEN locked_until
79
82
  WHEN status = 'locked' THEN NULL
83
+ WHEN updated_at <= ? THEN NULL
80
84
  WHEN failures + 1 >= ? THEN ?
81
85
  ELSE NULL
82
- END`,
83
- [subject, nowStr, MAX_FAILURES, nowStr, MAX_FAILURES, nowStr, MAX_FAILURES, lockUntil],
86
+ END,
87
+ updated_at = ?`,
88
+ [subject, nowStr, nowStr, staleBefore, MAX_FAILURES, nowStr, staleBefore, MAX_FAILURES, nowStr, staleBefore, MAX_FAILURES, lockUntil, nowStr],
84
89
  )
85
90
  .pipe(Effect.orDie)
86
91
  })
@@ -73,7 +73,9 @@ export class PasswordReset extends Context.Service<
73
73
  .pipe(Effect.orDie)
74
74
 
75
75
  const rendered = yield* renderer.render(passwordResetEmail(`${config.appUrl}/reset/${token}`, config.appName))
76
- yield* mailer.send({ to: user.email, ...rendered }).pipe(Effect.ignore)
76
+ yield* mailer
77
+ .send({ to: user.email, ...rendered })
78
+ .pipe(Effect.catch((error) => Effect.logWarning(`Password reset email failed (${error._tag}): ${error.message}`)))
77
79
  })
78
80
 
79
81
  const check = Effect.fn('PasswordReset.check')(function* (token: string) {
@@ -3,7 +3,7 @@ import { Context, DateTime, Effect, Layer, Schema } from 'effect'
3
3
  import type { RateLimited } from '#shared/domain/errors'
4
4
  import type { MeView } from '#shared/utils/auth'
5
5
 
6
- import { AtomicBatch } from '#server/core/db/atomic'
6
+ import { AtomicBatch, assertPreviousChanged } from '#server/core/db/atomic'
7
7
  import { AppConfig } from '#server/core/platform/app-config'
8
8
  import { nowIso } from '#server/core/platform/clock'
9
9
  import { Database } from '#server/core/platform/database'
@@ -116,7 +116,19 @@ export class Identity extends Context.Service<
116
116
  readonly oauth: (profile: OAuthProfile) => Effect.Effect<LoginOutcome, Forbidden | Conflict | Unprocessable>
117
117
  readonly me: (userId: string) => Effect.Effect<MeView, NotFound>
118
118
  readonly updateProfile: (userId: string, input: { readonly username: string }) => Effect.Effect<AuthUser, Conflict | NotFound>
119
- readonly deleteAccount: (userId: string, confirm: string) => Effect.Effect<void, NotFound | Unprocessable>
119
+ readonly setPassword: (
120
+ userId: string,
121
+ input: {
122
+ readonly currentPassword?: string | undefined
123
+ readonly newPassword: string
124
+ readonly code?: string | undefined
125
+ readonly keepSessionId?: string | undefined
126
+ },
127
+ ) => Effect.Effect<void, Conflict | NotFound | Unauthorized | Forbidden | RateLimited>
128
+ readonly deleteAccount: (
129
+ userId: string,
130
+ input: { readonly confirm: string; readonly password?: string | undefined; readonly code?: string | undefined },
131
+ ) => Effect.Effect<void, NotFound | Unprocessable | Unauthorized | Forbidden | RateLimited>
120
132
  }
121
133
  >()('app/identity/Identity') {
122
134
  static readonly layer = Layer.effect(
@@ -194,22 +206,23 @@ export class Identity extends Context.Service<
194
206
  const key = input.identity.trim().toLowerCase()
195
207
  yield* limiter.check('sign-in-account', `login:${key}`)
196
208
 
209
+ const lookupColumn = key.includes('@') ? 'email' : 'username'
197
210
  const user = yield* db
198
211
  .first(
199
212
  LoginUserRow,
200
213
  `SELECT id, username, email, password_hash, email_status, totp_status, totp_secret, totp_enabled_at, totp_last_step
201
214
  FROM users
202
- WHERE email = ? OR username = ?
215
+ WHERE ${lookupColumn} = ?
203
216
  LIMIT 1`,
204
- [key, key],
217
+ [key],
205
218
  )
206
219
  .pipe(Effect.orDie)
207
220
 
208
221
  const subject = user ? `user:${user.id}` : `identity:${key}`
209
222
  yield* lockout.assertUnlocked(subject)
210
223
 
211
- const decoyHash = yield* decoy
212
- const passwordOk = yield* hasher.verify(user?.password_hash ?? decoyHash, input.password)
224
+ const hashToVerify = user?.password_hash ?? (yield* decoy)
225
+ const passwordOk = yield* hasher.verify(hashToVerify, input.password)
213
226
  if (!user || !user.password_hash || !passwordOk) {
214
227
  yield* lockout.recordFailure(subject)
215
228
  return yield* new Unauthorized({ message: WRONG_LOGIN })
@@ -261,25 +274,16 @@ export class Identity extends Context.Service<
261
274
 
262
275
  const now = yield* DateTime.now
263
276
  const nowStr = DateTime.formatIso(now)
264
- const staleBefore = DateTime.formatIso(DateTime.subtract(now, { hours: UNCONFIRMED_HOLD_HOURS }))
265
277
 
266
- const byEmail = yield* db
267
- .first(OAuthUserRow, `SELECT ${columns} FROM users WHERE email = ? AND NOT (${UNCONFIRMED_STALE})`, [email, email, staleBefore])
268
- .pipe(Effect.orDie)
278
+ const byEmail = yield* db.first(OAuthUserRow, `SELECT ${columns} FROM users WHERE email = ?`, [email]).pipe(Effect.orDie)
269
279
 
270
- if (byEmail) {
280
+ if (byEmail && byEmail.email_status === 'verified') {
271
281
  const existingProviderId = byEmail[meta.column]
272
282
  if (existingProviderId && existingProviderId !== profile.providerId) {
273
283
  return yield* new Conflict({ message: `That email address is already linked to another ${meta.label} account.` })
274
284
  }
275
- yield* db
276
- .run(`UPDATE users SET ${meta.column} = ?, email_status = 'verified', email_verified_at = COALESCE(email_verified_at, ?) WHERE id = ?`, [
277
- profile.providerId,
278
- nowStr,
279
- byEmail.id,
280
- ])
281
- .pipe(Effect.orDie)
282
- const linked: AuthUser = { ...toAuthUser(byEmail), emailStatus: 'verified' }
285
+ yield* db.run(`UPDATE users SET ${meta.column} = ? WHERE id = ?`, [profile.providerId, byEmail.id]).pipe(Effect.orDie)
286
+ const linked = toAuthUser(byEmail)
283
287
  const totpState = decodeTotpState(byEmail)
284
288
  if (config.features.totp && totpState._tag === 'Enabled') {
285
289
  return { status: 'totp_required', challenge: yield* totp.issueChallenge(byEmail.id) } satisfies LoginOutcome
@@ -287,19 +291,28 @@ export class Identity extends Context.Service<
287
291
  return { status: 'authenticated', user: linked } satisfies LoginOutcome
288
292
  }
289
293
 
294
+ // An unverified local registration has not proven email ownership; replace it atomically so a
295
+ // pre-registered attacker's password, active sessions, and TOTP setup are never inherited.
290
296
  const id = yield* ids.next('user')
291
297
  const preferred = profile.preferredUsername ? usernameBaseFrom(profile.preferredUsername) : usernameBaseFrom(email.split('@')[0] ?? '')
292
298
  const username = yield* pickUniqueUsername(preferred)
293
299
  yield* atomic
294
300
  .run([
295
- { sql: `DELETE FROM users WHERE ${UNCONFIRMED_STALE}`, params: [email, staleBefore] },
301
+ { sql: `DELETE FROM users WHERE email = ? AND email_status = 'unverified' AND google_sub IS NULL AND github_id IS NULL`, params: [email] },
296
302
  {
297
303
  sql: `INSERT INTO users (id, username, email, ${meta.column}, email_status, email_verified_at, totp_status, created_at, last_active_at)
298
304
  VALUES (?, ?, ?, ?, 'verified', ?, 'off', ?, ?)`,
299
305
  params: [id, username, email, profile.providerId, nowStr, nowStr, nowStr],
300
306
  },
301
307
  ])
302
- .pipe(Effect.orDie)
308
+ .pipe(
309
+ Effect.catch((error) =>
310
+ /UNIQUE constraint failed: users\.email/i.test(error.message)
311
+ ? Effect.fail(new Conflict({ message: 'That email address is already registered.' }))
312
+ : Effect.die(error),
313
+ ),
314
+ )
315
+ if (byEmail) yield* sessions.forget(byEmail.id)
303
316
 
304
317
  return {
305
318
  status: 'authenticated',
@@ -320,11 +333,18 @@ export class Identity extends Context.Service<
320
333
  u.password_hash IS NOT NULL AS has_password,
321
334
  u.totp_status,
322
335
  u.email_changed_at,
323
- (SELECT c.new_email FROM email_change_tokens c WHERE c.user_id = u.id AND c.status = 'active' AND c.expires_at > ? ORDER BY c.created_at DESC LIMIT 1) AS pending_email,
324
- (SELECT c.expires_at FROM email_change_tokens c WHERE c.user_id = u.id AND c.status = 'active' AND c.expires_at > ? ORDER BY c.created_at DESC LIMIT 1) AS pending_until
336
+ c.new_email AS pending_email,
337
+ c.expires_at AS pending_until
325
338
  FROM users u
339
+ LEFT JOIN (
340
+ SELECT user_id, new_email, expires_at
341
+ FROM email_change_tokens
342
+ WHERE user_id = ? AND status = 'active' AND expires_at > ?
343
+ ORDER BY created_at DESC
344
+ LIMIT 1
345
+ ) c ON c.user_id = u.id
326
346
  WHERE u.id = ?`,
327
- [now, now, userId],
347
+ [userId, now, userId],
328
348
  )
329
349
  .pipe(Effect.orDie)
330
350
  if (!row) return yield* new NotFound({ resource: 'User', id: userId })
@@ -363,17 +383,112 @@ export class Identity extends Context.Service<
363
383
  return toAuthUser(updated)
364
384
  })
365
385
 
366
- const deleteAccount = Effect.fn('Identity.deleteAccount')(function* (userId: string, confirm: string) {
367
- const row = yield* db.first(UsernameRow, `SELECT username FROM users WHERE id = ?`, [userId]).pipe(Effect.orDie)
368
- if (!row) return yield* new NotFound({ resource: 'User', id: userId })
369
- if (!matchesConfirm(confirm, row.username)) {
370
- return yield* new Unprocessable({ message: `Type ${row.username} to confirm deletion.` })
386
+ const setPassword = Effect.fn('Identity.setPassword')(function* (
387
+ userId: string,
388
+ input: {
389
+ readonly currentPassword?: string | undefined
390
+ readonly newPassword: string
391
+ readonly code?: string | undefined
392
+ readonly keepSessionId?: string | undefined
393
+ },
394
+ ) {
395
+ const user = yield* db
396
+ .first(
397
+ LoginUserRow,
398
+ `SELECT id, username, email, password_hash, email_status, totp_status, totp_secret, totp_enabled_at, totp_last_step FROM users WHERE id = ?`,
399
+ [userId],
400
+ )
401
+ .pipe(Effect.orDie)
402
+ if (!user) return yield* new NotFound({ resource: 'User', id: userId })
403
+
404
+ if (user.password_hash) {
405
+ const subject = `user:${user.id}`
406
+ yield* lockout.assertUnlocked(subject)
407
+ if (!input.currentPassword || !(yield* hasher.verify(user.password_hash, input.currentPassword))) {
408
+ yield* lockout.recordFailure(subject)
409
+ return yield* new Unauthorized({ message: 'The current password is not right.' })
410
+ }
411
+ yield* lockout.clear(subject)
412
+
413
+ const totpState = decodeTotpState(user)
414
+ if (config.features.totp && totpState._tag === 'Enabled') {
415
+ if (!input.code) return yield* new Unauthorized({ message: 'Enter your verification code to change your password.' })
416
+ const ok = yield* totp.verifySecondFactor(user.id, input.code)
417
+ if (!ok) return yield* new Unauthorized({ message: WRONG_CODE })
418
+ }
419
+
420
+ const nextHash = yield* hasher.hash(input.newPassword)
421
+ yield* atomic
422
+ .runGuarded('password_changed_concurrently', [
423
+ { sql: `UPDATE users SET password_hash = ? WHERE id = ? AND password_hash = ?`, params: [nextHash, userId, user.password_hash] },
424
+ assertPreviousChanged,
425
+ input.keepSessionId
426
+ ? { sql: `DELETE FROM sessions WHERE user_id = ? AND id <> ?`, params: [userId, input.keepSessionId] }
427
+ : { sql: `DELETE FROM sessions WHERE user_id = ?`, params: [userId] },
428
+ ])
429
+ .pipe(
430
+ Effect.catchTags({
431
+ GuardFailed: () => Effect.fail(new Conflict({ message: 'Your password was updated elsewhere. Please try again.' })),
432
+ DatabaseError: Effect.die,
433
+ }),
434
+ )
435
+ yield* sessions.forget(userId)
436
+ return
371
437
  }
438
+
439
+ // OAuth-only account setting an initial password so they can enable 2FA or change email.
440
+ const nextHash = yield* hasher.hash(input.newPassword)
441
+ yield* atomic
442
+ .runGuarded('password_already_set', [
443
+ { sql: `UPDATE users SET password_hash = ? WHERE id = ? AND password_hash IS NULL`, params: [nextHash, userId] },
444
+ assertPreviousChanged,
445
+ ])
446
+ .pipe(
447
+ Effect.catchTags({
448
+ GuardFailed: () => Effect.fail(new Conflict({ message: 'A password is already set on this account.' })),
449
+ DatabaseError: Effect.die,
450
+ }),
451
+ )
452
+ })
453
+
454
+ const deleteAccount = Effect.fn('Identity.deleteAccount')(function* (
455
+ userId: string,
456
+ input: { readonly confirm: string; readonly password?: string | undefined; readonly code?: string | undefined },
457
+ ) {
458
+ const user = yield* db
459
+ .first(
460
+ LoginUserRow,
461
+ `SELECT id, username, email, password_hash, email_status, totp_status, totp_secret, totp_enabled_at, totp_last_step FROM users WHERE id = ?`,
462
+ [userId],
463
+ )
464
+ .pipe(Effect.orDie)
465
+ if (!user) return yield* new NotFound({ resource: 'User', id: userId })
466
+ if (!matchesConfirm(input.confirm, user.username)) {
467
+ return yield* new Unprocessable({ message: `Type ${user.username} to confirm deletion.` })
468
+ }
469
+
470
+ if (user.password_hash) {
471
+ const subject = `user:${user.id}`
472
+ yield* lockout.assertUnlocked(subject)
473
+ if (!input.password || !(yield* hasher.verify(user.password_hash, input.password))) {
474
+ yield* lockout.recordFailure(subject)
475
+ return yield* new Unauthorized({ message: 'Enter your current password to delete your account.' })
476
+ }
477
+ yield* lockout.clear(subject)
478
+ }
479
+
480
+ const totpState = decodeTotpState(user)
481
+ if (config.features.totp && totpState._tag === 'Enabled') {
482
+ if (!input.code) return yield* new Unauthorized({ message: 'Enter your verification code to delete your account.' })
483
+ const ok = yield* totp.verifySecondFactor(user.id, input.code)
484
+ if (!ok) return yield* new Unauthorized({ message: WRONG_CODE })
485
+ }
486
+
372
487
  yield* sessions.forget(userId)
373
488
  yield* db.run(`DELETE FROM users WHERE id = ?`, [userId]).pipe(Effect.orDie)
374
489
  })
375
490
 
376
- return Identity.of({ register, login, oauth, me, updateProfile, deleteAccount })
491
+ return Identity.of({ register, login, oauth, me, updateProfile, setPassword, deleteAccount })
377
492
  }),
378
493
  )
379
494
  }
@@ -2,6 +2,7 @@ import { Context, DateTime, Effect, Layer, Schema } from 'effect'
2
2
 
3
3
  import type { EmailStatus } from '#shared/utils/auth'
4
4
 
5
+ import { AtomicBatch, type Statement } from '#server/core/db/atomic'
5
6
  import { Database } from '#server/core/platform/database'
6
7
  import { IdGenerator } from '#server/core/platform/id-generator'
7
8
 
@@ -40,11 +41,15 @@ export interface SessionUser {
40
41
  const REMEMBER_MS = 3000
41
42
  const REMEMBER_MAX = 1000
42
43
 
44
+ export interface VerifySessionOptions {
45
+ readonly waitUntil?: (promise: Promise<unknown>) => void
46
+ }
47
+
43
48
  export class Sessions extends Context.Service<
44
49
  Sessions,
45
50
  {
46
51
  readonly start: (userId: string, device?: string) => Effect.Effect<string>
47
- readonly verify: (sessionId: string) => Effect.Effect<SessionUser | undefined>
52
+ readonly verify: (sessionId: string, options?: VerifySessionOptions) => Effect.Effect<SessionUser | undefined>
48
53
  readonly end: (sessionId: string) => Effect.Effect<void>
49
54
  readonly endAll: (userId: string) => Effect.Effect<void>
50
55
  readonly forget: (userId: string) => Effect.Effect<void>
@@ -55,6 +60,7 @@ export class Sessions extends Context.Service<
55
60
  Sessions,
56
61
  Effect.gen(function* () {
57
62
  const db = yield* Database
63
+ const atomic = yield* AtomicBatch
58
64
  const ids = yield* IdGenerator
59
65
  const remembered = new Map<string, { readonly user: SessionUser; readonly until: number }>()
60
66
 
@@ -62,6 +68,19 @@ export class Sessions extends Context.Service<
62
68
  for (const [id, entry] of remembered) if (entry.user.id === userId) remembered.delete(id)
63
69
  }
64
70
 
71
+ const remember = (sessionId: string, user: SessionUser, nowMs: number) => {
72
+ if (remembered.has(sessionId)) remembered.delete(sessionId)
73
+ if (remembered.size >= REMEMBER_MAX) {
74
+ for (const [id, entry] of remembered) if (entry.until <= nowMs) remembered.delete(id)
75
+ while (remembered.size >= REMEMBER_MAX) {
76
+ const oldest = remembered.keys().next().value
77
+ if (oldest === undefined) break
78
+ remembered.delete(oldest)
79
+ }
80
+ }
81
+ remembered.set(sessionId, { user, until: nowMs + REMEMBER_MS })
82
+ }
83
+
65
84
  return Sessions.of({
66
85
  start: (userId, device = '') =>
67
86
  Effect.gen(function* () {
@@ -81,7 +100,7 @@ export class Sessions extends Context.Service<
81
100
  return id
82
101
  }),
83
102
 
84
- verify: (sessionId) =>
103
+ verify: (sessionId, options) =>
85
104
  Effect.gen(function* () {
86
105
  const known = remembered.get(sessionId)
87
106
  if (known && known.until > Date.now()) return known.user
@@ -100,16 +119,29 @@ export class Sessions extends Context.Service<
100
119
  .pipe(Effect.orDie)
101
120
  if (!row) return undefined
102
121
 
122
+ const updates: Statement[] = []
103
123
  if (row.last_active_at < DateTime.formatIso(DateTime.subtract(now, { hours: ACTIVITY_STEP_HOURS }))) {
104
- yield* db.run(`UPDATE users SET last_active_at = ? WHERE id = ?`, [nowStr, row.id]).pipe(Effect.orDie)
124
+ updates.push({ sql: `UPDATE users SET last_active_at = ? WHERE id = ?`, params: [nowStr, row.id] })
105
125
  }
106
126
  if (row.last_seen_at < DateTime.formatIso(DateTime.subtract(now, { minutes: SEEN_STEP_MINUTES }))) {
107
- yield* db.run(`UPDATE sessions SET last_seen_at = ? WHERE id = ?`, [nowStr, sessionId]).pipe(Effect.orDie)
127
+ updates.push({ sql: `UPDATE sessions SET last_seen_at = ? WHERE id = ?`, params: [nowStr, sessionId] })
128
+ }
129
+ if (updates.length > 0) {
130
+ const persist = atomic.run(updates).pipe(Effect.catch((error) => Effect.logWarning(`Session activity update failed: ${error.message}`)))
131
+ if (options?.waitUntil) {
132
+ const fiber = yield* Effect.forkDetach(persist)
133
+ options.waitUntil(
134
+ new Promise<void>((resolve) => {
135
+ fiber.addObserver(() => resolve())
136
+ }),
137
+ )
138
+ } else {
139
+ yield* persist
140
+ }
108
141
  }
109
142
 
110
143
  const user: SessionUser = { id: row.id, username: row.username, emailStatus: row.email_status }
111
- if (remembered.size >= REMEMBER_MAX) remembered.clear()
112
- remembered.set(sessionId, { user, until: Date.now() + REMEMBER_MS })
144
+ remember(sessionId, user, Date.now())
113
145
  return user
114
146
  }),
115
147