@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
@@ -1,22 +1,136 @@
1
1
  <script setup lang="ts">
2
2
  definePageMeta({ middleware: 'auth' })
3
3
 
4
- const { data: me } = await useMe()
5
- const features = useFeatures()
6
- const { clear } = useUserSession()
7
-
8
- const signOut = async () => {
9
- await $fetch('/api/auth/logout', { method: 'POST' })
10
- await clear()
11
- await navigateTo('/login')
12
- }
4
+ const {
5
+ me,
6
+ features,
7
+ canUseVerifiedActions,
8
+ sessionList,
9
+ username,
10
+ nextEmail,
11
+ emailPassword,
12
+ emailCode,
13
+ currentPassword,
14
+ newPassword,
15
+ passwordCode,
16
+ deleteConfirm,
17
+ deletePassword,
18
+ deleteCode,
19
+ busy,
20
+ notice,
21
+ errorMessage,
22
+ refreshSessions,
23
+ signOut,
24
+ signOutEverywhere,
25
+ resendVerification,
26
+ saveProfile,
27
+ savePassword,
28
+ requestEmailChange,
29
+ cancelEmailChange,
30
+ deleteAccount,
31
+ } = await useAccount()
13
32
  </script>
14
33
 
15
34
  <template>
16
35
  <main v-if="me">
17
36
  <h1>Account</h1>
37
+ <p v-if="errorMessage" role="alert">{{ errorMessage }}</p>
38
+ <p v-if="notice" role="status">{{ notice }}</p>
39
+
18
40
  <p>{{ me.username }} ({{ me.email }}) — email {{ me.emailStatus }}</p>
19
- <button type="button" @click="signOut">Sign out</button>
20
- <TotpSetup v-if="features.totp && (!features.emailVerificationRequired || me.emailStatus === 'verified')" />
41
+ <button type="button" :disabled="busy" @click="signOut">Sign out</button>
42
+
43
+ <section v-if="me.emailStatus === 'unverified'">
44
+ <h2>Confirm your email</h2>
45
+ <p>Check your inbox for a confirmation link, or request a fresh one.</p>
46
+ <button type="button" :disabled="busy" @click="resendVerification">Resend verification email</button>
47
+ </section>
48
+
49
+ <template v-if="canUseVerifiedActions">
50
+ <section>
51
+ <h2>Profile</h2>
52
+ <form @submit.prevent="saveProfile">
53
+ <label>
54
+ Username
55
+ <input v-model="username" autocomplete="username" required />
56
+ </label>
57
+ <button type="submit" :disabled="busy">Save username</button>
58
+ </form>
59
+ </section>
60
+
61
+ <section>
62
+ <h2>{{ me.hasPassword ? 'Change password' : 'Set password' }}</h2>
63
+ <form @submit.prevent="savePassword">
64
+ <label v-if="me.hasPassword">
65
+ Current password
66
+ <input v-model="currentPassword" type="password" autocomplete="current-password" required />
67
+ </label>
68
+ <label>
69
+ New password
70
+ <input v-model="newPassword" type="password" autocomplete="new-password" required />
71
+ </label>
72
+ <label v-if="me.hasPassword && features.totp && me.totpStatus === 'enabled'">
73
+ Authenticator or recovery code
74
+ <input v-model="passwordCode" autocomplete="one-time-code" required />
75
+ </label>
76
+ <button type="submit" :disabled="busy">{{ me.hasPassword ? 'Change password' : 'Set password' }}</button>
77
+ </form>
78
+ </section>
79
+
80
+ <section v-if="me.hasPassword">
81
+ <h2>Email address</h2>
82
+ <div v-if="me.pendingEmailChange">
83
+ <p>Pending change to {{ me.pendingEmailChange.email }}.</p>
84
+ <button type="button" :disabled="busy" @click="cancelEmailChange">Cancel pending change</button>
85
+ </div>
86
+ <form v-else @submit.prevent="requestEmailChange">
87
+ <label>
88
+ New email
89
+ <input v-model="nextEmail" type="email" autocomplete="email" required />
90
+ </label>
91
+ <label>
92
+ Current password
93
+ <input v-model="emailPassword" type="password" autocomplete="current-password" required />
94
+ </label>
95
+ <label v-if="features.totp && me.totpStatus === 'enabled'">
96
+ Authenticator or recovery code
97
+ <input v-model="emailCode" autocomplete="one-time-code" required />
98
+ </label>
99
+ <button type="submit" :disabled="busy">Change email</button>
100
+ </form>
101
+ </section>
102
+
103
+ <TotpSetup v-if="features.totp" />
104
+
105
+ <section>
106
+ <h2>Active sessions</h2>
107
+ <ul>
108
+ <li v-for="(item, index) in sessionList.sessions" :key="index">
109
+ {{ item.device }} — last seen {{ item.lastSeenAt }}<span v-if="item.current"> (current)</span>
110
+ </li>
111
+ </ul>
112
+ <button type="button" :disabled="busy" @click="refreshSessions()">Refresh sessions</button>
113
+ <button type="button" :disabled="busy" @click="signOutEverywhere">Sign out everywhere</button>
114
+ </section>
115
+ </template>
116
+
117
+ <section>
118
+ <h2>Delete account</h2>
119
+ <form @submit.prevent="deleteAccount">
120
+ <label>
121
+ Type {{ me.username }} to confirm
122
+ <input v-model="deleteConfirm" required />
123
+ </label>
124
+ <label v-if="me.hasPassword">
125
+ Current password
126
+ <input v-model="deletePassword" type="password" autocomplete="current-password" required />
127
+ </label>
128
+ <label v-if="features.totp && me.totpStatus === 'enabled'">
129
+ Authenticator or recovery code
130
+ <input v-model="deleteCode" autocomplete="one-time-code" required />
131
+ </label>
132
+ <button type="submit" :disabled="busy">Delete account</button>
133
+ </form>
134
+ </section>
21
135
  </main>
22
136
  </template>
@@ -0,0 +1,18 @@
1
+ <script setup lang="ts">
2
+ const { step } = useEmailChangeConfirm()
3
+ </script>
4
+
5
+ <template>
6
+ <main>
7
+ <h1>Confirm new email</h1>
8
+ <p v-if="step.kind === 'confirming'">Updating your email address…</p>
9
+ <template v-else-if="step.kind === 'confirmed'">
10
+ <p>Your email address has been updated. Sign in with your new email address.</p>
11
+ <p><NuxtLink to="/login">Sign in</NuxtLink></p>
12
+ </template>
13
+ <template v-else>
14
+ <p role="alert">{{ step.message }}</p>
15
+ <p><NuxtLink to="/login">Back to sign in</NuxtLink></p>
16
+ </template>
17
+ </main>
18
+ </template>
@@ -0,0 +1,28 @@
1
+ <script setup lang="ts">
2
+ definePageMeta({ middleware: 'guest' })
3
+
4
+ const turnstile = ref<{ reset: () => void } | null>(null)
5
+ const { step, email, turnstileToken, busy, errorMessage, submit } = useForgotPassword()
6
+ </script>
7
+
8
+ <template>
9
+ <main>
10
+ <h1>Reset password</h1>
11
+ <p v-if="errorMessage" role="alert">{{ errorMessage }}</p>
12
+
13
+ <template v-if="step.kind === 'sent'">
14
+ <p>If an account matches that email address, a password reset link has been sent.</p>
15
+ <p><NuxtLink to="/login">Back to sign in</NuxtLink></p>
16
+ </template>
17
+
18
+ <form v-else @submit.prevent="submit(() => turnstile?.reset())">
19
+ <label>
20
+ Email
21
+ <input v-model="email" type="email" autocomplete="email" required />
22
+ </label>
23
+ <TurnstileWidget ref="turnstile" v-model="turnstileToken" />
24
+ <button type="submit" :disabled="busy">Send reset link</button>
25
+ <p><NuxtLink to="/login">Back to sign in</NuxtLink></p>
26
+ </form>
27
+ </main>
28
+ </template>
@@ -1,76 +1,10 @@
1
1
  <script setup lang="ts">
2
- import { isLocalPath } from '#shared/utils/auth'
3
- import { problemOf } from '~/utils/api-error'
4
-
5
2
  definePageMeta({ middleware: 'guest' })
6
3
 
7
- type LoginStep = { readonly kind: 'credentials' } | { readonly kind: 'totp'; readonly challenge: string }
8
-
9
- const route = useRoute()
10
4
  const features = useFeatures()
11
- const { fetch: refreshSession } = useUserSession()
12
-
13
- const step = ref<LoginStep>({ kind: 'credentials' })
14
- const identity = ref('')
15
- const password = ref('')
16
- const code = ref('')
17
- const busy = ref(false)
18
- const errorMessage = ref('')
19
-
20
- onMounted(() => {
21
- if (location.hash.startsWith('#totp=')) {
22
- const challenge = decodeURIComponent(location.hash.slice('#totp='.length))
23
- if (challenge) {
24
- step.value = { kind: 'totp', challenge }
25
- history.replaceState(null, '', location.pathname + location.search)
26
- }
27
- }
28
- })
29
-
30
- const destination = () => {
31
- const next = typeof route.query.next === 'string' ? route.query.next : ''
32
- return isLocalPath(next) ? next : '/account'
33
- }
34
-
35
- const submitCredentials = async () => {
36
- errorMessage.value = ''
37
- busy.value = true
38
- try {
39
- const result = await $fetch('/api/auth/login', {
40
- method: 'POST',
41
- body: { identity: identity.value, password: password.value },
42
- })
43
- if (result.status === 'totp_required') {
44
- password.value = ''
45
- step.value = { kind: 'totp', challenge: result.challenge }
46
- return
47
- }
48
- await refreshSession()
49
- await navigateTo(destination())
50
- } catch (error) {
51
- errorMessage.value = problemOf(error).message
52
- } finally {
53
- busy.value = false
54
- }
55
- }
56
-
57
- const submitTotp = async () => {
58
- if (step.value.kind !== 'totp') return
59
- errorMessage.value = ''
60
- busy.value = true
61
- try {
62
- await $fetch('/api/auth/login/totp', {
63
- method: 'POST',
64
- body: { challenge: step.value.challenge, code: code.value },
65
- })
66
- await refreshSession()
67
- await navigateTo(destination())
68
- } catch (error) {
69
- errorMessage.value = problemOf(error).message
70
- } finally {
71
- busy.value = false
72
- }
73
- }
5
+ const turnstile = ref<{ reset: () => void } | null>(null)
6
+ const { step, identity, password, code, turnstileToken, busy, errorMessage, rememberOAuthNext, submitCredentials, submitTotp, backToCredentials } =
7
+ useAuthLogin()
74
8
  </script>
75
9
 
76
10
  <template>
@@ -78,7 +12,7 @@ const submitTotp = async () => {
78
12
  <h1>Sign in</h1>
79
13
  <p v-if="errorMessage" role="alert">{{ errorMessage }}</p>
80
14
 
81
- <form v-if="step.kind === 'credentials'" @submit.prevent="submitCredentials">
15
+ <form v-if="step.kind === 'credentials'" @submit.prevent="submitCredentials(() => turnstile?.reset())">
82
16
  <label>
83
17
  Email or username
84
18
  <input v-model="identity" autocomplete="username" required />
@@ -87,7 +21,9 @@ const submitTotp = async () => {
87
21
  Password
88
22
  <input v-model="password" type="password" autocomplete="current-password" required />
89
23
  </label>
24
+ <TurnstileWidget ref="turnstile" v-model="turnstileToken" />
90
25
  <button type="submit" :disabled="busy">Sign in</button>
26
+ <p><NuxtLink to="/forgot-password">Forgot your password?</NuxtLink></p>
91
27
  </form>
92
28
 
93
29
  <form v-else @submit.prevent="submitTotp">
@@ -97,14 +33,14 @@ const submitTotp = async () => {
97
33
  <input v-model="code" autocomplete="one-time-code" required />
98
34
  </label>
99
35
  <button type="submit" :disabled="busy">Verify</button>
100
- <button type="button" :disabled="busy" @click="step = { kind: 'credentials' }">Back</button>
36
+ <button type="button" :disabled="busy" @click="backToCredentials">Back</button>
101
37
  </form>
102
38
 
103
39
  <p v-if="features.googleOAuth && step.kind === 'credentials'">
104
- <a href="/auth/google">Continue with Google</a>
40
+ <a href="/auth/google" @click="rememberOAuthNext">Continue with Google</a>
105
41
  </p>
106
42
  <p v-if="features.githubOAuth && step.kind === 'credentials'">
107
- <a href="/auth/github">Continue with GitHub</a>
43
+ <a href="/auth/github" @click="rememberOAuthNext">Continue with GitHub</a>
108
44
  </p>
109
45
  </main>
110
46
  </template>
@@ -1,38 +1,15 @@
1
1
  <script setup lang="ts">
2
- import { problemOf } from '~/utils/api-error'
3
-
4
2
  definePageMeta({ middleware: 'guest' })
5
3
 
6
- const { fetch: refreshSession } = useUserSession()
7
- const username = ref('')
8
- const email = ref('')
9
- const password = ref('')
10
- const busy = ref(false)
11
- const errorMessage = ref('')
12
-
13
- const submit = async () => {
14
- errorMessage.value = ''
15
- busy.value = true
16
- try {
17
- await $fetch('/api/auth/register', {
18
- method: 'POST',
19
- body: { username: username.value, email: email.value, password: password.value },
20
- })
21
- await refreshSession()
22
- await navigateTo('/account')
23
- } catch (error) {
24
- errorMessage.value = problemOf(error).message
25
- } finally {
26
- busy.value = false
27
- }
28
- }
4
+ const turnstile = ref<{ reset: () => void } | null>(null)
5
+ const { username, email, password, turnstileToken, busy, errorMessage, submit } = useAuthRegister()
29
6
  </script>
30
7
 
31
8
  <template>
32
9
  <main>
33
10
  <h1>Create account</h1>
34
11
  <p v-if="errorMessage" role="alert">{{ errorMessage }}</p>
35
- <form @submit.prevent="submit">
12
+ <form @submit.prevent="submit(() => turnstile?.reset())">
36
13
  <label>
37
14
  Username
38
15
  <input v-model="username" autocomplete="username" required />
@@ -45,6 +22,7 @@ const submit = async () => {
45
22
  Password
46
23
  <input v-model="password" type="password" autocomplete="new-password" required />
47
24
  </label>
25
+ <TurnstileWidget ref="turnstile" v-model="turnstileToken" />
48
26
  <button type="submit" :disabled="busy">Create account</button>
49
27
  </form>
50
28
  </main>
@@ -0,0 +1,31 @@
1
+ <script setup lang="ts">
2
+ const { step, password, confirm, busy, errorMessage, submit } = usePasswordReset()
3
+ </script>
4
+
5
+ <template>
6
+ <main>
7
+ <h1>Choose a new password</h1>
8
+ <p v-if="errorMessage" role="alert">{{ errorMessage }}</p>
9
+
10
+ <p v-if="step.kind === 'checking'">Checking your reset link…</p>
11
+ <template v-else-if="step.kind === 'invalid'">
12
+ <p role="alert">{{ step.message }}</p>
13
+ <p><NuxtLink to="/forgot-password">Request a new reset link</NuxtLink></p>
14
+ </template>
15
+ <template v-else-if="step.kind === 'done'">
16
+ <p>Your password has been updated and existing sessions were signed out.</p>
17
+ <p><NuxtLink to="/login">Sign in</NuxtLink></p>
18
+ </template>
19
+ <form v-else @submit.prevent="submit">
20
+ <label>
21
+ New password
22
+ <input v-model="password" type="password" autocomplete="new-password" required />
23
+ </label>
24
+ <label>
25
+ Confirm password
26
+ <input v-model="confirm" type="password" autocomplete="new-password" required />
27
+ </label>
28
+ <button type="submit" :disabled="busy">Update password</button>
29
+ </form>
30
+ </main>
31
+ </template>
@@ -0,0 +1,18 @@
1
+ <script setup lang="ts">
2
+ const { step, loggedIn } = useEmailVerify()
3
+ </script>
4
+
5
+ <template>
6
+ <main>
7
+ <h1>Email verification</h1>
8
+ <p v-if="step.kind === 'verifying'">Confirming your email address…</p>
9
+ <template v-else-if="step.kind === 'verified'">
10
+ <p>Your email address is confirmed.</p>
11
+ <p><NuxtLink :to="loggedIn ? '/account' : '/login'">Continue</NuxtLink></p>
12
+ </template>
13
+ <template v-else>
14
+ <p role="alert">{{ step.message }}</p>
15
+ <p><NuxtLink :to="loggedIn ? '/account' : '/login'">Back</NuxtLink></p>
16
+ </template>
17
+ </main>
18
+ </template>
@@ -38,6 +38,7 @@ export default defineNuxtConfig({
38
38
 
39
39
  routeRules: {
40
40
  '/api/**': { headers: { 'cache-control': 'no-store', 'content-security-policy': "default-src 'none'; frame-ancestors 'none'" } },
41
+ '/auth/**': { headers: { 'cache-control': 'no-store' } },
41
42
  '/account': { headers: { 'x-robots-tag': 'noindex', 'cache-control': 'no-store' } },
42
43
  '/verify/**': { headers: { 'x-robots-tag': 'noindex', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' } },
43
44
  '/reset/**': { headers: { 'x-robots-tag': 'noindex', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' } },
@@ -49,6 +50,9 @@ export default defineNuxtConfig({
49
50
  nitro: {
50
51
  preset: 'cloudflare_module',
51
52
  experimental: { database: true, tasks: true, envExpansion: true },
53
+ scheduledTasks: {
54
+ '0 3 * * *': ['cleanup'],
55
+ },
52
56
  database: {
53
57
  default: { connector: 'cloudflare-d1', options: { bindingName: 'DB' } },
54
58
  },
@@ -17,6 +17,8 @@
17
17
  "test": "vitest run",
18
18
  "test:affected": "vitest run --since-last-run",
19
19
  "check": "bun run typecheck && bun run lint && bun run fmt:check && bun run test",
20
+ "db:migrate": "bun scripts/migrate.ts",
21
+ "db:migrate:remote": "bun scripts/migrate.ts --remote",
20
22
  "deploy": "nuxt build && wrangler deploy"
21
23
  },
22
24
  "dependencies": {
@@ -9,8 +9,9 @@ import { spawnSync } from 'node:child_process'
9
9
  * bun scripts/admin-password.ts --email you@example.com local dev database
10
10
  * bun scripts/admin-password.ts --email you@example.com --remote deployed database
11
11
  */
12
- import { readFileSync } from 'node:fs'
13
- import { resolve } from 'node:path'
12
+ import { readFileSync, rmSync, writeFileSync } from 'node:fs'
13
+ import { tmpdir } from 'node:os'
14
+ import { join, resolve } from 'node:path'
14
15
  import { createInterface } from 'node:readline/promises'
15
16
 
16
17
  const args = process.argv.slice(2)
@@ -117,7 +118,13 @@ const statements = [
117
118
  `DELETE FROM admin_sessions WHERE email = ${quote(email)}`,
118
119
  ]
119
120
 
120
- const result = spawnSync('bunx', ['wrangler', 'd1', 'execute', dbName, flag('remote') ? '--remote' : '--local', '--command', statements.join('; ')], {
121
- stdio: 'inherit',
122
- })
123
- process.exit(result.status ?? 1)
121
+ const sqlFile = join(tmpdir(), `admin-password-${process.pid}-${Date.now()}.sql`)
122
+ writeFileSync(sqlFile, `${statements.join(';\n')};\n`, { encoding: 'utf8', mode: 0o600 })
123
+ try {
124
+ const result = spawnSync('bunx', ['wrangler', 'd1', 'execute', dbName, flag('remote') ? '--remote' : '--local', '--file', sqlFile], {
125
+ stdio: 'inherit',
126
+ })
127
+ process.exit(result.status ?? 1)
128
+ } finally {
129
+ rmSync(sqlFile, { force: true })
130
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Applies pending D1 migrations from `server/core/db/migrations.ts` at deploy time
3
+ * so production Worker isolates never incur cold-start DDL writes.
4
+ *
5
+ * bun scripts/migrate.ts local dev database
6
+ * bun scripts/migrate.ts --remote deployed database
7
+ */
8
+ import { Schema } from 'effect'
9
+ import { spawnSync } from 'node:child_process'
10
+ import { readFileSync, rmSync, writeFileSync } from 'node:fs'
11
+ import { tmpdir } from 'node:os'
12
+ import { join, resolve } from 'node:path'
13
+
14
+ import { migrations } from '../server/core/db/migrations'
15
+
16
+ const remote = process.argv.slice(2).includes('--remote')
17
+ const targetFlag = remote ? '--remote' : '--local'
18
+
19
+ const WranglerConfig = Schema.fromJsonString(
20
+ Schema.Struct({
21
+ d1_databases: Schema.optionalKey(Schema.Array(Schema.Struct({ database_name: Schema.optionalKey(Schema.String) }))),
22
+ }),
23
+ )
24
+ const wranglerConfig = Schema.decodeSync(WranglerConfig)(readFileSync(resolve(import.meta.dirname, '..', 'wrangler.json'), 'utf8'))
25
+ const dbName = wranglerConfig.d1_databases?.[0]?.database_name
26
+ if (!dbName) {
27
+ console.error('Could not find d1_databases[0].database_name in wrangler.json.')
28
+ process.exit(1)
29
+ }
30
+
31
+ const QueryOutput = Schema.fromJsonString(
32
+ Schema.Array(
33
+ Schema.Struct({
34
+ results: Schema.optionalKey(Schema.Array(Schema.Struct({ id: Schema.String }))),
35
+ }),
36
+ ),
37
+ )
38
+
39
+ const runSqlFile = (statements: ReadonlyArray<string>, json = false): string => {
40
+ const sqlFile = join(tmpdir(), `nuxtflare-migrate-${process.pid}-${Date.now()}.sql`)
41
+ writeFileSync(sqlFile, `${statements.join(';\n')};\n`, { encoding: 'utf8', mode: 0o600 })
42
+ try {
43
+ const args = ['wrangler', 'd1', 'execute', dbName, targetFlag, '--file', sqlFile, ...(json ? ['--json'] : [])]
44
+ const result = spawnSync('bunx', args, { encoding: 'utf8', stdio: json ? ['inherit', 'pipe', 'inherit'] : 'inherit' })
45
+ if (result.status !== 0) process.exit(result.status ?? 1)
46
+ return result.stdout ?? ''
47
+ } finally {
48
+ rmSync(sqlFile, { force: true })
49
+ }
50
+ }
51
+
52
+ const quote = (text: string) => `'${text.replaceAll("'", "''")}'`
53
+
54
+ runSqlFile([`CREATE TABLE IF NOT EXISTS _migrations (id TEXT PRIMARY KEY, applied_at TEXT NOT NULL)`])
55
+ const appliedRaw = runSqlFile([`SELECT id FROM _migrations`], true)
56
+ const applied = new Set(Schema.decodeSync(QueryOutput)(appliedRaw).flatMap((batch) => (batch.results ?? []).map((row) => row.id)))
57
+
58
+ let count = 0
59
+ for (const migration of migrations) {
60
+ if (applied.has(migration.id)) continue
61
+ const now = new Date().toISOString()
62
+ console.log(`Applying migration ${migration.id} (${remote ? 'remote' : 'local'})...`)
63
+ runSqlFile([...migration.statements, `INSERT INTO _migrations (id, applied_at) VALUES (${quote(migration.id)}, ${quote(now)})`])
64
+ count++
65
+ }
66
+
67
+ console.log(count === 0 ? 'All migrations are already applied.' : `Applied ${count} migration(s).`)
@@ -4,5 +4,5 @@ import { UserActor } from '#server/core/http/session'
4
4
  import { EmailChangeRequestBody } from '#shared/utils/auth'
5
5
 
6
6
  export default handleAuthed({ body: EmailChangeRequestBody, limit: 'email-change' }, ({ body }) =>
7
- UserActor.use((actor) => EmailChange.use((change) => change.request(actor.id, body.email, body.password))),
7
+ UserActor.use((actor) => EmailChange.use((change) => change.request(actor.id, body.email, body.password, body.code))),
8
8
  )
@@ -6,11 +6,11 @@ import { UserActor, endUserSession } from '#server/core/http/session'
6
6
  import { DeleteAccountBody } from '#shared/utils/auth'
7
7
 
8
8
  export default handleAuthed(
9
- { body: DeleteAccountBody },
9
+ { body: DeleteAccountBody, limit: 'sign-in' },
10
10
  ({ body }, event) =>
11
11
  Effect.gen(function* () {
12
12
  const actor = yield* UserActor
13
- yield* Identity.use((identity) => identity.deleteAccount(actor.id, body.confirm))
13
+ yield* Identity.use((identity) => identity.deleteAccount(actor.id, body))
14
14
  yield* endUserSession(event)
15
15
  }),
16
16
  { verification: 'allow-unverified' },
@@ -0,0 +1,8 @@
1
+ import { Identity } from '#server/app/identity/service'
2
+ import { handleAuthed } from '#server/core/http/handle'
3
+ import { UserActor, requestSessionId } from '#server/core/http/session'
4
+ import { SetPasswordBody } from '#shared/utils/auth'
5
+
6
+ export default handleAuthed({ body: SetPasswordBody, limit: 'sign-in' }, ({ body }, event) =>
7
+ UserActor.use((actor) => Identity.use((identity) => identity.setPassword(actor.id, { ...body, keepSessionId: requestSessionId(event) }))),
8
+ )
@@ -5,7 +5,7 @@ import { handlePublic } from '#server/core/http/handle'
5
5
  import { endUserSession } from '#server/core/http/session'
6
6
  import { TokenBody } from '#shared/utils/auth'
7
7
 
8
- export default handlePublic({ body: TokenBody }, ({ body }, event) =>
8
+ export default handlePublic({ body: TokenBody, limit: 'email-change' }, ({ body }, event) =>
9
9
  Effect.gen(function* () {
10
10
  yield* EmailChange.use((change) => change.confirm(body.token))
11
11
  yield* endUserSession(event)
@@ -1,14 +1,18 @@
1
1
  import { Effect } from 'effect'
2
2
 
3
3
  import { Totp } from '#server/app/identity/totp'
4
- import { handlePublic } from '#server/core/http/handle'
4
+ import { clearTotpChallengeCookie, handlePublic, totpChallengeCookieOf } from '#server/core/http/handle'
5
5
  import { establishUserSession } from '#server/core/http/session'
6
+ import { Unauthorized } from '#shared/domain/errors'
6
7
  import { AuthUserView, LoginTotpBody } from '#shared/utils/auth'
7
8
 
8
9
  export default handlePublic({ body: LoginTotpBody, response: AuthUserView, limit: 'totp' }, ({ body }, event) =>
9
10
  Effect.gen(function* () {
11
+ const challenge = body.challenge ?? totpChallengeCookieOf(event)
12
+ if (!challenge) return yield* new Unauthorized({ message: 'Your sign-in challenge expired. Sign in again.' })
10
13
  const totp = yield* Totp
11
- const user = yield* totp.verifyChallenge(body.challenge, body.code)
14
+ const user = yield* totp.verifyChallenge(challenge, body.code)
15
+ clearTotpChallengeCookie(event)
12
16
  yield* establishUserSession(event, user)
13
17
  return user
14
18
  }),
@@ -1,16 +1,18 @@
1
1
  import { Effect } from 'effect'
2
2
 
3
3
  import { Identity } from '#server/app/identity/service'
4
- import { handlePublic } from '#server/core/http/handle'
4
+ import { handlePublic, setTotpChallengeCookie } from '#server/core/http/handle'
5
5
  import { establishUserSession } from '#server/core/http/session'
6
6
  import { LoginBody, LoginResponse } from '#shared/utils/auth'
7
7
 
8
- export default handlePublic({ body: LoginBody, response: LoginResponse, limit: 'sign-in' }, ({ body }, event) =>
8
+ export default handlePublic({ body: LoginBody, response: LoginResponse, limit: 'sign-in', captcha: true }, ({ body }, event) =>
9
9
  Effect.gen(function* () {
10
10
  const identity = yield* Identity
11
11
  const outcome = yield* identity.login(body)
12
12
  if (outcome.status === 'authenticated') {
13
13
  yield* establishUserSession(event, outcome.user)
14
+ } else {
15
+ setTotpChallengeCookie(event, outcome.challenge)
14
16
  }
15
17
  return outcome
16
18
  }),
@@ -12,7 +12,7 @@ export default handlePublic({ body: RegisterBody, response: AuthUserView, limit:
12
12
  const verification = yield* EmailVerification
13
13
  const user = yield* identity.register(body)
14
14
  yield* establishUserSession(event, user)
15
- yield* verification.send(user.id).pipe(Effect.ignore)
15
+ yield* verification.send(user.id).pipe(Effect.catch((error) => Effect.logWarning(`Initial verification send skipped (${error._tag}): ${error.message}`)))
16
16
  return user
17
17
  }),
18
18
  )
@@ -5,7 +5,7 @@ import { handlePublic } from '#server/core/http/handle'
5
5
  import { requestUser, updateUserSessionMetadata } from '#server/core/http/session'
6
6
  import { TokenBody } from '#shared/utils/auth'
7
7
 
8
- export default handlePublic({ body: TokenBody }, ({ body }, event) =>
8
+ export default handlePublic({ body: TokenBody, limit: 'verify' }, ({ body }, event) =>
9
9
  Effect.gen(function* () {
10
10
  const { userId } = yield* EmailVerification.use((verification) => verification.confirm(body.token))
11
11
  const current = requestUser(event)