@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.
- package/README.md +3 -1
- package/dist/cli.js +3 -1
- package/dist/template/.github/workflows/ci.yml +3 -1
- package/dist/template/CLAUDE.md +4 -2
- package/dist/template/app/components/turnstile-widget.vue +81 -0
- package/dist/template/app/composables/use-auth.ts +418 -0
- package/dist/template/app/pages/account.vue +125 -11
- package/dist/template/app/pages/email/[token].vue +18 -0
- package/dist/template/app/pages/forgot-password.vue +28 -0
- package/dist/template/app/pages/login.vue +9 -73
- package/dist/template/app/pages/register.vue +4 -26
- package/dist/template/app/pages/reset/[token].vue +31 -0
- package/dist/template/app/pages/verify/[token].vue +18 -0
- package/dist/template/nuxt.config.ts +4 -0
- package/dist/template/package.json +2 -0
- package/dist/template/scripts/admin-password.ts +13 -6
- package/dist/template/scripts/migrate.ts +67 -0
- package/dist/template/server/api/account/email/index.post.ts +1 -1
- package/dist/template/server/api/account/index.delete.ts +2 -2
- package/dist/template/server/api/account/password.post.ts +8 -0
- package/dist/template/server/api/auth/email/index.post.ts +1 -1
- package/dist/template/server/api/auth/login/totp.post.ts +6 -2
- package/dist/template/server/api/auth/login.post.ts +4 -2
- package/dist/template/server/api/auth/register.post.ts +1 -1
- package/dist/template/server/api/auth/verify/index.post.ts +1 -1
- package/dist/template/server/app/admin/auth.ts +2 -1
- package/dist/template/server/app/features.ts +4 -3
- package/dist/template/server/app/identity/email-change.ts +44 -7
- package/dist/template/server/app/identity/identity.test.ts +70 -0
- package/dist/template/server/app/identity/lockout.ts +8 -3
- package/dist/template/server/app/identity/password-reset.ts +3 -1
- package/dist/template/server/app/identity/service.ts +149 -30
- package/dist/template/server/app/identity/sessions.ts +43 -20
- package/dist/template/server/app/identity/totp-crypto.ts +12 -5
- package/dist/template/server/app/identity/totp.ts +24 -15
- package/dist/template/server/app/identity/verification.ts +3 -1
- package/dist/template/server/app/maintenance/cleanup.test.ts +56 -0
- package/dist/template/server/app/maintenance/cleanup.ts +63 -0
- package/dist/template/server/core/db/atomic.ts +9 -11
- package/dist/template/server/core/db/migrations.ts +7 -0
- package/dist/template/server/core/db/migrator.ts +5 -1
- package/dist/template/server/core/http/body.ts +1 -1
- package/dist/template/server/core/http/handle.ts +89 -81
- package/dist/template/server/core/http/security.test.ts +38 -0
- package/dist/template/server/core/http/security.ts +17 -5
- package/dist/template/server/core/http/session.ts +15 -0
- package/dist/template/server/core/platform/crypto-and-window.test.ts +75 -0
- package/dist/template/server/core/platform/database.ts +16 -1
- package/dist/template/server/core/platform/pii.ts +5 -8
- package/dist/template/server/core/platform/rate-limiter-strict.ts +35 -5
- package/dist/template/server/core/platform/rate-limiter.ts +2 -2
- package/dist/template/server/core/platform/seal.ts +20 -21
- package/dist/template/server/core/platform/sliding-window.ts +11 -2
- package/dist/template/server/core/platform/tokens.ts +3 -1
- package/dist/template/server/middleware/00-security-headers.ts +8 -4
- package/dist/template/server/middleware/01-user-session.ts +17 -5
- package/dist/template/server/plugins/page-csp.ts +24 -4
- package/dist/template/server/plugins/sessions.ts +4 -2
- package/dist/template/server/routes/auth/github.get.ts +4 -3
- package/dist/template/server/routes/auth/google.get.ts +4 -2
- package/dist/template/server/tasks/cleanup.ts +15 -0
- package/dist/template/server/test/invariants.test.ts +4 -2
- package/dist/template/server/utils/define-validated-handler.ts +14 -12
- package/dist/template/shared/domain/errors.ts +1 -0
- package/dist/template/shared/types/auth.d.ts +1 -1
- package/dist/template/shared/utils/auth.ts +10 -4
- package/dist/template/shared/utils/paths.ts +2 -0
- package/dist/template/shared/utils/schema-validation.ts +1 -1
- package/dist/template/wrangler.json +17 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,9 +8,11 @@ CLI scaffolder and starter template for **Nuxt 5 + Nitro + Cloudflare Workers +
|
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
10
|
bun create @humanonlyweb/nuxtflare@latest my-project
|
|
11
|
+
# or with npm
|
|
12
|
+
npm create @humanonlyweb/nuxtflare@latest my-project
|
|
11
13
|
```
|
|
12
14
|
|
|
13
|
-
Non-interactive with flags:
|
|
15
|
+
Non-interactive with flags (`--` separates `bun create` / `npm create` flags from template flags):
|
|
14
16
|
|
|
15
17
|
```bash
|
|
16
18
|
bun create @humanonlyweb/nuxtflare@latest my-project -- -y \
|
package/dist/cli.js
CHANGED
|
@@ -6,7 +6,7 @@ import { basename as basename2, resolve as resolve2 } from "node:path";
|
|
|
6
6
|
// package.json
|
|
7
7
|
var package_default = {
|
|
8
8
|
name: "@humanonlyweb/create-nuxtflare",
|
|
9
|
-
version: "0.1
|
|
9
|
+
version: "0.2.1",
|
|
10
10
|
description: "Scaffold a Nuxt 5 + Cloudflare Workers + D1 + Effect v4 app with explicit auth, TOTP 2FA, and admin.",
|
|
11
11
|
license: "MIT",
|
|
12
12
|
repository: {
|
|
@@ -154,6 +154,8 @@ var scaffold = (options) => {
|
|
|
154
154
|
admin: ${options.features.admin},
|
|
155
155
|
} as const`).replace(`title: 'Nuxtflare App'`, `title: '${options.appName.replaceAll("'", "\\'")}'`).replace(`appUrl: 'https://example.com'`, `appUrl: 'https://${options.domain}'`).replace(`adminEmails: 'admin@example.test'`, `adminEmails: 'admin@${options.slug}.test'`).replace(`appName: text('Nuxtflare App'`, `appName: text('${options.appName.replaceAll("'", "\\'")}'`).replace(`mailFrom: text('Nuxtflare App <no-reply@example.com>'`, `mailFrom: text('${options.appName.replaceAll("'", "\\'")} <no-reply@${options.domain}>'`).replace(`name: 'app-session'`, `name: '${options.cookiePrefix}-session'`));
|
|
156
156
|
replaceInFile(join(targetDir, "shared/utils/admin.ts"), (content) => content.replace(`ADMIN_COOKIE = 'app_admin'`, `ADMIN_COOKIE = '${options.cookiePrefix}_admin'`));
|
|
157
|
+
replaceInFile(join(targetDir, "server/core/http/handle.ts"), (content) => content.replace(`TOTP_CHALLENGE_COOKIE = 'app_totp'`, `TOTP_CHALLENGE_COOKIE = '${options.cookiePrefix}_totp'`));
|
|
158
|
+
replaceInFile(join(targetDir, "app/composables/use-auth.ts"), (content) => content.replace(`app_next=`, `${options.cookiePrefix}_next=`));
|
|
157
159
|
replaceInFile(join(targetDir, "server/routes/auth/google.get.ts"), (content) => content.replaceAll(`'app_next'`, `'${options.cookiePrefix}_next'`));
|
|
158
160
|
replaceInFile(join(targetDir, "server/routes/auth/github.get.ts"), (content) => content.replaceAll(`'app_next'`, `'${options.cookiePrefix}_next'`).replace(`'nuxtflare-oauth'`, `'${options.slug}-oauth'`));
|
|
159
161
|
replaceInFile(join(targetDir, ".github/workflows/ci.yml"), (content) => content.replace(`url: https://example.com`, `url: https://${options.domain}`));
|
|
@@ -91,6 +91,8 @@ jobs:
|
|
|
91
91
|
- name: Install dependencies
|
|
92
92
|
run: bun install --frozen-lockfile
|
|
93
93
|
|
|
94
|
-
|
|
94
|
+
- name: Apply D1 migrations
|
|
95
|
+
run: bun run db:migrate:remote
|
|
96
|
+
|
|
95
97
|
- name: Build and deploy the Worker
|
|
96
98
|
run: bun run deploy
|
package/dist/template/CLAUDE.md
CHANGED
|
@@ -5,11 +5,13 @@ Nuxt 5 / Nitro on one Cloudflare Worker, D1 via `useDatabase()` (no ORM), Effect
|
|
|
5
5
|
## Architecture
|
|
6
6
|
|
|
7
7
|
- `server/core/`: Platform ports (`Database`, `AtomicBatch`, `Kv`, `Pii`, `Seal`, `Tokens`, `PasswordHasher`, `IdGenerator`, `RateLimiter`, `Turnstile`, `Mailer`, `EmailAssets`), HTTP handlers (`handlePublic`, `handleAuthed`, `handleAdmin`), migrations, and `app-layer.ts`.
|
|
8
|
-
- `server/app/`: Domain features (`identity/`, `notifications/`, `admin/`, plus your own features) composed once in `server/app/features.ts`.
|
|
8
|
+
- `server/app/`: Domain features (`identity/`, `notifications/`, `admin/`, `maintenance/`, plus your own features) composed once in `server/app/features.ts`.
|
|
9
|
+
- `server/tasks/`: Nitro scheduled tasks (`cleanup.ts`, wired to Cloudflare Cron Triggers via `nitro.scheduledTasks`).
|
|
9
10
|
- `server/assets/email/`: Nitro server-asset HTML layout and blocks rendered by `EmailRenderer` (both HTML and plain text). Preview all templates in dev at `/emails`.
|
|
10
11
|
- `server/api/`: Thin routes. Routes validate schemas, delegate to Effect services, and encode responses — no business logic.
|
|
11
12
|
- `server/cloudflare/exports/`: Durable Objects (`RateLimitCounter`). Exported from root `server.ts`.
|
|
12
|
-
- `
|
|
13
|
+
- `scripts/`: Operational CLI scripts (`migrate.ts` for deploy-time D1 migrations, `admin-password.ts` for setting admin passwords).
|
|
14
|
+
- `shared/`: Schemas, branded IDs, and tagged domain errors shared by server and client. Keep pure client helpers (like `shared/utils/paths.ts`) out of `effect` `Schema` modules so client bundles stay lean.
|
|
13
15
|
|
|
14
16
|
## Core Design Principles (Apply Everywhere)
|
|
15
17
|
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
interface TurnstileApi {
|
|
3
|
+
readonly render: (
|
|
4
|
+
container: HTMLElement,
|
|
5
|
+
options: {
|
|
6
|
+
readonly sitekey: string
|
|
7
|
+
readonly callback: (token: string) => void
|
|
8
|
+
readonly 'expired-callback': () => void
|
|
9
|
+
readonly 'error-callback': () => void
|
|
10
|
+
},
|
|
11
|
+
) => string
|
|
12
|
+
readonly reset: (widgetId?: string) => void
|
|
13
|
+
readonly remove: (widgetId: string) => void
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
declare global {
|
|
17
|
+
interface Window {
|
|
18
|
+
turnstile?: TurnstileApi
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const SCRIPT_URL = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'
|
|
23
|
+
|
|
24
|
+
const token = defineModel<string>({ default: '' })
|
|
25
|
+
const siteKey = useRuntimeConfig().public.turnstileSiteKey
|
|
26
|
+
const container = useTemplateRef('container')
|
|
27
|
+
let widgetId: string | undefined
|
|
28
|
+
|
|
29
|
+
const loadScript = (): Promise<TurnstileApi | undefined> => {
|
|
30
|
+
if (window.turnstile) return Promise.resolve(window.turnstile)
|
|
31
|
+
const existing = document.querySelector<HTMLScriptElement>(`script[src="${SCRIPT_URL}"]`)
|
|
32
|
+
if (existing) {
|
|
33
|
+
return new Promise((resolve) => {
|
|
34
|
+
existing.addEventListener('load', () => resolve(window.turnstile), { once: true })
|
|
35
|
+
existing.addEventListener('error', () => resolve(undefined), { once: true })
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
return new Promise((resolve) => {
|
|
39
|
+
const script = document.createElement('script')
|
|
40
|
+
script.src = SCRIPT_URL
|
|
41
|
+
script.async = true
|
|
42
|
+
script.defer = true
|
|
43
|
+
script.addEventListener('load', () => resolve(window.turnstile), { once: true })
|
|
44
|
+
script.addEventListener('error', () => resolve(undefined), { once: true })
|
|
45
|
+
document.head.appendChild(script)
|
|
46
|
+
})
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const reset = () => {
|
|
50
|
+
token.value = ''
|
|
51
|
+
if (widgetId && window.turnstile) window.turnstile.reset(widgetId)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
onMounted(async () => {
|
|
55
|
+
if (!siteKey || !container.value) return
|
|
56
|
+
const api = await loadScript()
|
|
57
|
+
if (!api || !container.value) return
|
|
58
|
+
widgetId = api.render(container.value, {
|
|
59
|
+
sitekey: siteKey,
|
|
60
|
+
callback: (next) => {
|
|
61
|
+
token.value = next
|
|
62
|
+
},
|
|
63
|
+
'expired-callback': () => {
|
|
64
|
+
token.value = ''
|
|
65
|
+
},
|
|
66
|
+
'error-callback': () => {
|
|
67
|
+
token.value = ''
|
|
68
|
+
},
|
|
69
|
+
})
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
onBeforeUnmount(() => {
|
|
73
|
+
if (widgetId && window.turnstile) window.turnstile.remove(widgetId)
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
defineExpose({ reset })
|
|
77
|
+
</script>
|
|
78
|
+
|
|
79
|
+
<template>
|
|
80
|
+
<div v-if="siteKey" ref="container" />
|
|
81
|
+
</template>
|
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import { isLocalPath } from '#shared/utils/paths'
|
|
2
|
+
import { problemOf } from '~/utils/api-error'
|
|
3
|
+
|
|
4
|
+
export type LoginStep = { readonly kind: 'credentials' } | { readonly kind: 'totp'; readonly challenge?: string }
|
|
5
|
+
export type ForgotStep = { readonly kind: 'form' } | { readonly kind: 'sent' }
|
|
6
|
+
export type ResetStep =
|
|
7
|
+
| { readonly kind: 'checking' }
|
|
8
|
+
| { readonly kind: 'invalid'; readonly message: string }
|
|
9
|
+
| { readonly kind: 'form'; readonly token: string }
|
|
10
|
+
| { readonly kind: 'done' }
|
|
11
|
+
export type VerifyStep = { readonly kind: 'verifying' } | { readonly kind: 'verified' } | { readonly kind: 'error'; readonly message: string }
|
|
12
|
+
export type EmailChangeStep = { readonly kind: 'confirming' } | { readonly kind: 'confirmed' } | { readonly kind: 'error'; readonly message: string }
|
|
13
|
+
|
|
14
|
+
const OAUTH_ERRORS: Readonly<Record<string, string>> = {
|
|
15
|
+
google: 'Google sign-in failed. Please try again.',
|
|
16
|
+
'google-email': 'That email address is already linked to another Google account.',
|
|
17
|
+
'google-disabled': 'Google sign-in is disabled.',
|
|
18
|
+
github: 'GitHub sign-in failed. Please try again.',
|
|
19
|
+
'github-email': 'That email address is already linked to another GitHub account.',
|
|
20
|
+
'github-disabled': 'GitHub sign-in is disabled.',
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const turnstileHeaders = (token: string) => (token ? { 'x-turnstile-token': token } : undefined)
|
|
24
|
+
|
|
25
|
+
const routeToken = (params: Record<string, unknown>): string => ('token' in params && typeof params.token === 'string' ? params.token : '')
|
|
26
|
+
|
|
27
|
+
export const useAuthLogin = () => {
|
|
28
|
+
const route = useRoute()
|
|
29
|
+
const { fetch: refreshSession } = useUserSession()
|
|
30
|
+
|
|
31
|
+
const step = ref<LoginStep>(route.query.totp === '1' ? { kind: 'totp' } : { kind: 'credentials' })
|
|
32
|
+
const identity = ref('')
|
|
33
|
+
const password = ref('')
|
|
34
|
+
const code = ref('')
|
|
35
|
+
const turnstileToken = ref('')
|
|
36
|
+
const busy = ref(false)
|
|
37
|
+
const initialError = typeof route.query.error === 'string' ? (OAUTH_ERRORS[route.query.error] ?? '') : ''
|
|
38
|
+
const errorMessage = ref(initialError)
|
|
39
|
+
|
|
40
|
+
const destination = () => {
|
|
41
|
+
const next = typeof route.query.next === 'string' ? route.query.next : ''
|
|
42
|
+
return isLocalPath(next) ? next : '/account'
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const rememberOAuthNext = () => {
|
|
46
|
+
const next = typeof route.query.next === 'string' ? route.query.next : ''
|
|
47
|
+
if (!isLocalPath(next)) return
|
|
48
|
+
const secure = location.protocol === 'https:' ? '; Secure' : ''
|
|
49
|
+
document.cookie = `app_next=${encodeURIComponent(next)}; Path=/auth; Max-Age=600; SameSite=Lax${secure}`
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const submitCredentials = async (onResetCaptcha?: () => void) => {
|
|
53
|
+
errorMessage.value = ''
|
|
54
|
+
busy.value = true
|
|
55
|
+
try {
|
|
56
|
+
const result = await $fetch('/api/auth/login', {
|
|
57
|
+
method: 'POST',
|
|
58
|
+
body: { identity: identity.value, password: password.value },
|
|
59
|
+
headers: turnstileHeaders(turnstileToken.value),
|
|
60
|
+
})
|
|
61
|
+
if (result.status === 'totp_required') {
|
|
62
|
+
password.value = ''
|
|
63
|
+
step.value = { kind: 'totp', challenge: result.challenge }
|
|
64
|
+
return
|
|
65
|
+
}
|
|
66
|
+
await refreshSession()
|
|
67
|
+
await navigateTo(destination())
|
|
68
|
+
} catch (error) {
|
|
69
|
+
errorMessage.value = problemOf(error).message
|
|
70
|
+
onResetCaptcha?.()
|
|
71
|
+
} finally {
|
|
72
|
+
busy.value = false
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const submitTotp = async () => {
|
|
77
|
+
if (step.value.kind !== 'totp') return
|
|
78
|
+
errorMessage.value = ''
|
|
79
|
+
busy.value = true
|
|
80
|
+
try {
|
|
81
|
+
await $fetch('/api/auth/login/totp', {
|
|
82
|
+
method: 'POST',
|
|
83
|
+
body: step.value.challenge ? { challenge: step.value.challenge, code: code.value } : { code: code.value },
|
|
84
|
+
})
|
|
85
|
+
await refreshSession()
|
|
86
|
+
await navigateTo(destination())
|
|
87
|
+
} catch (error) {
|
|
88
|
+
errorMessage.value = problemOf(error).message
|
|
89
|
+
} finally {
|
|
90
|
+
busy.value = false
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const backToCredentials = () => {
|
|
95
|
+
code.value = ''
|
|
96
|
+
errorMessage.value = ''
|
|
97
|
+
step.value = { kind: 'credentials' }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return {
|
|
101
|
+
step,
|
|
102
|
+
identity,
|
|
103
|
+
password,
|
|
104
|
+
code,
|
|
105
|
+
turnstileToken,
|
|
106
|
+
busy,
|
|
107
|
+
errorMessage,
|
|
108
|
+
rememberOAuthNext,
|
|
109
|
+
submitCredentials,
|
|
110
|
+
submitTotp,
|
|
111
|
+
backToCredentials,
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export const useAuthRegister = () => {
|
|
116
|
+
const { fetch: refreshSession } = useUserSession()
|
|
117
|
+
const username = ref('')
|
|
118
|
+
const email = ref('')
|
|
119
|
+
const password = ref('')
|
|
120
|
+
const turnstileToken = ref('')
|
|
121
|
+
const busy = ref(false)
|
|
122
|
+
const errorMessage = ref('')
|
|
123
|
+
|
|
124
|
+
const submit = async (onResetCaptcha?: () => void) => {
|
|
125
|
+
errorMessage.value = ''
|
|
126
|
+
busy.value = true
|
|
127
|
+
try {
|
|
128
|
+
await $fetch('/api/auth/register', {
|
|
129
|
+
method: 'POST',
|
|
130
|
+
body: { username: username.value, email: email.value, password: password.value },
|
|
131
|
+
headers: turnstileHeaders(turnstileToken.value),
|
|
132
|
+
})
|
|
133
|
+
await refreshSession()
|
|
134
|
+
await navigateTo('/account')
|
|
135
|
+
} catch (error) {
|
|
136
|
+
errorMessage.value = problemOf(error).message
|
|
137
|
+
onResetCaptcha?.()
|
|
138
|
+
} finally {
|
|
139
|
+
busy.value = false
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return { username, email, password, turnstileToken, busy, errorMessage, submit }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export const useForgotPassword = () => {
|
|
147
|
+
const step = ref<ForgotStep>({ kind: 'form' })
|
|
148
|
+
const email = ref('')
|
|
149
|
+
const turnstileToken = ref('')
|
|
150
|
+
const busy = ref(false)
|
|
151
|
+
const errorMessage = ref('')
|
|
152
|
+
|
|
153
|
+
const submit = async (onResetCaptcha?: () => void) => {
|
|
154
|
+
errorMessage.value = ''
|
|
155
|
+
busy.value = true
|
|
156
|
+
try {
|
|
157
|
+
await $fetch('/api/auth/reset/request', {
|
|
158
|
+
method: 'POST',
|
|
159
|
+
body: { email: email.value },
|
|
160
|
+
headers: turnstileHeaders(turnstileToken.value),
|
|
161
|
+
})
|
|
162
|
+
step.value = { kind: 'sent' }
|
|
163
|
+
} catch (error) {
|
|
164
|
+
errorMessage.value = problemOf(error).message
|
|
165
|
+
onResetCaptcha?.()
|
|
166
|
+
} finally {
|
|
167
|
+
busy.value = false
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return { step, email, turnstileToken, busy, errorMessage, submit }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export const usePasswordReset = () => {
|
|
175
|
+
const route = useRoute()
|
|
176
|
+
const step = ref<ResetStep>({ kind: 'checking' })
|
|
177
|
+
const password = ref('')
|
|
178
|
+
const confirm = ref('')
|
|
179
|
+
const busy = ref(false)
|
|
180
|
+
const errorMessage = ref('')
|
|
181
|
+
|
|
182
|
+
onMounted(async () => {
|
|
183
|
+
const token = routeToken(route.params)
|
|
184
|
+
if (!token) {
|
|
185
|
+
step.value = { kind: 'invalid', message: 'This password reset link is invalid or has expired.' }
|
|
186
|
+
return
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
await $fetch('/api/auth/reset/check', { method: 'POST', body: { token } })
|
|
190
|
+
step.value = { kind: 'form', token }
|
|
191
|
+
} catch (error) {
|
|
192
|
+
step.value = { kind: 'invalid', message: problemOf(error).message }
|
|
193
|
+
}
|
|
194
|
+
})
|
|
195
|
+
|
|
196
|
+
const submit = async () => {
|
|
197
|
+
if (step.value.kind !== 'form') return
|
|
198
|
+
errorMessage.value = ''
|
|
199
|
+
if (password.value !== confirm.value) {
|
|
200
|
+
errorMessage.value = 'Passwords do not match.'
|
|
201
|
+
return
|
|
202
|
+
}
|
|
203
|
+
busy.value = true
|
|
204
|
+
try {
|
|
205
|
+
await $fetch('/api/auth/reset', {
|
|
206
|
+
method: 'POST',
|
|
207
|
+
body: { token: step.value.token, password: password.value },
|
|
208
|
+
})
|
|
209
|
+
password.value = ''
|
|
210
|
+
confirm.value = ''
|
|
211
|
+
step.value = { kind: 'done' }
|
|
212
|
+
} catch (error) {
|
|
213
|
+
errorMessage.value = problemOf(error).message
|
|
214
|
+
} finally {
|
|
215
|
+
busy.value = false
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return { step, password, confirm, busy, errorMessage, submit }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export const useEmailVerify = () => {
|
|
223
|
+
const route = useRoute()
|
|
224
|
+
const { loggedIn, fetch: refreshSession } = useUserSession()
|
|
225
|
+
const step = ref<VerifyStep>({ kind: 'verifying' })
|
|
226
|
+
|
|
227
|
+
onMounted(async () => {
|
|
228
|
+
const token = routeToken(route.params)
|
|
229
|
+
if (!token) {
|
|
230
|
+
step.value = { kind: 'error', message: 'This verification link is invalid or has expired.' }
|
|
231
|
+
return
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
await $fetch('/api/auth/verify', { method: 'POST', body: { token } })
|
|
235
|
+
if (loggedIn.value) await refreshSession()
|
|
236
|
+
step.value = { kind: 'verified' }
|
|
237
|
+
} catch (error) {
|
|
238
|
+
step.value = { kind: 'error', message: problemOf(error).message }
|
|
239
|
+
}
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
return { step, loggedIn }
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export const useEmailChangeConfirm = () => {
|
|
246
|
+
const route = useRoute()
|
|
247
|
+
const { clear } = useUserSession()
|
|
248
|
+
const step = ref<EmailChangeStep>({ kind: 'confirming' })
|
|
249
|
+
|
|
250
|
+
onMounted(async () => {
|
|
251
|
+
const token = routeToken(route.params)
|
|
252
|
+
if (!token) {
|
|
253
|
+
step.value = { kind: 'error', message: 'This email confirmation link is invalid or has expired.' }
|
|
254
|
+
return
|
|
255
|
+
}
|
|
256
|
+
try {
|
|
257
|
+
await $fetch('/api/auth/email', { method: 'POST', body: { token } })
|
|
258
|
+
await clear()
|
|
259
|
+
step.value = { kind: 'confirmed' }
|
|
260
|
+
} catch (error) {
|
|
261
|
+
step.value = { kind: 'error', message: problemOf(error).message }
|
|
262
|
+
}
|
|
263
|
+
})
|
|
264
|
+
|
|
265
|
+
return { step }
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export const useAccount = async () => {
|
|
269
|
+
const { data: me, refresh: refreshMe } = await useMe()
|
|
270
|
+
const features = useFeatures()
|
|
271
|
+
const { clear, fetch: refreshSession } = useUserSession()
|
|
272
|
+
|
|
273
|
+
const canUseVerifiedActions = computed(() => Boolean(me.value && (!features.emailVerificationRequired || me.value.emailStatus === 'verified')))
|
|
274
|
+
|
|
275
|
+
const { data: sessionList, refresh: refreshSessions } = await useFetch('/api/account/sessions', {
|
|
276
|
+
immediate: canUseVerifiedActions.value,
|
|
277
|
+
default: () => ({ sessions: [] }),
|
|
278
|
+
})
|
|
279
|
+
|
|
280
|
+
const username = ref(me.value?.username ?? '')
|
|
281
|
+
const nextEmail = ref('')
|
|
282
|
+
const emailPassword = ref('')
|
|
283
|
+
const emailCode = ref('')
|
|
284
|
+
const currentPassword = ref('')
|
|
285
|
+
const newPassword = ref('')
|
|
286
|
+
const passwordCode = ref('')
|
|
287
|
+
const deleteConfirm = ref('')
|
|
288
|
+
const deletePassword = ref('')
|
|
289
|
+
const deleteCode = ref('')
|
|
290
|
+
const busy = ref(false)
|
|
291
|
+
const notice = ref('')
|
|
292
|
+
const errorMessage = ref('')
|
|
293
|
+
|
|
294
|
+
const runAction = async (work: () => Promise<void>, successMessage?: string) => {
|
|
295
|
+
errorMessage.value = ''
|
|
296
|
+
notice.value = ''
|
|
297
|
+
busy.value = true
|
|
298
|
+
try {
|
|
299
|
+
await work()
|
|
300
|
+
if (successMessage) notice.value = successMessage
|
|
301
|
+
} catch (error) {
|
|
302
|
+
errorMessage.value = problemOf(error).message
|
|
303
|
+
} finally {
|
|
304
|
+
busy.value = false
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const signOut = () =>
|
|
309
|
+
runAction(async () => {
|
|
310
|
+
await $fetch('/api/auth/logout', { method: 'POST' })
|
|
311
|
+
await clear()
|
|
312
|
+
await navigateTo('/login')
|
|
313
|
+
})
|
|
314
|
+
|
|
315
|
+
const signOutEverywhere = () =>
|
|
316
|
+
runAction(async () => {
|
|
317
|
+
await $fetch('/api/auth/logout-everywhere', { method: 'POST' })
|
|
318
|
+
await clear()
|
|
319
|
+
await navigateTo('/login')
|
|
320
|
+
})
|
|
321
|
+
|
|
322
|
+
const resendVerification = () =>
|
|
323
|
+
runAction(async () => {
|
|
324
|
+
await $fetch('/api/auth/verify/send', { method: 'POST' })
|
|
325
|
+
}, 'Verification email sent.')
|
|
326
|
+
|
|
327
|
+
const saveProfile = () =>
|
|
328
|
+
runAction(async () => {
|
|
329
|
+
const updated = await $fetch('/api/account', { method: 'PATCH', body: { username: username.value } })
|
|
330
|
+
username.value = updated.username
|
|
331
|
+
await Promise.all([refreshMe(), refreshSession()])
|
|
332
|
+
}, 'Username updated.')
|
|
333
|
+
|
|
334
|
+
const requestEmailChange = () =>
|
|
335
|
+
runAction(async () => {
|
|
336
|
+
await $fetch('/api/account/email', {
|
|
337
|
+
method: 'POST',
|
|
338
|
+
body: {
|
|
339
|
+
email: nextEmail.value,
|
|
340
|
+
password: emailPassword.value,
|
|
341
|
+
...(emailCode.value ? { code: emailCode.value } : {}),
|
|
342
|
+
},
|
|
343
|
+
})
|
|
344
|
+
nextEmail.value = ''
|
|
345
|
+
emailPassword.value = ''
|
|
346
|
+
emailCode.value = ''
|
|
347
|
+
await refreshMe()
|
|
348
|
+
}, 'Check your new email address for a confirmation link.')
|
|
349
|
+
|
|
350
|
+
const cancelEmailChange = () =>
|
|
351
|
+
runAction(async () => {
|
|
352
|
+
await $fetch('/api/account/email', { method: 'DELETE' })
|
|
353
|
+
await refreshMe()
|
|
354
|
+
}, 'Pending email change cancelled.')
|
|
355
|
+
|
|
356
|
+
const savePassword = () =>
|
|
357
|
+
runAction(
|
|
358
|
+
async () => {
|
|
359
|
+
const hadPassword = Boolean(me.value?.hasPassword)
|
|
360
|
+
await $fetch('/api/account/password', {
|
|
361
|
+
method: 'POST',
|
|
362
|
+
body: {
|
|
363
|
+
...(hadPassword && currentPassword.value ? { currentPassword: currentPassword.value } : {}),
|
|
364
|
+
newPassword: newPassword.value,
|
|
365
|
+
...(passwordCode.value ? { code: passwordCode.value } : {}),
|
|
366
|
+
},
|
|
367
|
+
})
|
|
368
|
+
currentPassword.value = ''
|
|
369
|
+
newPassword.value = ''
|
|
370
|
+
passwordCode.value = ''
|
|
371
|
+
await Promise.all([refreshMe(), refreshSessions()])
|
|
372
|
+
},
|
|
373
|
+
me.value?.hasPassword ? 'Password updated and other sessions signed out.' : 'Password set.',
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
const deleteAccount = () =>
|
|
377
|
+
runAction(async () => {
|
|
378
|
+
await $fetch('/api/account', {
|
|
379
|
+
method: 'DELETE',
|
|
380
|
+
body: {
|
|
381
|
+
confirm: deleteConfirm.value,
|
|
382
|
+
...(deletePassword.value ? { password: deletePassword.value } : {}),
|
|
383
|
+
...(deleteCode.value ? { code: deleteCode.value } : {}),
|
|
384
|
+
},
|
|
385
|
+
})
|
|
386
|
+
await clear()
|
|
387
|
+
await navigateTo('/login')
|
|
388
|
+
})
|
|
389
|
+
|
|
390
|
+
return {
|
|
391
|
+
me,
|
|
392
|
+
features,
|
|
393
|
+
canUseVerifiedActions,
|
|
394
|
+
sessionList,
|
|
395
|
+
username,
|
|
396
|
+
nextEmail,
|
|
397
|
+
emailPassword,
|
|
398
|
+
emailCode,
|
|
399
|
+
currentPassword,
|
|
400
|
+
newPassword,
|
|
401
|
+
passwordCode,
|
|
402
|
+
deleteConfirm,
|
|
403
|
+
deletePassword,
|
|
404
|
+
deleteCode,
|
|
405
|
+
busy,
|
|
406
|
+
notice,
|
|
407
|
+
errorMessage,
|
|
408
|
+
refreshSessions,
|
|
409
|
+
signOut,
|
|
410
|
+
signOutEverywhere,
|
|
411
|
+
resendVerification,
|
|
412
|
+
saveProfile,
|
|
413
|
+
savePassword,
|
|
414
|
+
requestEmailChange,
|
|
415
|
+
cancelEmailChange,
|
|
416
|
+
deleteAccount,
|
|
417
|
+
}
|
|
418
|
+
}
|