tinyzoo 0.2.2 → 0.4.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 (72) hide show
  1. package/app/components/CmsDayPicker.vue +5 -1
  2. package/app/components/CmsFieldColor.vue +3 -3
  3. package/app/components/CmsFieldDate.vue +5 -3
  4. package/app/components/CmsFieldGallery.vue +1 -1
  5. package/app/components/CmsFieldRelationOne.vue +1 -1
  6. package/app/components/CmsFieldText.vue +1 -1
  7. package/app/components/CmsListFilters.vue +1 -1
  8. package/app/components/CmsMoment.vue +1 -1
  9. package/app/components/CmsPasswordInput.vue +1 -1
  10. package/app/components/CmsPreviewPanel.vue +4 -4
  11. package/app/components/CmsPublishReview.vue +1 -1
  12. package/app/components/CmsRevisions.vue +1 -1
  13. package/app/components/CmsRichTextEditor.vue +3 -3
  14. package/app/components/CmsSingletonForm.vue +1 -1
  15. package/app/components/CmsTreeList.vue +3 -3
  16. package/app/i18n/cs.ts +43 -0
  17. package/app/i18n/de.ts +43 -0
  18. package/app/i18n/en.ts +43 -0
  19. package/app/middleware/cms-auth.global.ts +1 -1
  20. package/app/pages/admin/[entity]/[id].vue +9 -9
  21. package/app/pages/admin/[entity]/index.vue +7 -7
  22. package/app/pages/admin/account.vue +96 -4
  23. package/app/pages/admin/email/[token].vue +70 -0
  24. package/app/pages/admin/email/revert/[token].vue +70 -0
  25. package/app/pages/admin/media.vue +1 -1
  26. package/app/pages/admin/privacy.vue +6 -2
  27. package/app/pages/admin/styleguide.vue +1 -1
  28. package/app/pages/admin/team.vue +75 -2
  29. package/app/utils/cmsIssues.ts +2 -0
  30. package/cli/generate.ts +2 -1
  31. package/cli/index.ts +1 -1
  32. package/cli/upgrade.ts +24 -6
  33. package/cli/versions.ts +2 -2
  34. package/forms/index.ts +0 -3
  35. package/module.ts +33 -9
  36. package/nuxt.config.ts +4 -3
  37. package/package.json +11 -12
  38. package/server/api/cms/_auth/email/[token].get.ts +16 -0
  39. package/server/api/cms/_auth/email/confirm.post.ts +73 -0
  40. package/server/api/cms/_auth/email/index.delete.ts +11 -0
  41. package/server/api/cms/_auth/email/index.get.ts +10 -0
  42. package/server/api/cms/_auth/email/index.post.ts +86 -0
  43. package/server/api/cms/_auth/email/revert/[token].get.ts +15 -0
  44. package/server/api/cms/_auth/email/revert.post.ts +68 -0
  45. package/server/api/cms/_auth/me.patch.ts +1 -1
  46. package/server/api/cms/_auth/password.post.ts +1 -1
  47. package/server/api/cms/_collab/socket.ts +68 -20
  48. package/server/api/cms/_live.ts +1 -1
  49. package/server/api/cms/_privacy/export.post.ts +5 -1
  50. package/server/api/cms/_privacy/lookup.post.ts +5 -2
  51. package/server/api/cms/_users/[id].delete.ts +3 -0
  52. package/server/api/cms/_users/[id].patch.ts +114 -13
  53. package/server/api/cms/_users/index.post.ts +2 -1
  54. package/server/middleware/cms-session.ts +2 -0
  55. package/server/plugins/cms-0-config-check.ts +32 -7
  56. package/server/store/redis.ts +9 -1
  57. package/server/utils/cmsAudit.ts +10 -2
  58. package/server/utils/cmsAuth.ts +42 -6
  59. package/server/utils/cmsCollabServer.ts +27 -12
  60. package/server/utils/cmsEmailChange.ts +193 -0
  61. package/server/utils/cmsEmailChangeRules.ts +108 -0
  62. package/server/utils/cmsEmails.ts +155 -9
  63. package/server/utils/cmsLive.ts +7 -4
  64. package/server/utils/cmsPrivacy.ts +60 -11
  65. package/server/utils/cmsRetention.ts +4 -0
  66. package/server/utils/cmsSession.ts +42 -9
  67. package/src/appSecret.ts +88 -0
  68. package/src/index.ts +1 -1
  69. package/src/presets.ts +1 -33
  70. package/src/system.ts +1 -1
  71. package/starter/.env.example +3 -2
  72. package/starter/package.json +4 -4
@@ -1,5 +1,5 @@
1
1
  <script setup lang="ts">
2
- // Your own account: name, interface language, password.
2
+ // Your own account: name, interface language, sign-in email, password.
3
3
  definePageMeta({ layout: 'admin' })
4
4
  const { t, locale, locales, setLocale } = useCmsI18n()
5
5
  const toast = useToast()
@@ -34,6 +34,59 @@ async function saveProfile() {
34
34
  }
35
35
  }
36
36
 
37
+ // ── sign-in email: asked for with the password, made when the link sent to the new address is opened ──
38
+ interface PendingEmail { email: string; expiresAt: string }
39
+ // Read in the browser after the page is shown: an async load in setup shifts the ids Nuxt UI gives this
40
+ // page's labels and fields between the server and the browser (every label pointed at nothing).
41
+ const pendingEmail = ref<PendingEmail | null>(null)
42
+ async function refreshEmailState() {
43
+ try {
44
+ pendingEmail.value = (await $fetch<{ pending: PendingEmail | null }>('/api/cms/_auth/email')).pending
45
+ }
46
+ catch {
47
+ pendingEmail.value = null // nothing to show; asking again still works
48
+ }
49
+ }
50
+ onMounted(refreshEmailState)
51
+ const emailChange = reactive({ email: '', password: '' })
52
+ const emailErrors = reactive<Record<string, string>>({})
53
+ const emailForm = ref<HTMLElement | null>(null)
54
+ const savingEmail = ref(false)
55
+ const cancellingEmail = ref(false)
56
+ async function requestEmailChange() {
57
+ Object.keys(emailErrors).forEach((k) => delete emailErrors[k])
58
+ savingEmail.value = true
59
+ try {
60
+ const res = await $fetch<{ pending: PendingEmail }>('/api/cms/_auth/email', { method: 'POST', body: emailChange })
61
+ pendingEmail.value = res.pending
62
+ Object.assign(emailChange, { email: '', password: '' })
63
+ toast.add({ title: t('account.emailSent'), description: res.pending.email, icon: 'i-lucide-mail-check', color: 'success' })
64
+ }
65
+ catch (err: any) {
66
+ const issues = err?.data?.data
67
+ if (Array.isArray(issues)) for (const i of issues) if (i.path?.[0]) emailErrors[i.path[0]] = cmsIssueMessage(i, null, t as any)
68
+ if (Object.keys(emailErrors).length) await cmsFocusInvalid(emailForm.value)
69
+ else toast.add({ title: t('team.actionFailed'), description: cmsRequestError(err, t as any), color: 'error', icon: 'i-lucide-x' })
70
+ }
71
+ finally {
72
+ savingEmail.value = false
73
+ }
74
+ }
75
+ async function cancelEmailChange() {
76
+ cancellingEmail.value = true
77
+ try {
78
+ await $fetch('/api/cms/_auth/email', { method: 'DELETE' })
79
+ await refreshEmailState()
80
+ toast.add({ title: t('account.emailChangeCancelled'), icon: 'i-lucide-check', color: 'success' })
81
+ }
82
+ catch (err: any) {
83
+ toast.add({ title: t('team.actionFailed'), description: cmsRequestError(err, t as any), color: 'error', icon: 'i-lucide-x' })
84
+ }
85
+ finally {
86
+ cancellingEmail.value = false
87
+ }
88
+ }
89
+
37
90
  const pw = reactive({ current: '', password: '' })
38
91
  const pwErrors = reactive<Record<string, string>>({})
39
92
  const pwForm = ref<HTMLElement | null>(null)
@@ -76,9 +129,6 @@ async function changePassword() {
76
129
  <UInput v-model="profile.name" autocomplete="name" :disabled="isDemo" class="w-full" />
77
130
  <template #error="{ error }"><span v-if="error" role="alert">{{ error }}</span></template>
78
131
  </UFormField>
79
- <UFormField :label="t('auth.email')" name="email">
80
- <UInput :model-value="user?.email" disabled icon="i-lucide-mail" class="w-full" />
81
- </UFormField>
82
132
  <UFormField :label="t('account.language')" name="locale">
83
133
  <USelect v-model="profile.locale" icon="i-lucide-languages" :items="locales.map((code: string) => ({ value: code, label: CMS_ADMIN_LOCALES[code] ?? code }))" class="w-full sm:w-60" />
84
134
  </UFormField>
@@ -88,6 +138,48 @@ async function changePassword() {
88
138
  </form>
89
139
  </section>
90
140
 
141
+ <section class="cms-section" aria-labelledby="account-email">
142
+ <header class="cms-section__head">
143
+ <span class="cms-section__tile"><UIcon name="i-lucide-mail" class="size-4" /></span>
144
+ <div class="min-w-0">
145
+ <h2 id="account-email" class="cms-section__title">{{ t('account.signInEmail') }}</h2>
146
+ <p class="text-sm text-muted text-pretty">{{ t('account.signInEmailDescription') }}</p>
147
+ </div>
148
+ </header>
149
+ <div class="cms-section__fields">
150
+ <UFormField :label="t('account.currentEmail')" name="currentEmail">
151
+ <UInput :model-value="user?.email ?? ''" disabled icon="i-lucide-mail" class="w-full" />
152
+ </UFormField>
153
+ <UAlert v-if="isDemo" color="neutral" variant="subtle" icon="i-lucide-info" :title="t('account.demoTitle')" :description="t('account.demoEmail')" />
154
+ <template v-else>
155
+ <!-- a change waiting for its link: what was sent where, what to do if it does not arrive -->
156
+ <UAlert
157
+ v-if="pendingEmail" color="info" variant="subtle" icon="i-lucide-mail-check" role="status"
158
+ :title="t('account.emailPendingTitle', { email: pendingEmail.email })"
159
+ >
160
+ <template #description>
161
+ <p class="text-pretty">{{ t('account.emailPendingBody') }}</p>
162
+ <p class="mt-2 text-pretty">{{ t('account.emailNotArrived') }}</p>
163
+ <UButton class="mt-3" color="neutral" variant="outline" size="sm" icon="i-lucide-x" :loading="cancellingEmail" @click="cancelEmailChange">{{ t('account.cancelEmailChange') }}</UButton>
164
+ </template>
165
+ </UAlert>
166
+ <form method="post" ref="emailForm" class="space-y-5" novalidate @submit.prevent="requestEmailChange">
167
+ <UFormField :label="t('account.newEmail')" name="email" :error="emailErrors.email || undefined" required>
168
+ <UInput v-model="emailChange.email" type="email" autocomplete="email" inputmode="email" class="w-full" />
169
+ <template #error="{ error }"><span v-if="error" role="alert">{{ error }}</span></template>
170
+ </UFormField>
171
+ <UFormField :label="t('account.passwordToConfirm')" name="password" :help="t('account.passwordToConfirmHint')" :error="emailErrors.password || undefined" required>
172
+ <CmsPasswordInput v-model="emailChange.password" autocomplete="current-password" />
173
+ <template #error="{ error }"><span v-if="error" role="alert">{{ error }}</span></template>
174
+ </UFormField>
175
+ <div>
176
+ <UButton type="submit" color="neutral" variant="outline" icon="i-lucide-send" :loading="savingEmail">{{ t('account.changeEmail') }}</UButton>
177
+ </div>
178
+ </form>
179
+ </template>
180
+ </div>
181
+ </section>
182
+
91
183
  <section class="cms-section" aria-labelledby="account-password">
92
184
  <header class="cms-section__head">
93
185
  <span class="cms-section__tile"><UIcon name="i-lucide-key-round" class="size-4" /></span>
@@ -0,0 +1,70 @@
1
+ <script setup lang="ts">
2
+ // The link from "confirm your new email": shows the new address and makes the change on
3
+ // a click (a POST — mail scanners open links, so opening the page changes nothing).
4
+ // Works signed in or not; a browser signed in to the same account stays signed in.
5
+ definePageMeta({ layout: 'cms-auth' })
6
+ const { t } = useCmsI18n()
7
+ const { productName } = useCmsAdminHead()
8
+ const route = useRoute()
9
+ const { loggedIn, fetch: refreshSession } = useUserSession()
10
+ useHead({ title: () => t('auth.emailConfirmTabTitle') })
11
+
12
+ const token = computed(() => String(route.params.token ?? ''))
13
+ const { data: info, error: loadError } = await useFetch<{ email: string }>((): string => `/api/cms/_auth/email/${token.value}`)
14
+
15
+ type Outcome = 'done' | 'expired' | 'taken'
16
+ const outcome = ref<Outcome | null>(loadError.value ? 'expired' : null)
17
+ const changedTo = ref('')
18
+ const stillSignedIn = ref(false)
19
+ const pending = ref(false)
20
+ const formError = ref('')
21
+
22
+ async function confirmChange() {
23
+ formError.value = ''
24
+ pending.value = true
25
+ try {
26
+ const res = await $fetch<{ email: string; signedIn: boolean }>('/api/cms/_auth/email/confirm', { method: 'POST', body: { token: token.value } })
27
+ changedTo.value = res.email
28
+ stillSignedIn.value = res.signedIn
29
+ // A browser signed in to this account now carries the new address in its session; one signed in as somebody else is left alone.
30
+ if (loggedIn.value) await refreshSession()
31
+ outcome.value = 'done'
32
+ }
33
+ catch (err: any) {
34
+ const status = err?.statusCode ?? err?.status
35
+ if (status === 410) outcome.value = 'expired'
36
+ else if (status === 409) outcome.value = 'taken'
37
+ else formError.value = cmsRequestError(err, t as any)
38
+ }
39
+ finally {
40
+ pending.value = false
41
+ }
42
+ }
43
+ </script>
44
+
45
+ <template>
46
+ <div v-if="outcome === 'done'" class="space-y-5">
47
+ <div class="text-center">
48
+ <h1 class="cms-display text-[1.625rem] leading-tight text-highlighted">{{ t('auth.emailConfirmedTitle') }}</h1>
49
+ <p class="mt-1 text-sm text-muted text-pretty">{{ t('auth.emailConfirmedBody', { email: changedTo }) }}</p>
50
+ </div>
51
+ <UButton v-if="stillSignedIn" to="/admin" block>{{ t('auth.emailConfirmedContinue') }}</UButton>
52
+ <UButton v-else to="/admin/login" block>{{ t('auth.emailConfirmedSignIn') }}</UButton>
53
+ </div>
54
+ <div v-else-if="outcome === 'taken'" class="space-y-3">
55
+ <h1 class="text-center cms-display text-[1.625rem] leading-tight text-highlighted">{{ t('auth.emailTakenTitle') }}</h1>
56
+ <p class="text-sm text-muted text-pretty">{{ t('auth.emailTakenBody', { email: info?.email ?? '' }) }}</p>
57
+ </div>
58
+ <div v-else-if="outcome === 'expired' || !info" class="space-y-3">
59
+ <h1 class="text-center cms-display text-[1.625rem] leading-tight text-highlighted">{{ t('auth.linkExpiredTitle') }}</h1>
60
+ <p class="text-sm text-muted text-pretty">{{ t('auth.emailLinkExpired') }}</p>
61
+ </div>
62
+ <form v-else method="post" class="space-y-5" novalidate @submit.prevent="confirmChange">
63
+ <div class="text-center">
64
+ <h1 class="cms-display text-[1.625rem] leading-tight text-highlighted">{{ t('auth.emailConfirmTitle') }}</h1>
65
+ <p class="mt-1 text-sm text-muted text-pretty">{{ t('auth.emailConfirmBody', { site: productName, email: info.email }) }}</p>
66
+ </div>
67
+ <UAlert v-if="formError" color="error" variant="subtle" icon="i-lucide-circle-alert" :title="formError" role="alert" data-cms-error-summary />
68
+ <UButton type="submit" block :loading="pending">{{ t('auth.emailConfirmAction') }}</UButton>
69
+ </form>
70
+ </template>
@@ -0,0 +1,70 @@
1
+ <script setup lang="ts">
2
+ // The link from "your sign-in email was changed", in the old mailbox: gives the account
3
+ // its old address back and sets a new password in one step (whoever made the change knew
4
+ // the old one). Opening the page changes nothing (mail scanners open links); the form
5
+ // does it, ends every other session and signs this browser in, as a password reset does.
6
+ definePageMeta({ layout: 'cms-auth' })
7
+ const { t } = useCmsI18n()
8
+ const { productName } = useCmsAdminHead()
9
+ const route = useRoute()
10
+ const signedIn = useCmsSignedIn()
11
+ useHead({ title: () => t('auth.emailRevertTabTitle') })
12
+
13
+ const token = computed(() => String(route.params.token ?? ''))
14
+ const { data: info, error: loadError } = await useFetch<{ email: string }>((): string => `/api/cms/_auth/email/revert/${token.value}`)
15
+
16
+ const outcome = ref<'expired' | 'taken' | null>(loadError.value ? 'expired' : null)
17
+ const password = ref('')
18
+ const error = ref('')
19
+ const formError = ref('')
20
+ const pending = ref(false)
21
+ const formEl = ref<HTMLElement | null>(null)
22
+
23
+ async function submit() {
24
+ error.value = ''
25
+ formError.value = ''
26
+ pending.value = true
27
+ try {
28
+ const res = await $fetch<{ user: any }>('/api/cms/_auth/email/revert', { method: 'POST', body: { token: token.value, password: password.value } })
29
+ await signedIn(res.user)
30
+ }
31
+ catch (err: any) {
32
+ const status = err?.statusCode ?? err?.status
33
+ if (status === 410) outcome.value = 'expired'
34
+ else if (status === 409) outcome.value = 'taken'
35
+ else {
36
+ // In the page's language, not the validator's English.
37
+ const issue = err?.data?.data?.[0]
38
+ if (issue?.code) error.value = cmsIssueMessage(issue, null, t as any)
39
+ else formError.value = cmsRequestError(err, t as any)
40
+ await cmsFocusInvalid(formEl.value)
41
+ }
42
+ }
43
+ finally {
44
+ pending.value = false
45
+ }
46
+ }
47
+ </script>
48
+
49
+ <template>
50
+ <div v-if="outcome === 'taken'" class="space-y-3">
51
+ <h1 class="text-center cms-display text-[1.625rem] leading-tight text-highlighted">{{ t('auth.emailTakenTitle') }}</h1>
52
+ <p class="text-sm text-muted text-pretty">{{ t('auth.emailRevertTakenBody', { email: info?.email ?? '' }) }}</p>
53
+ </div>
54
+ <div v-else-if="outcome === 'expired' || !info" class="space-y-3">
55
+ <h1 class="text-center cms-display text-[1.625rem] leading-tight text-highlighted">{{ t('auth.linkExpiredTitle') }}</h1>
56
+ <p class="text-sm text-muted text-pretty">{{ t('auth.emailRevertExpired') }}</p>
57
+ </div>
58
+ <form v-else method="post" ref="formEl" class="space-y-5" novalidate @submit.prevent="submit">
59
+ <div class="text-center">
60
+ <h1 class="cms-display text-[1.625rem] leading-tight text-highlighted">{{ t('auth.emailRevertTitle') }}</h1>
61
+ <p class="mt-1 text-sm text-muted text-pretty">{{ t('auth.emailRevertBody', { site: productName, email: info.email }) }}</p>
62
+ </div>
63
+ <UAlert v-if="formError" color="error" variant="subtle" icon="i-lucide-circle-alert" :title="formError" role="alert" data-cms-error-summary />
64
+ <UFormField :label="t('auth.newPassword')" name="password" :description="t('auth.passwordHint')" :error="error || undefined">
65
+ <CmsPasswordInput v-model="password" autocomplete="new-password" autofocus />
66
+ <template #error="{ error: message }"><span v-if="message" role="alert">{{ message }}</span></template>
67
+ </UFormField>
68
+ <UButton type="submit" block :loading="pending">{{ t('auth.emailRevertAction') }}</UButton>
69
+ </form>
70
+ </template>
@@ -435,7 +435,7 @@ async function copyUrl() {
435
435
  <p id="cms-focal-help" class="text-xs text-muted" aria-live="polite">
436
436
  {{ draft.focal ? t('media.focalSet', { x: draft.focal.x, y: draft.focal.y }) : t('media.focalHint') }}
437
437
  <span class="max-sm:hidden"> {{ t('media.focalKeys') }}</span>
438
- <UButton v-if="draft.focal" color="neutral" variant="link" size="xs" class="px-1" @click="draft.focal = null">{{ t('media.focalClear') }}</UButton>
438
+ <UButton v-if="draft.focal" color="neutral" variant="link" size="xs" class="px-1" @click="() => { draft.focal = null }">{{ t('media.focalClear') }}</UButton>
439
439
  </p>
440
440
  </div>
441
441
  <!-- a video or a sound: played right here -->
@@ -19,6 +19,8 @@ interface Found {
19
19
  submissions: { form: string; formLabel: any; id: string; createdAt: string; status: string | null; data: Record<string, unknown> }[]
20
20
  account: { id: string; email: string; name: string; role: string; status: string; lastLoginAt: string | null; createdAt: string } | null
21
21
  audit: { total: number; latest: { id: string; action: string; createdAt: string }[] }
22
+ /** Changes of sign-in address waiting for this one, or ways back to it. */
23
+ emailChanges: number
22
24
  }
23
25
 
24
26
  const email = ref('')
@@ -29,7 +31,7 @@ const busy = ref<'export' | 'delete' | null>(null)
29
31
  // Right after an erase the lookup is empty because we emptied it: say so, not "nothing was ever stored".
30
32
  const justErased = ref(false)
31
33
 
32
- const empty = computed(() => !!found.value && !found.value.submissions.length && !found.value.account && !found.value.audit.total)
34
+ const empty = computed(() => !!found.value && !found.value.submissions.length && !found.value.account && !found.value.audit.total && !found.value.emailChanges)
33
35
 
34
36
  async function search(keepErased = false) {
35
37
  if (!keepErased) justErased.value = false
@@ -72,10 +74,11 @@ async function erase() {
72
74
  if (!found.value) return
73
75
  const target = found.value.email
74
76
  // The question names what this lookup found, so "delete" says what goes.
75
- const { submissions, account, audit } = found.value
77
+ const { submissions, account, audit, emailChanges } = found.value
76
78
  const lines = [
77
79
  submissions.length ? t('privacy.eraseSubmissions', { count: submissions.length }) : '',
78
80
  account ? t('privacy.eraseAccount') : '',
81
+ emailChanges ? t('privacy.eraseEmailChanges') : '',
79
82
  audit.total ? t('privacy.eraseActivity', { count: audit.total }) : '',
80
83
  t('privacy.eraseUndone'),
81
84
  ].filter(Boolean)
@@ -177,6 +180,7 @@ const roleName = (r: string) => (['admin', 'editor', 'author'] as const).include
177
180
  <dt class="text-muted">{{ t('team.status') }}</dt><dd>{{ t(`team.status${found.account.status === 'active' ? 'Active' : found.account.status === 'invited' ? 'Invited' : 'Disabled'}`) }}</dd>
178
181
  <dt class="text-muted">{{ t('team.lastActive') }}</dt><dd>{{ found.account.lastLoginAt ? formatDate(found.account.lastLoginAt) : t('team.never') }}</dd>
179
182
  </dl>
183
+ <p v-if="found.emailChanges" class="px-4 pb-3 text-sm text-muted">{{ t('privacy.emailChanges') }}</p>
180
184
  </section>
181
185
 
182
186
  <section class="cms-card overflow-hidden" :aria-label="t('privacy.activity')">
@@ -67,7 +67,7 @@ const toc = ['brand', 'color', 'type', 'surfaces', 'moments', 'editors', 'action
67
67
  <UFieldGroup>
68
68
  <UButton
69
69
  v-for="a in accents" :key="a" color="neutral" :variant="accent === a ? 'solid' : 'outline'"
70
- size="sm" class="capitalize" @click="accent = a"
70
+ size="sm" class="capitalize" @click="() => { accent = a }"
71
71
  >{{ a }}</UButton>
72
72
  </UFieldGroup>
73
73
  </template>
@@ -82,6 +82,54 @@ async function resend(u: any) {
82
82
  }, t('team.resent'))
83
83
  }
84
84
 
85
+ // ── change someone's email (not your own: that is on your account page, with a confirmation link) ──
86
+ const emailTarget = ref<{ id: string; name: string; email: string; status: string } | null>(null)
87
+ const newEmail = ref('')
88
+ // Your own password: a session left open must not be enough to move someone's account (the server checks it).
89
+ const myPassword = ref('')
90
+ const emailError = ref('')
91
+ const passwordError = ref('')
92
+ const emailFailed = ref('')
93
+ const savingEmail = ref(false)
94
+ const emailFormEl = ref<HTMLElement | null>(null)
95
+ function openEmail(u: any) {
96
+ emailTarget.value = { id: u.id, name: u.name || u.email, email: u.email, status: u.status }
97
+ newEmail.value = u.email
98
+ myPassword.value = ''
99
+ emailError.value = ''
100
+ passwordError.value = ''
101
+ emailFailed.value = ''
102
+ }
103
+ async function saveEmail() {
104
+ const target = emailTarget.value
105
+ if (!target) return
106
+ emailError.value = ''
107
+ passwordError.value = ''
108
+ emailFailed.value = ''
109
+ savingEmail.value = true
110
+ try {
111
+ const res = await cmsFetch<{ user: { email: string; role: string }; inviteUrl?: string; emailed?: boolean }>(`/api/cms/_users/${target.id}`, { method: 'PATCH', body: { email: newEmail.value, password: myPassword.value } })
112
+ emailTarget.value = null
113
+ myPassword.value = ''
114
+ toast.add({ title: t('team.emailChanged'), description: res.user.email, icon: 'i-lucide-check', color: 'success' })
115
+ // An invitation that went to the new address: show its link, as after "Send a new invitation".
116
+ if (res.inviteUrl) resent.value = { email: res.user.email, role: res.user.role, url: res.inviteUrl, emailed: !!res.emailed }
117
+ refresh()
118
+ }
119
+ catch (err: any) {
120
+ const issues = Array.isArray(err?.data?.data) ? err.data.data as any[] : []
121
+ const emailIssue = issues.find((i: any) => i?.path?.[0] === 'email')
122
+ const passwordIssue = issues.find((i: any) => i?.path?.[0] === 'password')
123
+ if (emailIssue) emailError.value = cmsIssueMessage(emailIssue, null, t as any)
124
+ if (passwordIssue) passwordError.value = t(passwordIssue.message === 'Required' ? 'validation.required' : 'validation.wrongPassword')
125
+ if (!emailIssue && !passwordIssue) emailFailed.value = cmsRequestError(err, t as any)
126
+ await cmsFocusInvalid(emailFormEl.value)
127
+ }
128
+ finally {
129
+ savingEmail.value = false
130
+ }
131
+ }
132
+
85
133
  // Someone who never accepted the invitation has only an invitation to take back.
86
134
  const confirm = useCmsConfirm()
87
135
  async function remove(u: any) {
@@ -116,6 +164,7 @@ function rowMenu(u: any): DropdownMenuItem[][] {
116
164
  onSelect: () => { if (u.role !== r) act(() => patch(u.id, { role: r }), t('team.roleChanged')) },
117
165
  })),
118
166
  }]]
167
+ groups[0]!.push({ label: t('team.changeEmail'), icon: 'i-lucide-mail', onSelect: () => openEmail(u) })
119
168
  if (u.status === 'invited') groups[0]!.push({ label: t('team.resend'), icon: 'i-lucide-send', onSelect: () => resend(u) })
120
169
  if (u.status === 'active') groups[0]!.push({ label: t('team.disable'), icon: 'i-lucide-ban', onSelect: () => disable(u) })
121
170
  if (u.status === 'disabled') groups[0]!.push({ label: t('team.enable'), icon: 'i-lucide-rotate-ccw', onSelect: () => act(() => patch(u.id, { status: 'active' }), t('team.enabled')) })
@@ -229,16 +278,40 @@ const initials = (u: any) => (u.name || u.email).split(/[\s@.]+/).filter(Boolean
229
278
  <div class="flex justify-end gap-2 w-full">
230
279
  <template v-if="created">
231
280
  <UButton color="neutral" variant="ghost" icon="i-lucide-user-plus" @click="openInvite">{{ t('team.inviteAnother') }}</UButton>
232
- <UButton @click="inviteOpen = false">{{ t('common.close') }}</UButton>
281
+ <UButton @click="() => { inviteOpen = false }">{{ t('common.close') }}</UButton>
233
282
  </template>
234
283
  <template v-else>
235
- <UButton color="neutral" variant="ghost" @click="inviteOpen = false">{{ t('common.cancel') }}</UButton>
284
+ <UButton color="neutral" variant="ghost" @click="() => { inviteOpen = false }">{{ t('common.cancel') }}</UButton>
236
285
  <UButton type="submit" form="cms-invite" icon="i-lucide-send" :loading="inviting">{{ t('team.sendInvite') }}</UButton>
237
286
  </template>
238
287
  </div>
239
288
  </template>
240
289
  </UModal>
241
290
 
291
+ <!-- Change someone's email -->
292
+ <UModal :open="!!emailTarget" :title="emailTarget ? t('team.changeEmailTitle', { name: emailTarget.name }) : ''" @update:open="(v: boolean) => { if (!v) emailTarget = null }">
293
+ <template #body>
294
+ <form v-if="emailTarget" id="cms-change-email" ref="emailFormEl" class="space-y-5" novalidate @submit.prevent="saveEmail">
295
+ <p class="text-sm text-muted text-pretty">{{ t(emailTarget.status === 'invited' ? 'team.changeEmailInvitedBody' : emailTarget.status === 'disabled' ? 'team.changeEmailDisabledBody' : 'team.changeEmailBody') }}</p>
296
+ <UFormField :label="t('team.newEmail')" name="email" :error="emailError || undefined" required>
297
+ <UInput v-model="newEmail" type="email" autocomplete="off" inputmode="email" autofocus class="w-full" />
298
+ <template #error="{ error }"><span v-if="error" role="alert">{{ error }}</span></template>
299
+ </UFormField>
300
+ <UFormField :label="t('team.yourPassword')" name="password" :help="t('team.yourPasswordHint')" :error="passwordError || undefined" required>
301
+ <CmsPasswordInput v-model="myPassword" autocomplete="current-password" />
302
+ <template #error="{ error }"><span v-if="error" role="alert">{{ error }}</span></template>
303
+ </UFormField>
304
+ <UAlert v-if="emailFailed" color="error" variant="subtle" icon="i-lucide-circle-alert" :title="emailFailed" role="alert" data-cms-error-summary />
305
+ </form>
306
+ </template>
307
+ <template #footer>
308
+ <div class="flex justify-end gap-2 w-full">
309
+ <UButton color="neutral" variant="ghost" @click="() => { emailTarget = null }">{{ t('common.cancel') }}</UButton>
310
+ <UButton type="submit" form="cms-change-email" icon="i-lucide-mail" :loading="savingEmail">{{ t('team.changeEmail') }}</UButton>
311
+ </div>
312
+ </template>
313
+ </UModal>
314
+
242
315
  <!-- A resent invitation: show the new link too -->
243
316
  <UModal :open="!!resent" :title="resent ? t(resent.emailed ? 'team.inviteSent' : 'team.inviteCreated', { email: resent.email }) : ''" @update:open="(v: boolean) => { if (!v) resent = null }">
244
317
  <template #body>
@@ -40,6 +40,8 @@ export function cmsIssueMessage(issue: any, field: any, t: T): string {
40
40
  // A page tree: the whole address is taken, not just the part.
41
41
  if (issue.address) return t('validation.addressTaken', { address: issue.address, title: issue.otherTitle ?? '' })
42
42
  return t('validation.unique')
43
+ case 'same_email':
44
+ return t('account.sameEmail')
43
45
  case 'tree_cycle':
44
46
  return t('validation.treeCycle', { loop: Array.isArray(issue.loop) ? issue.loop.join(' → ') : '' })
45
47
  case 'tree_depth':
package/cli/generate.ts CHANGED
@@ -31,7 +31,8 @@ export interface GenerateOptions {
31
31
  error?: (line: string) => void
32
32
  }
33
33
 
34
- const journalTags = (dir: string): string[] => {
34
+ /** The migrations a folder's drizzle journal lists, by tag (file name without `.sql`). */
35
+ export const journalTags = (dir: string): string[] => {
35
36
  const file = join(dir, 'meta/_journal.json')
36
37
  return existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')).entries as { tag: string }[]).map((e) => e.tag) : []
37
38
  }
package/cli/index.ts CHANGED
@@ -120,7 +120,7 @@ switch (cmd) {
120
120
  case 'generate': process.exit(await generate()); break
121
121
  case 'up': process.exit(await up(cwd)); break
122
122
  case 'status': process.exit(await status(cwd)); break
123
- case 'upgrade': process.exit(await upgrade(cwd, resolve(dirname(fileURLToPath(import.meta.url)), '..'), { generate })); break
123
+ case 'upgrade': process.exit(await upgrade(cwd, resolve(dirname(fileURLToPath(import.meta.url)), '..'), { generate, migrationsDir: resolve(cwd, 'server/db/migrations') })); break
124
124
  case 'client': await client(); break
125
125
  case 'openapi': await openapi(); break
126
126
  case 'content:migrate': await (await import('./content-migrate')).contentMigrateCommand(await loadConfig(), process.argv.slice(3)); break
package/cli/upgrade.ts CHANGED
@@ -7,12 +7,15 @@ import { docsUrl } from '../src/docs'
7
7
  import { execFileSync } from 'node:child_process'
8
8
  import { existsSync, readFileSync } from 'node:fs'
9
9
  import { join } from 'node:path'
10
+ import { journalTags } from './generate'
10
11
  import { checkVersions } from './versions'
11
12
  import { status } from './status'
12
13
 
13
14
  export interface UpgradeDeps {
14
15
  /** Emit schema.ts and generate the migration (with the guard). Returns an exit code. */
15
16
  generate: () => Promise<number>
17
+ /** The site's migrations folder (default `server/db/migrations`), to tell whether `generate` wrote one. */
18
+ migrationsDir?: string
16
19
  }
17
20
 
18
21
  /** Returns the process exit code. */
@@ -22,12 +25,14 @@ export async function upgrade(cwd: string, pkgDir: string, deps: UpgradeDeps): P
22
25
 
23
26
  console.log('1. Versions')
24
27
  const problems = checkVersions(cwd, own)
25
- if (!problems.length) console.log(' ✓ nuxt, @nuxt/ui, drizzle-orm and zod fit this tinyzoo')
28
+ if (!problems.length) console.log(' ✓ nuxt, @nuxt/ui, nuxt-auth-utils, drizzle-orm and zod fit this tinyzoo')
26
29
  for (const p of problems) {
27
30
  console.warn(` ⚠ ${p.name}: ${p.installed ? `${p.installed} is installed` : 'not installed'}, tinyzoo ${own.version} wants ${p.wanted} — update it (\`pnpm up ${p.name}\`) before deploying`)
28
31
  }
29
32
 
30
33
  console.log('\n2. Schema and migration')
34
+ const migrationsDir = deps.migrationsDir ?? join(cwd, 'server/db/migrations')
35
+ const before = new Set(journalTags(migrationsDir))
31
36
  const code = await deps.generate()
32
37
  if (code !== 0) {
33
38
  console.error('\n✗ Stopped: fix the above and run `tinyzoo upgrade` again.')
@@ -51,10 +56,23 @@ export async function upgrade(cwd: string, pkgDir: string, deps: UpgradeDeps): P
51
56
  const statusCode = await status(cwd)
52
57
  if (statusCode === 2) console.log(' (Could not check the database from here. Run `tinyzoo status` where DATABASE_URL points at it.)')
53
58
 
54
- console.log(`\nNext:
55
- 1. Read the new migration in server/db/migrations — that is the change your database will get.
56
- 2. pnpm typecheck, then commit the migration, schema.ts and the typed client together with the package update.
57
- 3. Deploy. The app migrates itself at start (NUXT_CMS_MIGRATIONS_ON_START=true), or run \`tinyzoo up\` yourself.
58
- Details: ${docsUrl('upgrading')}`)
59
+ const added = journalTags(migrationsDir).filter((t) => !before.has(t))
60
+ console.log(`\n${nextSteps(added)}\n Details: ${docsUrl('upgrading')}`)
59
61
  return 0
60
62
  }
63
+
64
+ /** What to do after `tinyzoo upgrade`: with a new migration, read and commit it; without one, there is none to read. */
65
+ export function nextSteps(added: string[]): string {
66
+ const deploy = '3. Deploy. The app migrates itself at start (NUXT_CMS_MIGRATIONS_ON_START=true), or run `tinyzoo up` yourself.'
67
+ if (!added.length) {
68
+ return `Next:
69
+ 1. No new migration: this update changes nothing in your database schema (step 4 shows whether earlier migrations are still waiting).
70
+ 2. pnpm typecheck, then commit schema.ts and the typed client (if they changed) together with the package update.
71
+ ${deploy}`
72
+ }
73
+ const files = added.map((t) => `server/db/migrations/${t}.sql`).join(', ')
74
+ return `Next:
75
+ 1. Read the new migration (${files}): that is the change your database will get.
76
+ 2. pnpm typecheck, then commit the migration, schema.ts and the typed client together with the package update.
77
+ ${deploy}`
78
+ }
package/cli/versions.ts CHANGED
@@ -1,8 +1,8 @@
1
- /** Version checks for `tinyzoo upgrade`: does the site's own nuxt, @nuxt/ui, drizzle-orm and zod fit? */
1
+ /** Version checks for `tinyzoo upgrade`: does the site's own nuxt, @nuxt/ui, nuxt-auth-utils, drizzle-orm and zod fit? */
2
2
  import { existsSync, readFileSync } from 'node:fs'
3
3
  import { dirname, join, parse } from 'node:path'
4
4
 
5
- export const CHECKED_PACKAGES = ['nuxt', '@nuxt/ui', 'drizzle-orm', 'zod'] as const
5
+ export const CHECKED_PACKAGES = ['nuxt', '@nuxt/ui', 'nuxt-auth-utils', 'drizzle-orm', 'zod'] as const
6
6
 
7
7
  const parseVersion = (v: string): [number, number, number] | null => {
8
8
  const m = /^[v=\s]*(\d+)(?:\.(\d+|x|\*))?(?:\.(\d+|x|\*))?/.exec(v)
package/forms/index.ts CHANGED
@@ -198,6 +198,3 @@ export function formsPlugin(): CmsPlugin {
198
198
  },
199
199
  })
200
200
  }
201
-
202
- /** The registration the deprecated `defineForm` / `defineFormSettings` of `tinyzoo` leave to the plugin. */
203
- export const IMPLICIT_FORMS_REQUIREMENT: CmsPluginRequirement = { ...FORMS_REQUIREMENT, create: formsPlugin }
package/module.ts CHANGED
@@ -3,6 +3,7 @@ import { dirname, resolve } from 'node:path'
3
3
  import { fileURLToPath } from 'node:url'
4
4
  import { addComponentsDir, addServerHandler, addServerPlugin, addTypeTemplate, defineNuxtModule, extendPages } from '@nuxt/kit'
5
5
  import { createJiti } from 'jiti'
6
+ import { appSecretFallbackCode, NITRO_CONFIG_MODULE, planAppSecretFallback, prependedLinesMap } from './src/appSecret'
6
7
  import { collectPlugins, planPlugins, type CmsPlugin } from './src/plugin'
7
8
 
8
9
  const layerDir = dirname(fileURLToPath(import.meta.url))
@@ -201,6 +202,22 @@ function sitemapPaths(paths: (string | Record<string, string>)[] | undefined): (
201
202
  return paths ?? []
202
203
  }
203
204
 
205
+ /**
206
+ * NUXT_SESSION_PASSWORD (or a nuxt.config `runtimeConfig.session.password`) standing in for
207
+ * NUXT_APP_SECRET until 0.5: the lines of src/appSecret.ts put at the top of Nitro's runtime
208
+ * config module, before Nitro reads the environment.
209
+ */
210
+ function appSecretFallback(code: string, onInstalled: () => void) {
211
+ return {
212
+ name: 'tinyzoo:app-secret-fallback',
213
+ transform(source: string, id: string) {
214
+ if (!NITRO_CONFIG_MODULE.test(id.split('?')[0]!)) return null
215
+ onInstalled()
216
+ return { code: code + source, map: prependedLinesMap(code, source, id) }
217
+ },
218
+ }
219
+ }
220
+
204
221
  export default defineNuxtModule<CmsModuleOptions>({
205
222
  meta: { name: 'tinyzoo', configKey: 'cms' },
206
223
  defaults: { config: 'cms.config.ts' },
@@ -214,15 +231,22 @@ export default defineNuxtModule<CmsModuleOptions>({
214
231
  nuxt.options.alias['#cms/config'] = configPath
215
232
  // Bundle the host's migrations as server assets so they ship with .output.
216
233
  const migrationsDir = resolve(nuxt.options.rootDir, options.migrations?.dir || 'server/db/migrations')
234
+ // NUXT_SESSION_PASSWORD as the app secret while a site has not set NUXT_APP_SECRET yet
235
+ // (src/appSecret.ts).
236
+ nuxt.hook('nitro:init', (nitro) => {
237
+ const plan = planAppSecretFallback(nitro.options.runtimeConfig as any)
238
+ if (!plan.install) return
239
+ let installed = false
240
+ nitro.hooks.hook('rollup:before', (_nitro, rollupConfig) => {
241
+ const plugins = (rollupConfig.plugins ||= []) as any[]
242
+ plugins.push(appSecretFallback(appSecretFallbackCode(plan.envPrefix, plan.fromConfig), () => { installed = true }))
243
+ })
244
+ // After the server is built, whichever bundler built it: was the module found?
245
+ nitro.hooks.hook('compiled', () => {
246
+ if (!installed) console.warn('[tinyzoo] Nitro\'s runtime config module was not found in the server bundle, so NUXT_SESSION_PASSWORD will not stand in for NUXT_APP_SECRET: set NUXT_APP_SECRET.')
247
+ })
248
+ })
217
249
  nuxt.hook('nitro:config', (nitro) => {
218
- // nuxt-auth-utils adds a Nitro plugin when WebSockets are on (the admin's live socket
219
- // is one) that reads the session on EVERY request: for a visitor without one that
220
- // *creates* it and sets a cookie on every response, public pages, content API and
221
- // media included, so no CDN caches them. The admin socket checks the session itself
222
- // (admitAdminSocket) and only when the request carries one, so that plugin goes.
223
- if (Array.isArray(nitro.plugins)) {
224
- nitro.plugins = nitro.plugins.filter((p) => !/nuxt-auth-utils[\\/]dist[\\/]runtime[\\/]server[\\/]plugins[\\/]ws(\.|$)/.test(String(p)))
225
- }
226
250
  if (existsSync(migrationsDir)) {
227
251
  nitro.serverAssets = nitro.serverAssets || []
228
252
  nitro.serverAssets.push({ baseName: 'cms-migrations', dir: migrationsDir })
@@ -253,7 +277,7 @@ export default defineNuxtModule<CmsModuleOptions>({
253
277
  locale: string | null
254
278
  }
255
279
  interface UserSession {
256
- cms?: { uid: string; sv: number }
280
+ cms?: { uid: string; sv: number; iat: number }
257
281
  }
258
282
  }
259
283
  declare module 'nitropack/types' {
package/nuxt.config.ts CHANGED
@@ -19,9 +19,10 @@ export default defineNuxtConfig({
19
19
  // Admin design tokens, scoped to html[data-cms-admin] so the host site's own
20
20
  // theme is untouched (see app/assets/css/cms-admin.css).
21
21
  css: [join(layerDir, 'app/assets/css/cms-admin.css')],
22
- // Admin sessions end after 14 days at the latest (sign in again). Without a maxAge
23
- // a copied session cookie would stay valid until the account changes. Hosts can
24
- // override with runtimeConfig.session.maxAge / NUXT_SESSION_MAX_AGE.
22
+ // Admin sessions end 14 days after signing in: sign in again. Changing one's name, language,
23
+ // email or password writes the session again but keeps the time of the sign-in (cms.iat,
24
+ // checked in activeAccountOf), so a copied session cookie cannot be kept alive past it.
25
+ // Hosts can override with runtimeConfig.session.maxAge / NUXT_SESSION_MAX_AGE (seconds).
25
26
  runtimeConfig: {
26
27
  session: { maxAge: 60 * 60 * 24 * 14 },
27
28
  },