@humanonlyweb/create-nuxtflare 0.0.0-stage → 0.1.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 (138) hide show
  1. package/README.md +55 -2
  2. package/dist/cli.js +322 -0
  3. package/dist/template/.env.example +22 -0
  4. package/dist/template/.github/workflows/ci.yml +96 -0
  5. package/dist/template/.oxfmtrc.json +18 -0
  6. package/dist/template/.oxlintrc.json +69 -0
  7. package/dist/template/CLAUDE.md +42 -0
  8. package/dist/template/_gitignore +14 -0
  9. package/dist/template/app/app.vue +3 -0
  10. package/dist/template/app/components/qr-code.vue +36 -0
  11. package/dist/template/app/components/totp-setup.vue +151 -0
  12. package/dist/template/app/composables/use-features.ts +1 -0
  13. package/dist/template/app/composables/use-me.ts +10 -0
  14. package/dist/template/app/middleware/admin.global.ts +12 -0
  15. package/dist/template/app/middleware/auth.ts +6 -0
  16. package/dist/template/app/middleware/guest.ts +4 -0
  17. package/dist/template/app/pages/account.vue +22 -0
  18. package/dist/template/app/pages/admin/index.vue +16 -0
  19. package/dist/template/app/pages/admin/login.vue +39 -0
  20. package/dist/template/app/pages/index.vue +18 -0
  21. package/dist/template/app/pages/login.vue +110 -0
  22. package/dist/template/app/pages/register.vue +51 -0
  23. package/dist/template/app/utils/api-error.ts +50 -0
  24. package/dist/template/nuxt.config.ts +115 -0
  25. package/dist/template/package.json +59 -0
  26. package/dist/template/scripts/admin-password.ts +123 -0
  27. package/dist/template/server/api/account/email/index.delete.ts +5 -0
  28. package/dist/template/server/api/account/email/index.post.ts +8 -0
  29. package/dist/template/server/api/account/index.delete.ts +18 -0
  30. package/dist/template/server/api/account/index.patch.ts +16 -0
  31. package/dist/template/server/api/account/sessions.get.ts +11 -0
  32. package/dist/template/server/api/account/totp/cancel.post.ts +5 -0
  33. package/dist/template/server/api/account/totp/confirm.post.ts +10 -0
  34. package/dist/template/server/api/account/totp/disable.post.ts +8 -0
  35. package/dist/template/server/api/account/totp/index.get.ts +6 -0
  36. package/dist/template/server/api/account/totp/start.post.ts +8 -0
  37. package/dist/template/server/api/admin/me.get.ts +7 -0
  38. package/dist/template/server/api/admin/session/index.delete.ts +12 -0
  39. package/dist/template/server/api/admin/session/index.post.ts +18 -0
  40. package/dist/template/server/api/auth/email/index.post.ts +13 -0
  41. package/dist/template/server/api/auth/login/totp.post.ts +15 -0
  42. package/dist/template/server/api/auth/login.post.ts +17 -0
  43. package/dist/template/server/api/auth/logout-everywhere.post.ts +17 -0
  44. package/dist/template/server/api/auth/logout.post.ts +14 -0
  45. package/dist/template/server/api/auth/register.post.ts +18 -0
  46. package/dist/template/server/api/auth/reset/check.post.ts +5 -0
  47. package/dist/template/server/api/auth/reset/index.post.ts +5 -0
  48. package/dist/template/server/api/auth/reset/request.post.ts +5 -0
  49. package/dist/template/server/api/auth/verify/index.post.ts +17 -0
  50. package/dist/template/server/api/auth/verify/send.post.ts +7 -0
  51. package/dist/template/server/api/me.get.ts +8 -0
  52. package/dist/template/server/app/admin/auth.test.ts +41 -0
  53. package/dist/template/server/app/admin/auth.ts +133 -0
  54. package/dist/template/server/app/features.ts +18 -0
  55. package/dist/template/server/app/identity/email-change.ts +147 -0
  56. package/dist/template/server/app/identity/identity.test.ts +119 -0
  57. package/dist/template/server/app/identity/lockout.ts +93 -0
  58. package/dist/template/server/app/identity/password-reset.ts +119 -0
  59. package/dist/template/server/app/identity/service.ts +379 -0
  60. package/dist/template/server/app/identity/sessions.ts +141 -0
  61. package/dist/template/server/app/identity/state.ts +41 -0
  62. package/dist/template/server/app/identity/totp-crypto.ts +89 -0
  63. package/dist/template/server/app/identity/totp.test.ts +103 -0
  64. package/dist/template/server/app/identity/totp.ts +361 -0
  65. package/dist/template/server/app/identity/verification.ts +120 -0
  66. package/dist/template/server/app/notifications/email.ts +12 -0
  67. package/dist/template/server/app/notifications/render.test.ts +26 -0
  68. package/dist/template/server/app/notifications/render.ts +82 -0
  69. package/dist/template/server/app/notifications/samples.ts +11 -0
  70. package/dist/template/server/app/notifications/templates.ts +37 -0
  71. package/dist/template/server/assets/email/blocks/button.html +1 -0
  72. package/dist/template/server/assets/email/blocks/lead.html +1 -0
  73. package/dist/template/server/assets/email/blocks/note.html +1 -0
  74. package/dist/template/server/assets/email/blocks/text.html +1 -0
  75. package/dist/template/server/assets/email/layout.html +22 -0
  76. package/dist/template/server/cloudflare/exports/rate-limit.do.ts +38 -0
  77. package/dist/template/server/core/app-layer.ts +33 -0
  78. package/dist/template/server/core/db/atomic-d1.ts +21 -0
  79. package/dist/template/server/core/db/atomic.ts +86 -0
  80. package/dist/template/server/core/db/chunked.ts +13 -0
  81. package/dist/template/server/core/db/migrations.ts +149 -0
  82. package/dist/template/server/core/db/migrator.ts +39 -0
  83. package/dist/template/server/core/http/body-limit.ts +35 -0
  84. package/dist/template/server/core/http/csrf.ts +16 -0
  85. package/dist/template/server/core/http/device-label.ts +27 -0
  86. package/dist/template/server/core/http/handle.ts +271 -0
  87. package/dist/template/server/core/http/limit-key.ts +17 -0
  88. package/dist/template/server/core/http/page-csp.ts +16 -0
  89. package/dist/template/server/core/http/public-failure.ts +9 -0
  90. package/dist/template/server/core/http/request-user.ts +13 -0
  91. package/dist/template/server/core/http/runtime.ts +30 -0
  92. package/dist/template/server/core/http/session-cookie.ts +29 -0
  93. package/dist/template/server/core/platform/app-config.ts +55 -0
  94. package/dist/template/server/core/platform/clock.ts +4 -0
  95. package/dist/template/server/core/platform/database.ts +78 -0
  96. package/dist/template/server/core/platform/email-assets.ts +32 -0
  97. package/dist/template/server/core/platform/id-generator.ts +29 -0
  98. package/dist/template/server/core/platform/kv.ts +54 -0
  99. package/dist/template/server/core/platform/mailer-cloudflare.ts +51 -0
  100. package/dist/template/server/core/platform/mailer.ts +21 -0
  101. package/dist/template/server/core/platform/password-hasher.ts +27 -0
  102. package/dist/template/server/core/platform/pii.ts +80 -0
  103. package/dist/template/server/core/platform/provider-http.ts +21 -0
  104. package/dist/template/server/core/platform/rate-limiter-strict.ts +42 -0
  105. package/dist/template/server/core/platform/rate-limiter.ts +35 -0
  106. package/dist/template/server/core/platform/runtime-config-schema.ts +15 -0
  107. package/dist/template/server/core/platform/seal.ts +68 -0
  108. package/dist/template/server/core/platform/sliding-window.ts +39 -0
  109. package/dist/template/server/core/platform/tokens.ts +36 -0
  110. package/dist/template/server/core/platform/turnstile.ts +61 -0
  111. package/dist/template/server/middleware/00-body-limit.ts +10 -0
  112. package/dist/template/server/middleware/00-security-headers.ts +19 -0
  113. package/dist/template/server/middleware/01-user-session.ts +25 -0
  114. package/dist/template/server/plugins/page-csp.ts +15 -0
  115. package/dist/template/server/plugins/sessions.ts +21 -0
  116. package/dist/template/server/routes/(dev)/emails.get.dev.ts +37 -0
  117. package/dist/template/server/routes/auth/github.get.ts +96 -0
  118. package/dist/template/server/routes/auth/google.get.ts +61 -0
  119. package/dist/template/server/test/email-assets.ts +8 -0
  120. package/dist/template/server/test/invariants.test.ts +83 -0
  121. package/dist/template/server/test/kit.ts +83 -0
  122. package/dist/template/server/utils/define-validated-handler.ts +78 -0
  123. package/dist/template/server/utils/errors.ts +16 -0
  124. package/dist/template/server/utils/read-body.ts +34 -0
  125. package/dist/template/server/utils/user-actor.ts +10 -0
  126. package/dist/template/server.ts +5 -0
  127. package/dist/template/shared/domain/errors.ts +33 -0
  128. package/dist/template/shared/types/auth.d.ts +13 -0
  129. package/dist/template/shared/utils/admin.ts +13 -0
  130. package/dist/template/shared/utils/auth.ts +132 -0
  131. package/dist/template/shared/utils/ids.ts +21 -0
  132. package/dist/template/shared/utils/local-path.ts +2 -0
  133. package/dist/template/shared/utils/schema-validation.ts +59 -0
  134. package/dist/template/shared/utils/unknown.ts +9 -0
  135. package/dist/template/tsconfig.json +17 -0
  136. package/dist/template/vitest.config.ts +10 -0
  137. package/dist/template/wrangler.json +46 -0
  138. package/package.json +28 -4
@@ -0,0 +1,133 @@
1
+ import type { AccessIdentity } from '@humanonlyweb/cf-access'
2
+
3
+ import { Context, DateTime, Effect, Layer, Schema } from 'effect'
4
+
5
+ import type { RateLimited } from '#shared/domain/errors'
6
+
7
+ import { AppConfig } from '#server/core/platform/app-config'
8
+ import { nowIso } from '#server/core/platform/clock'
9
+ import { Database } from '#server/core/platform/database'
10
+ import { PasswordHasher } from '#server/core/platform/password-hasher'
11
+ import { RateLimiter } from '#server/core/platform/rate-limiter'
12
+ import { Tokens } from '#server/core/platform/tokens'
13
+ import { ServiceNotConfigured } from '#server/utils/errors'
14
+ import { Forbidden, Unauthorized } from '#shared/domain/errors'
15
+ import { ADMIN_SESSION_HOURS } from '#shared/utils/admin'
16
+
17
+ const AdminRow = Schema.Struct({ email: Schema.String, password_hash: Schema.String })
18
+ const SessionRow = Schema.Struct({ email: Schema.String })
19
+
20
+ const WRONG = 'That email and password do not match an admin.'
21
+
22
+ export const isLocalHost = (url: string) => {
23
+ try {
24
+ const host = new URL(url).hostname
25
+ return host === 'localhost' || host === '127.0.0.1' || host === '[::1]' || host.endsWith('.localhost')
26
+ } catch {
27
+ return false
28
+ }
29
+ }
30
+
31
+ const allowed = (list: string) =>
32
+ list
33
+ .split(',')
34
+ .map((email) => email.trim().toLowerCase())
35
+ .filter(Boolean)
36
+
37
+ /**
38
+ * Two-lock admin authentication:
39
+ * 1. Cloudflare Access JWT verified by `@humanonlyweb/cf-access`, email checked against `NUXT_ADMIN_EMAILS`.
40
+ * 2. Admin password stored in D1 (`scripts/admin-password.ts`), opening a 12-hour cookie session.
41
+ * Disabled cleanly when `features.admin` is false in `nuxt.config.ts`.
42
+ */
43
+ export class AdminAuth extends Context.Service<
44
+ AdminAuth,
45
+ {
46
+ readonly gate: (identity: AccessIdentity | null | undefined) => Effect.Effect<string, Forbidden | ServiceNotConfigured>
47
+ readonly signIn: (
48
+ accessEmail: string,
49
+ email: string,
50
+ password: string,
51
+ ) => Effect.Effect<{ readonly token: string; readonly expiresAt: string }, Unauthorized | RateLimited>
52
+ readonly session: (accessEmail: string, token: string | undefined) => Effect.Effect<{ readonly email: string }, Unauthorized>
53
+ readonly signOut: (token: string) => Effect.Effect<void>
54
+ readonly audit: (email: string, action: string, target: string, detail?: string) => Effect.Effect<void>
55
+ }
56
+ >()('app/admin/AdminAuth') {
57
+ static readonly layer = Layer.effect(
58
+ AdminAuth,
59
+ Effect.gen(function* () {
60
+ const config = yield* AppConfig
61
+ const db = yield* Database
62
+ const hasher = yield* PasswordHasher
63
+ const tokens = yield* Tokens
64
+ const limiter = yield* RateLimiter
65
+
66
+ const gate = (identity: AccessIdentity | null | undefined) =>
67
+ Effect.gen(function* () {
68
+ if (!config.features.admin) return yield* new ServiceNotConfigured({ service: 'admin', message: 'Admin is disabled.' })
69
+ const admins = allowed(config.adminEmails)
70
+ if (!admins.length) return yield* new ServiceNotConfigured({ service: 'admin', message: 'Admin is not configured.' })
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.
73
+ const email = identity === null ? admins[0]! : identity.email.toLowerCase()
74
+ if (!admins.includes(email)) return yield* new Forbidden({ message: 'This account is not an admin.' })
75
+ return email
76
+ })
77
+
78
+ const audit = (email: string, action: string, target: string, detail?: string) =>
79
+ Effect.gen(function* () {
80
+ yield* db
81
+ .run(`INSERT INTO admin_audit (actor_email, action, target, detail, created_at) VALUES (?, ?, ?, ?, ?)`, [
82
+ email,
83
+ action,
84
+ target,
85
+ detail ?? null,
86
+ yield* nowIso,
87
+ ])
88
+ .pipe(Effect.orDie)
89
+ })
90
+
91
+ const signIn = (accessEmail: string, rawEmail: string, password: string) =>
92
+ Effect.gen(function* () {
93
+ const email = rawEmail.trim().toLowerCase()
94
+ yield* limiter.check('sign-in-account', `admin:${email}`)
95
+ if (email !== accessEmail) return yield* new Unauthorized({ message: WRONG })
96
+ const row = yield* db.first(AdminRow, `SELECT email, password_hash FROM admins WHERE email = ?`, [email]).pipe(Effect.orDie)
97
+ if (!row || !(yield* hasher.verify(row.password_hash, password))) return yield* new Unauthorized({ message: WRONG })
98
+ const { token, hash } = yield* tokens.generate
99
+ const now = yield* DateTime.now
100
+ const expiresAt = DateTime.formatIso(DateTime.add(now, { hours: ADMIN_SESSION_HOURS }))
101
+ yield* db
102
+ .run(`INSERT INTO admin_sessions (token_hash, email, created_at, expires_at) VALUES (?, ?, ?, ?)`, [
103
+ hash,
104
+ row.email,
105
+ DateTime.formatIso(now),
106
+ expiresAt,
107
+ ])
108
+ .pipe(Effect.orDie)
109
+ yield* audit(row.email, 'signed_in', row.email)
110
+ return { token, expiresAt }
111
+ })
112
+
113
+ const session = (accessEmail: string, token: string | undefined) =>
114
+ Effect.gen(function* () {
115
+ if (!token) return yield* new Unauthorized({ message: 'Sign in to the admin.' })
116
+ const row = yield* db
117
+ .first(SessionRow, `SELECT email FROM admin_sessions WHERE token_hash = ? AND expires_at > ?`, [yield* tokens.hash(token), yield* nowIso])
118
+ .pipe(Effect.orDie)
119
+ if (!row || row.email.toLowerCase() !== accessEmail) return yield* new Unauthorized({ message: 'Sign in to the admin.' })
120
+ return { email: row.email.toLowerCase() }
121
+ })
122
+
123
+ const signOut = (token: string) =>
124
+ Effect.gen(function* () {
125
+ yield* db.run(`DELETE FROM admin_sessions WHERE token_hash = ? OR expires_at <= ?`, [yield* tokens.hash(token), yield* nowIso]).pipe(Effect.orDie)
126
+ })
127
+
128
+ return AdminAuth.of({ gate, signIn, session, signOut, audit })
129
+ }),
130
+ )
131
+ }
132
+
133
+ export class AdminActor extends Context.Service<AdminActor, { readonly email: string }>()('app/admin/AdminActor') {}
@@ -0,0 +1,18 @@
1
+ import { Layer } from 'effect'
2
+
3
+ import { AdminAuth } from './admin/auth'
4
+ import { EmailChange } from './identity/email-change'
5
+ import { LoginLockout } from './identity/lockout'
6
+ import { PasswordReset } from './identity/password-reset'
7
+ import { Identity } from './identity/service'
8
+ import { Sessions } from './identity/sessions'
9
+ import { Totp } from './identity/totp'
10
+ import { EmailVerification } from './identity/verification'
11
+ import { EmailRenderer } from './notifications/render'
12
+
13
+ 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))
16
+
17
+ /** 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))
@@ -0,0 +1,147 @@
1
+ import { Context, DateTime, Effect, Layer, Schema } from 'effect'
2
+
3
+ import type { RateLimited } from '#shared/domain/errors'
4
+
5
+ import { EmailRenderer } from '#server/app/notifications/render'
6
+ import { emailChangeEmail } from '#server/app/notifications/templates'
7
+ import { AtomicBatch, assertPreviousChanged } from '#server/core/db/atomic'
8
+ import { AppConfig } from '#server/core/platform/app-config'
9
+ import { nowIso } from '#server/core/platform/clock'
10
+ import { Database } from '#server/core/platform/database'
11
+ import { Mailer } from '#server/core/platform/mailer'
12
+ import { PasswordHasher } from '#server/core/platform/password-hasher'
13
+ import { RateLimiter } from '#server/core/platform/rate-limiter'
14
+ import { Tokens } from '#server/core/platform/tokens'
15
+ import { Conflict, Unauthorized, Unprocessable } from '#shared/domain/errors'
16
+ import { EMAIL_CHANGE_DAYS } from '#shared/utils/auth'
17
+
18
+ import { Sessions } from './sessions'
19
+
20
+ const LINK_HOURS = 24
21
+
22
+ const UserRow = Schema.Struct({
23
+ id: Schema.String,
24
+ email: Schema.String,
25
+ password_hash: Schema.NullOr(Schema.String),
26
+ email_changed_at: Schema.NullOr(Schema.String),
27
+ })
28
+
29
+ const TakenRow = Schema.Struct({ taken: Schema.Finite })
30
+
31
+ const TokenRow = Schema.Struct({
32
+ user_id: Schema.String,
33
+ new_email: Schema.String,
34
+ status: Schema.Literals(['active', 'used', 'revoked']),
35
+ expires_at: Schema.String,
36
+ })
37
+
38
+ export class EmailChange extends Context.Service<
39
+ EmailChange,
40
+ {
41
+ readonly request: (userId: string, newEmail: string, password: string) => Effect.Effect<void, Conflict | Unauthorized | Unprocessable | RateLimited>
42
+ readonly cancel: (userId: string) => Effect.Effect<void>
43
+ readonly confirm: (token: string) => Effect.Effect<{ readonly userId: string }, Unauthorized | Conflict>
44
+ }
45
+ >()('app/identity/EmailChange') {
46
+ static readonly layer = Layer.effect(
47
+ EmailChange,
48
+ Effect.gen(function* () {
49
+ const config = yield* AppConfig
50
+ const db = yield* Database
51
+ const atomic = yield* AtomicBatch
52
+ const tokens = yield* Tokens
53
+ const hasher = yield* PasswordHasher
54
+ const mailer = yield* Mailer
55
+ const renderer = yield* EmailRenderer
56
+ const limiter = yield* RateLimiter
57
+ const sessions = yield* Sessions
58
+
59
+ const request = Effect.fn('EmailChange.request')(function* (userId: string, rawEmail: string, password: string) {
60
+ yield* limiter.check('email-change', userId)
61
+ 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)
64
+
65
+ if (!user) return yield* new Unauthorized({ message: 'Please sign in again.' })
66
+ 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.' })
68
+ if (nextEmail === user.email) return yield* new Conflict({ field: 'email', message: 'That is already your email address.' })
69
+
70
+ const now = yield* DateTime.now
71
+
72
+ if (user.email_changed_at) {
73
+ const earliest = DateTime.formatIso(DateTime.subtract(now, { days: EMAIL_CHANGE_DAYS }))
74
+ if (user.email_changed_at > earliest) {
75
+ return yield* new Conflict({ message: `You can change your email once every ${EMAIL_CHANGE_DAYS} days.` })
76
+ }
77
+ }
78
+
79
+ const taken = yield* db.first(TakenRow, `SELECT 1 AS taken FROM users WHERE email = ? AND id <> ? LIMIT 1`, [nextEmail, userId]).pipe(Effect.orDie)
80
+ if (taken) return yield* new Conflict({ field: 'email', message: 'That email address is already in use.' })
81
+
82
+ const { token, hash } = yield* tokens.generate
83
+ const nowStr = DateTime.formatIso(now)
84
+ const expiresAt = DateTime.formatIso(DateTime.add(now, { hours: LINK_HOURS }))
85
+
86
+ yield* atomic
87
+ .run([
88
+ { sql: `UPDATE email_change_tokens SET status = 'revoked', revoked_at = ? WHERE user_id = ? AND status = 'active'`, params: [nowStr, userId] },
89
+ {
90
+ sql: `INSERT INTO email_change_tokens (token_hash, user_id, new_email, status, created_at, expires_at) VALUES (?, ?, ?, 'active', ?, ?)`,
91
+ params: [hash, userId, nextEmail, nowStr, expiresAt],
92
+ },
93
+ ])
94
+ .pipe(Effect.orDie)
95
+
96
+ const rendered = yield* renderer.render(emailChangeEmail(`${config.appUrl}/email/${token}`, config.appName))
97
+ yield* mailer.send({ to: nextEmail, ...rendered }).pipe(Effect.ignore)
98
+ })
99
+
100
+ const cancel = Effect.fn('EmailChange.cancel')(function* (userId: string) {
101
+ yield* db
102
+ .run(`UPDATE email_change_tokens SET status = 'revoked', revoked_at = ? WHERE user_id = ? AND status = 'active'`, [yield* nowIso, userId])
103
+ .pipe(Effect.orDie)
104
+ })
105
+
106
+ const confirm = Effect.fn('EmailChange.confirm')(function* (token: string) {
107
+ const invalid = new Unauthorized({ message: 'This email confirmation link is invalid or has expired.' })
108
+ const hash = yield* tokens.hash(token)
109
+ const now = yield* nowIso
110
+
111
+ const row = yield* db
112
+ .first(TokenRow, `SELECT user_id, new_email, status, expires_at FROM email_change_tokens WHERE token_hash = ?`, [hash])
113
+ .pipe(Effect.orDie)
114
+ if (!row || row.status !== 'active' || row.expires_at <= now) return yield* invalid
115
+
116
+ yield* atomic
117
+ .runGuarded('email_change_token_not_active', [
118
+ {
119
+ sql: `UPDATE email_change_tokens SET status = 'used', used_at = ? WHERE token_hash = ? AND status = 'active' AND expires_at > ?`,
120
+ params: [now, hash, now],
121
+ },
122
+ assertPreviousChanged,
123
+ {
124
+ sql: `UPDATE users SET email = ?, email_status = 'verified', email_verified_at = ?, email_changed_at = ? WHERE id = ?`,
125
+ params: [row.new_email, now, now, row.user_id],
126
+ },
127
+ assertPreviousChanged,
128
+ { sql: `DELETE FROM sessions WHERE user_id = ?`, params: [row.user_id] },
129
+ ])
130
+ .pipe(
131
+ Effect.catchTags({
132
+ GuardFailed: () => Effect.fail(invalid),
133
+ DatabaseError: (error) =>
134
+ /UNIQUE/i.test(error.message)
135
+ ? Effect.fail(new Conflict({ field: 'email', message: 'That email address is already in use.' }))
136
+ : Effect.die(error),
137
+ }),
138
+ )
139
+
140
+ yield* sessions.forget(row.user_id)
141
+ return { userId: row.user_id }
142
+ })
143
+
144
+ return EmailChange.of({ request, cancel, confirm })
145
+ }),
146
+ )
147
+ }
@@ -0,0 +1,119 @@
1
+ import { Effect } from 'effect'
2
+ import { describe, expect, it } from 'vitest'
3
+
4
+ import { EmailChange } from '#server/app/identity/email-change'
5
+ import { PasswordReset } from '#server/app/identity/password-reset'
6
+ import { Identity } from '#server/app/identity/service'
7
+ import { Sessions } from '#server/app/identity/sessions'
8
+ import { EmailVerification } from '#server/app/identity/verification'
9
+ import { makeTestLayer } from '#server/test/kit'
10
+
11
+ const extractToken = (text: string) => {
12
+ const match = /\/(?:verify|reset|email)\/([0-9a-f]{64})/.exec(text)
13
+ if (!match) throw new Error(`No token found in email: ${text}`)
14
+ return match[1]!
15
+ }
16
+
17
+ describe('identity flows', () => {
18
+ it('registers, verifies email, manages sessions, resets password, and changes email', async () => {
19
+ const { run, sent } = await makeTestLayer()
20
+
21
+ const user = await run(Identity.use((id) => id.register({ username: 'maya', email: 'maya@example.com', password: 'password123' })))
22
+ expect(user.emailStatus).toBe('unverified')
23
+
24
+ // Email verification flow
25
+ await run(EmailVerification.use((v) => v.send(user.id)))
26
+ expect(sent).toHaveLength(1)
27
+ const verifyToken = extractToken(sent[0]!.text)
28
+ await run(EmailVerification.use((v) => v.confirm(verifyToken)))
29
+ const me = await run(Identity.use((id) => id.me(user.id)))
30
+ expect(me.emailStatus).toBe('verified')
31
+
32
+ // Reusing verification token fails
33
+ const reuse = await run(EmailVerification.use((v) => v.confirm(verifyToken)).pipe(Effect.result))
34
+ expect(reuse._tag).toBe('Failure')
35
+
36
+ // Sessions start, verify, list, and revoke
37
+ const sessionId = await run(Sessions.use((s) => s.start(user.id, 'Chrome on macOS')))
38
+ const verified = await run(Sessions.use((s) => s.verify(sessionId)))
39
+ expect(verified?.id).toBe(user.id)
40
+ const recent = await run(Sessions.use((s) => s.recent(user.id, sessionId)))
41
+ expect(recent).toHaveLength(1)
42
+ expect(recent[0]?.current).toBe(true)
43
+
44
+ // Password reset revokes existing sessions and updates password
45
+ await run(PasswordReset.use((r) => r.request('maya@example.com')))
46
+ expect(sent).toHaveLength(2)
47
+ const resetToken = extractToken(sent[1]!.text)
48
+ await run(PasswordReset.use((r) => r.check(resetToken)))
49
+ await run(PasswordReset.use((r) => r.complete(resetToken, 'new-password-456')))
50
+
51
+ expect(await run(Sessions.use((s) => s.verify(sessionId)))).toBeUndefined()
52
+ const loggedIn = await run(Identity.use((id) => id.login({ identity: 'maya', password: 'new-password-456' })))
53
+ expect(loggedIn.status).toBe('authenticated')
54
+
55
+ // Email change flow
56
+ await run(EmailChange.use((c) => c.request(user.id, 'maya2@example.com', 'new-password-456')))
57
+ expect(sent).toHaveLength(3)
58
+ const changeToken = extractToken(sent[2]!.text)
59
+ await run(EmailChange.use((c) => c.confirm(changeToken)))
60
+
61
+ const updatedMe = await run(Identity.use((id) => id.me(user.id)))
62
+ expect(updatedMe.email).toBe('maya2@example.com')
63
+ expect(updatedMe.pendingEmailChange).toBeNull()
64
+ })
65
+
66
+ it('enforces Google and GitHub OAuth feature flags and supports GitHub sign-in & linking', async () => {
67
+ const disabled = await makeTestLayer({ config: { features: { googleOAuth: false, githubOAuth: false } } })
68
+ const googleOff = await disabled.run(
69
+ Identity.use((id) => id.oauth({ provider: 'google', providerId: 'sub-1', email: 'g@example.com', emailVerified: true })).pipe(Effect.result),
70
+ )
71
+ expect(googleOff._tag).toBe('Failure')
72
+ if (googleOff._tag === 'Failure') expect(googleOff.failure._tag).toBe('Forbidden')
73
+
74
+ const githubOff = await disabled.run(
75
+ Identity.use((id) => id.oauth({ provider: 'github', providerId: '42', email: 'gh@example.com', emailVerified: true })).pipe(Effect.result),
76
+ )
77
+ expect(githubOff._tag).toBe('Failure')
78
+ if (githubOff._tag === 'Failure') expect(githubOff.failure._tag).toBe('Forbidden')
79
+
80
+ const { run } = await makeTestLayer({ config: { features: { githubOAuth: true } } })
81
+ const created = await run(
82
+ Identity.use((id) =>
83
+ id.oauth({ provider: 'github', providerId: '9001', email: 'octocat@example.com', emailVerified: true, preferredUsername: 'octocat' }),
84
+ ),
85
+ )
86
+ expect(created.status).toBe('authenticated')
87
+ if (created.status === 'authenticated') {
88
+ expect(created.user.username).toBe('octocat')
89
+ expect(created.user.emailStatus).toBe('verified')
90
+ }
91
+
92
+ // Returning GitHub sign-in finds the same account
93
+ const again = await run(Identity.use((id) => id.oauth({ provider: 'github', providerId: '9001', email: 'octocat@example.com', emailVerified: true })))
94
+ expect(again.status).toBe('authenticated')
95
+ if (created.status === 'authenticated' && again.status === 'authenticated') {
96
+ expect(again.user.id).toBe(created.user.id)
97
+ }
98
+
99
+ // Unverified email is explicitly refused
100
+ const unverified = await run(
101
+ Identity.use((id) => id.oauth({ provider: 'github', providerId: '9002', email: 'no@example.com', emailVerified: false })).pipe(Effect.result),
102
+ )
103
+ expect(unverified._tag).toBe('Failure')
104
+ if (unverified._tag === 'Failure') expect(unverified.failure._tag).toBe('Unprocessable')
105
+ })
106
+
107
+ it('locks account after repeated wrong passwords', async () => {
108
+ const { run } = await makeTestLayer()
109
+
110
+ await run(Identity.use((id) => id.register({ username: 'sam', email: 'sam@example.com', password: 'real-password' })))
111
+ for (let i = 0; i < 5; i++) {
112
+ const attempt = await run(Identity.use((id) => id.login({ identity: 'sam', password: 'wrong' })).pipe(Effect.result))
113
+ expect(attempt._tag).toBe('Failure')
114
+ }
115
+ const locked = await run(Identity.use((id) => id.login({ identity: 'sam', password: 'real-password' })).pipe(Effect.result))
116
+ expect(locked._tag).toBe('Failure')
117
+ if (locked._tag === 'Failure') expect(locked.failure._tag).toBe('RateLimited')
118
+ })
119
+ })
@@ -0,0 +1,93 @@
1
+ import { Context, DateTime, Effect, Layer, Schema } from 'effect'
2
+
3
+ import { Database } from '#server/core/platform/database'
4
+ import { RateLimited } from '#shared/domain/errors'
5
+
6
+ const MAX_FAILURES = 5
7
+ const LOCK_MINUTES = 15
8
+
9
+ const FailureRow = Schema.Struct({
10
+ status: Schema.Literals(['counting', 'locked']),
11
+ failures: Schema.Finite,
12
+ locked_until: Schema.NullOr(Schema.String),
13
+ })
14
+
15
+ type LockoutState = { readonly _tag: 'Counting'; readonly failures: number } | { readonly _tag: 'Locked'; readonly lockedUntil: string }
16
+
17
+ const decodeLockoutState = (row: typeof FailureRow.Type): LockoutState => {
18
+ switch (row.status) {
19
+ case 'counting':
20
+ if (row.failures <= 0 || row.locked_until !== null) throw new Error('Invariant violation: login_failures counting row is inconsistent.')
21
+ return { _tag: 'Counting', failures: row.failures }
22
+ case 'locked':
23
+ if (row.failures !== 0 || row.locked_until === null) throw new Error('Invariant violation: login_failures locked row is inconsistent.')
24
+ return { _tag: 'Locked', lockedUntil: row.locked_until }
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Shared per-subject sign-in and 2FA attempt lockout backed by `login_failures`.
30
+ * Explicit state machine: absent -> counting(1..MAX-1) -> locked(locked_until) -> absent.
31
+ */
32
+ export class LoginLockout extends Context.Service<
33
+ LoginLockout,
34
+ {
35
+ readonly assertUnlocked: (subject: string) => Effect.Effect<void, RateLimited>
36
+ readonly recordFailure: (subject: string) => Effect.Effect<void>
37
+ readonly clear: (subject: string) => Effect.Effect<void>
38
+ }
39
+ >()('app/identity/LoginLockout') {
40
+ static readonly layer = Layer.effect(
41
+ LoginLockout,
42
+ Effect.gen(function* () {
43
+ const db = yield* Database
44
+
45
+ const assertUnlocked = (subject: string) =>
46
+ Effect.gen(function* () {
47
+ const row = yield* db.first(FailureRow, `SELECT status, failures, locked_until FROM login_failures WHERE subject = ?`, [subject]).pipe(Effect.orDie)
48
+ if (!row) return
49
+ const state = decodeLockoutState(row)
50
+ const now = DateTime.formatIso(yield* DateTime.now)
51
+ if (state._tag === 'Locked' && state.lockedUntil > now) {
52
+ return yield* new RateLimited({ message: `Too many wrong attempts. Try again in ${LOCK_MINUTES} minutes, or reset your password.` })
53
+ }
54
+ })
55
+
56
+ const recordFailure = (subject: string) =>
57
+ Effect.gen(function* () {
58
+ const now = yield* DateTime.now
59
+ const nowStr = DateTime.formatIso(now)
60
+ const lockUntil = DateTime.formatIso(DateTime.add(now, { minutes: LOCK_MINUTES }))
61
+ yield* db
62
+ .run(
63
+ `INSERT INTO login_failures (subject, status, failures, locked_until) VALUES (?, 'counting', 1, NULL)
64
+ ON CONFLICT(subject) DO UPDATE SET
65
+ status = CASE
66
+ WHEN status = 'locked' AND locked_until > ? THEN 'locked'
67
+ WHEN status = 'locked' THEN 'counting'
68
+ WHEN failures + 1 >= ? THEN 'locked'
69
+ ELSE 'counting'
70
+ END,
71
+ failures = CASE
72
+ WHEN status = 'locked' AND locked_until > ? THEN 0
73
+ WHEN status = 'locked' THEN 1
74
+ WHEN failures + 1 >= ? THEN 0
75
+ ELSE failures + 1
76
+ END,
77
+ locked_until = CASE
78
+ WHEN status = 'locked' AND locked_until > ? THEN locked_until
79
+ WHEN status = 'locked' THEN NULL
80
+ WHEN failures + 1 >= ? THEN ?
81
+ ELSE NULL
82
+ END`,
83
+ [subject, nowStr, MAX_FAILURES, nowStr, MAX_FAILURES, nowStr, MAX_FAILURES, lockUntil],
84
+ )
85
+ .pipe(Effect.orDie)
86
+ })
87
+
88
+ const clear = (subject: string) => db.run(`DELETE FROM login_failures WHERE subject = ?`, [subject]).pipe(Effect.orDie)
89
+
90
+ return LoginLockout.of({ assertUnlocked, recordFailure, clear })
91
+ }),
92
+ )
93
+ }
@@ -0,0 +1,119 @@
1
+ import { Context, DateTime, Effect, Layer, Schema } from 'effect'
2
+
3
+ import { EmailRenderer } from '#server/app/notifications/render'
4
+ import { passwordResetEmail } from '#server/app/notifications/templates'
5
+ import { AtomicBatch, assertPreviousChanged } from '#server/core/db/atomic'
6
+ import { AppConfig } from '#server/core/platform/app-config'
7
+ import { nowIso } from '#server/core/platform/clock'
8
+ import { Database } from '#server/core/platform/database'
9
+ import { Mailer } from '#server/core/platform/mailer'
10
+ import { PasswordHasher } from '#server/core/platform/password-hasher'
11
+ import { Pii } from '#server/core/platform/pii'
12
+ import { RateLimiter } from '#server/core/platform/rate-limiter'
13
+ import { Tokens } from '#server/core/platform/tokens'
14
+ import { Unauthorized } from '#shared/domain/errors'
15
+
16
+ import { Sessions } from './sessions'
17
+
18
+ const LINK_HOURS = 1
19
+
20
+ const UserRow = Schema.Struct({ id: Schema.String, email: Schema.String })
21
+ const TokenRow = Schema.Struct({
22
+ user_id: Schema.String,
23
+ status: Schema.Literals(['active', 'used', 'revoked']),
24
+ expires_at: Schema.String,
25
+ })
26
+
27
+ export class PasswordReset extends Context.Service<
28
+ PasswordReset,
29
+ {
30
+ /** Always resolves silently so callers cannot enumerate registered email addresses. */
31
+ readonly request: (email: string) => Effect.Effect<void>
32
+ readonly check: (token: string) => Effect.Effect<void, Unauthorized>
33
+ readonly complete: (token: string, newPassword: string) => Effect.Effect<void, Unauthorized>
34
+ }
35
+ >()('app/identity/PasswordReset') {
36
+ static readonly layer = Layer.effect(
37
+ PasswordReset,
38
+ Effect.gen(function* () {
39
+ const config = yield* AppConfig
40
+ const db = yield* Database
41
+ const atomic = yield* AtomicBatch
42
+ const tokens = yield* Tokens
43
+ const hasher = yield* PasswordHasher
44
+ const mailer = yield* Mailer
45
+ const renderer = yield* EmailRenderer
46
+ const pii = yield* Pii
47
+ const limiter = yield* RateLimiter
48
+ const sessions = yield* Sessions
49
+
50
+ const invalid = new Unauthorized({ message: 'This password reset link is invalid or has expired.' })
51
+
52
+ const request = Effect.fn('PasswordReset.request')(function* (rawEmail: string) {
53
+ const email = rawEmail.trim().toLowerCase()
54
+ const limited = yield* limiter.check('reset-email', yield* pii.index(email)).pipe(Effect.option)
55
+ if (limited._tag === 'None') return
56
+
57
+ const user = yield* db.first(UserRow, `SELECT id, email FROM users WHERE email = ?`, [email]).pipe(Effect.orDie)
58
+ if (!user) return
59
+
60
+ const { token, hash } = yield* tokens.generate
61
+ const now = yield* DateTime.now
62
+ const nowStr = DateTime.formatIso(now)
63
+ const expiresAt = DateTime.formatIso(DateTime.add(now, { hours: LINK_HOURS }))
64
+
65
+ yield* atomic
66
+ .run([
67
+ { sql: `UPDATE password_reset_tokens SET status = 'revoked', revoked_at = ? WHERE user_id = ? AND status = 'active'`, params: [nowStr, user.id] },
68
+ {
69
+ sql: `INSERT INTO password_reset_tokens (token_hash, user_id, status, created_at, expires_at) VALUES (?, ?, 'active', ?, ?)`,
70
+ params: [hash, user.id, nowStr, expiresAt],
71
+ },
72
+ ])
73
+ .pipe(Effect.orDie)
74
+
75
+ const rendered = yield* renderer.render(passwordResetEmail(`${config.appUrl}/reset/${token}`, config.appName))
76
+ yield* mailer.send({ to: user.email, ...rendered }).pipe(Effect.ignore)
77
+ })
78
+
79
+ const check = Effect.fn('PasswordReset.check')(function* (token: string) {
80
+ const hash = yield* tokens.hash(token)
81
+ const now = yield* nowIso
82
+ const row = yield* db.first(TokenRow, `SELECT user_id, status, expires_at FROM password_reset_tokens WHERE token_hash = ?`, [hash]).pipe(Effect.orDie)
83
+ if (!row || row.status !== 'active' || row.expires_at <= now) return yield* invalid
84
+ })
85
+
86
+ const complete = Effect.fn('PasswordReset.complete')(function* (token: string, newPassword: string) {
87
+ const hash = yield* tokens.hash(token)
88
+ const now = yield* nowIso
89
+ const row = yield* db.first(TokenRow, `SELECT user_id, status, expires_at FROM password_reset_tokens WHERE token_hash = ?`, [hash]).pipe(Effect.orDie)
90
+ if (!row || row.status !== 'active' || row.expires_at <= now) return yield* invalid
91
+
92
+ const passwordHash = yield* hasher.hash(newPassword)
93
+ const claimNow = yield* nowIso
94
+
95
+ yield* atomic
96
+ .runGuarded('reset_token_not_active', [
97
+ {
98
+ sql: `UPDATE password_reset_tokens SET status = 'used', used_at = ? WHERE token_hash = ? AND status = 'active' AND expires_at > ?`,
99
+ params: [claimNow, hash, claimNow],
100
+ },
101
+ assertPreviousChanged,
102
+ { sql: `UPDATE users SET password_hash = ? WHERE id = ?`, params: [passwordHash, row.user_id] },
103
+ { sql: `DELETE FROM sessions WHERE user_id = ?`, params: [row.user_id] },
104
+ { sql: `DELETE FROM login_failures WHERE subject IN (?, ?)`, params: [`user:${row.user_id}`, `totp:${row.user_id}`] },
105
+ ])
106
+ .pipe(
107
+ Effect.catchTags({
108
+ GuardFailed: () => Effect.fail(invalid),
109
+ DatabaseError: Effect.die,
110
+ }),
111
+ )
112
+
113
+ yield* sessions.forget(row.user_id)
114
+ })
115
+
116
+ return PasswordReset.of({ request, check, complete })
117
+ }),
118
+ )
119
+ }