tinyzoo 0.2.1 → 0.3.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 (54) 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/package.json +9 -10
  31. package/server/api/cms/_auth/email/[token].get.ts +16 -0
  32. package/server/api/cms/_auth/email/confirm.post.ts +73 -0
  33. package/server/api/cms/_auth/email/index.delete.ts +11 -0
  34. package/server/api/cms/_auth/email/index.get.ts +10 -0
  35. package/server/api/cms/_auth/email/index.post.ts +86 -0
  36. package/server/api/cms/_auth/email/revert/[token].get.ts +15 -0
  37. package/server/api/cms/_auth/email/revert.post.ts +68 -0
  38. package/server/api/cms/_collab/socket.ts +68 -20
  39. package/server/api/cms/_privacy/export.post.ts +5 -1
  40. package/server/api/cms/_privacy/lookup.post.ts +5 -2
  41. package/server/api/cms/_users/[id].delete.ts +3 -0
  42. package/server/api/cms/_users/[id].patch.ts +114 -13
  43. package/server/api/cms/_users/index.post.ts +2 -1
  44. package/server/store/redis.ts +9 -1
  45. package/server/utils/cmsAudit.ts +10 -2
  46. package/server/utils/cmsAuth.ts +15 -4
  47. package/server/utils/cmsCollabServer.ts +22 -9
  48. package/server/utils/cmsEmailChange.ts +193 -0
  49. package/server/utils/cmsEmailChangeRules.ts +108 -0
  50. package/server/utils/cmsEmails.ts +155 -9
  51. package/server/utils/cmsPrivacy.ts +60 -11
  52. package/server/utils/cmsRetention.ts +4 -0
  53. package/src/system.ts +1 -1
  54. package/starter/package.json +2 -2
@@ -1,4 +1,4 @@
1
- import { and, eq, or, propOf, sql } from 'tinyzoo'
1
+ import { and, eq, inArray, or, propOf, sql } from 'tinyzoo'
2
2
  import type { CmsEntity, CmsRegistry } from 'tinyzoo'
3
3
  import { z } from 'zod'
4
4
  import { formEntities, purgeSubmissions } from '../../forms/retention'
@@ -13,8 +13,11 @@ import { formEntities, purgeSubmissions } from '../../forms/retention'
13
13
  * fields equal the address (case-insensitive, whitespace trimmed) — and their saved
14
14
  * versions and search rows, which hold the same text;
15
15
  * - the account: email, name, role, status, language, sign-in times;
16
- * - audit entries: those the account made, those about it (invitation, role change)
17
- * and failed sign-ins that tried the address.
16
+ * - audit entries: those the account made, those about it (invitation, role change,
17
+ * a change of its address) and failed sign-ins that tried the address. A change of
18
+ * address names the new one as `email` and the old one as `previousEmail`; either finds it;
19
+ * - a change of sign-in address waiting for confirmation, or the way back from one
20
+ * (cms_state `email-change:*` / `email-revert:*`), that names the address.
18
21
  * Not covered: what an editor wrote under their own name in entries or media (that is
19
22
  * the site's content, not personal data about a visitor), and copies in backups.
20
23
  */
@@ -58,7 +61,7 @@ export async function findSubmissions(db: any, reg: CmsRegistry, email: string):
58
61
  /** The condition that picks the audit entries touching a person: theirs, about them, or naming their address. */
59
62
  export function auditCondition(reg: CmsRegistry, email: string, accountId: string | null) {
60
63
  const a = reg.cmsAudit
61
- const parts = [sql`lower(${a.meta}->>'email') = ${email}`]
64
+ const parts = [sql`lower(${a.meta}->>'email') = ${email}`, sql`lower(${a.meta}->>'previousEmail') = ${email}`]
62
65
  if (accountId) parts.push(eq(a.userId, accountId), and(eq(a.recordId, accountId), sql`${a.action} like 'user.%'`)!)
63
66
  return or(...parts)!
64
67
  }
@@ -77,6 +80,31 @@ export function submissionView(e: CmsEntity, row: Record<string, any>) {
77
80
  return { form: e.name, id: row.id as string, createdAt: row.createdAt as Date, status: (row.status as string | null) ?? null, data }
78
81
  }
79
82
 
83
+ /** The audit actions of a change of sign-in address: they name two addresses, `email` (new) and `previousEmail` (old). */
84
+ const ADDRESS_CHANGES = new Set(['account.email_request', 'account.email', 'account.email_cancel', 'account.email_revert', 'user.email'])
85
+
86
+ /**
87
+ * An audit entry as exported to the person with `email`: a change of sign-in address
88
+ * names two addresses, and the other one is not always theirs. It is when the entry is
89
+ * about their own account (they made the change, or it was made to their account) —
90
+ * except the address of another account they asked for (`inUse`). Found only through
91
+ * the address (it is the old address of somebody else's account now, or that other
92
+ * account's own), the other address is left out.
93
+ */
94
+ export function auditExportMeta(entry: { action: string; userId: string | null; recordId: string | null; meta: unknown }, email: string, accountId: string | null): unknown {
95
+ const meta = entry.meta as Record<string, unknown> | null
96
+ if (!meta || typeof meta !== 'object' || Array.isArray(meta) || !ADDRESS_CHANGES.has(entry.action)) return entry.meta
97
+ const own = !!accountId && (entry.action.startsWith('user.') ? entry.recordId === accountId : entry.userId === accountId)
98
+ const out: Record<string, unknown> = { ...meta }
99
+ for (const key of ['email', 'previousEmail'] as const) {
100
+ const value = typeof out[key] === 'string' ? (out[key] as string).trim().toLowerCase() : null
101
+ if (value === null || value === email) continue
102
+ const theirs = own && !(key === 'email' && out.inUse === true)
103
+ if (!theirs) out[key] = '(another person’s address)'
104
+ }
105
+ return out
106
+ }
107
+
80
108
  /** The account without secrets (no password hash, no session counter). */
81
109
  export function accountView(u: any) {
82
110
  return { id: u.id as string, email: u.email as string, name: u.name as string, role: u.role as string, status: u.status as string, language: (u.locale as string | null) ?? null, lastLoginAt: u.lastLoginAt as Date | null, createdAt: u.createdAt as Date }
@@ -125,16 +153,26 @@ export async function erasePerson(db: any, reg: CmsRegistry, email: string, acto
125
153
  sessionVersion: sql`${u.sessionVersion} + 1`, updatedAt: new Date(),
126
154
  }).where(eq(u.id, account.id))
127
155
  await tx.delete(reg.cmsTokens).where(eq(reg.cmsTokens.userId, account.id))
156
+ await tx.delete(reg.cmsState).where(eq(reg.cmsState.key, emailChangeStateKey(account.id)))
157
+ await tx.delete(reg.cmsState).where(sql`${reg.cmsState.key} like ${emailRevertStatePattern(account.id)}`)
128
158
  }
159
+ // A change waiting for this address, or a way back to it, of whichever account: the link goes with it.
160
+ const states = await findEmailStates(tx, reg, email)
161
+ if (states.length) await tx.delete(reg.cmsState).where(inArray(reg.cmsState.key, states.map((r) => r.key)))
129
162
  return { submissions, account: !!account, auditEntries }
130
163
  })
131
164
  }
132
165
 
133
166
  /**
134
167
  * Take the erased person's own details out of the audit log, and nobody else's:
135
- * - entries that name their address (`meta.email`, any case, whitespace trimmed: a failed
136
- * sign-in with it, their invitation, their deletion) and entries about their account
137
- * (`user.*` on their id) lose email, IP address and name;
168
+ * - entries that name their address (`meta.email` or `meta.previousEmail`, any case,
169
+ * whitespace trimmed: a failed sign-in with it, their invitation, their deletion, a
170
+ * change of their address) lose that address — only that one: a change of address
171
+ * names another, which may be somebody else's now (the account that moved away from
172
+ * the address this person has today) — and sign-in attempts their IP address too;
173
+ * - entries about their account (`user.*` on their id) lose addresses, IP address and name;
174
+ * - their own changes of address (`account.email*`) lose both addresses (but not the
175
+ * address of another account they asked for, `inUse`);
138
176
  * - entries they made themselves lose their IP address and their name — but not an
139
177
  * `email` that is someone else's: the `user.invite` entries of an administrator hold
140
178
  * the invitees' addresses, which belong to the invitees.
@@ -148,12 +186,23 @@ async function scrubAudit(tx: any, reg: CmsRegistry, email: string, account: { i
148
186
  const res: any = await tx.execute(sql`update ${a} set meta = nullif(${set}, '{}'::jsonb) where ${isObject} and (${where}) returning ${a.id}`)
149
187
  for (const row of res?.rows ?? []) touched.add(String(row.id))
150
188
  }
151
- const strip = sql`${a.meta} - 'email' - 'ip' - 'name'`
189
+ const strip = sql`${a.meta} - 'email' - 'previousEmail' - 'ip' - 'name'`
190
+ const names = (key: string) => sql`lower(btrim(${a.meta}->>${key})) = ${email}`
152
191
  // Naming the address: a sign-in attempt (its IP address went with the attempt) or an entry by somebody
153
- // else about this person (the actor's own details are not ours to take).
154
- await run(sql`case when ${a.action} like 'auth.%' then ${strip} else ${a.meta} - 'email' end`, sql`lower(btrim(${a.meta}->>'email')) = ${email}`)
192
+ // else about this person (the actor's own details are not ours to take). Only the keys that hold this
193
+ // address go: the other address of a change belongs to whoever has it (their own changes: below).
194
+ const matching = sql`${a.meta} - (case when ${names('email')} then 'email' else '' end) - (case when ${names('previousEmail')} then 'previousEmail' else '' end)`
195
+ await run(
196
+ sql`case when ${a.action} like 'auth.%' then ${strip} else ${matching} end`,
197
+ sql`(${names('email')} or ${names('previousEmail')})`,
198
+ )
155
199
  if (account) {
156
- await run(strip, sql`${a.recordId} = ${account.id} and ${a.action} like 'user.%' and ${a.meta} ?| array['email', 'ip', 'name']`)
200
+ await run(strip, sql`${a.recordId} = ${account.id} and ${a.action} like 'user.%' and ${a.meta} ?| array['email', 'previousEmail', 'ip', 'name']`)
201
+ // Their own changes of address: both addresses are theirs (but not another account's address they asked for).
202
+ await run(
203
+ sql`case when ${a.meta} ? 'inUse' then ${a.meta} - 'previousEmail' else ${a.meta} - 'email' - 'previousEmail' end`,
204
+ sql`${a.userId} = ${account.id} and ${a.action} like 'account.email%' and ${a.meta} ?| array['email', 'previousEmail']`,
205
+ )
157
206
  // Their own entries: their client address, and their name if it is the one on the entry.
158
207
  const name = (account.name ?? '').trim().toLowerCase()
159
208
  await run(
@@ -7,6 +7,8 @@ import { inArray, lt, sql } from 'tinyzoo'
7
7
  * past their form's `retentionDays`; none = kept).
8
8
  * - The audit log: `cms.retention.auditDays` (default 365; 0 = kept) — it holds who
9
9
  * did what and, for failed sign-ins, the email and address tried.
10
+ * - Changes of sign-in address: one nobody confirmed, or a way back nobody took, is
11
+ * deleted once its link has expired (cms_state `email-change:*`, `email-revert:*`).
10
12
  *
11
13
  * A daily task (`cms:retention`) deletes what is past its time, in batches, one
12
14
  * instance at a time (an advisory lock), and writes one audit entry with the counts
@@ -47,6 +49,8 @@ export async function runRetention(): Promise<RetentionResult | null> {
47
49
  if (old.length < BATCH * 2) break
48
50
  }
49
51
  }
52
+ // Changes of sign-in address nobody confirmed, and ways back nobody took, once expired.
53
+ await sweepEmailStates(tx, reg)
50
54
  return true
51
55
  })
52
56
  if (!ran) return null
package/src/system.ts CHANGED
@@ -38,7 +38,7 @@ export const cmsUsers = pgTable('cms_users', {
38
38
  export const cmsTokens = pgTable('cms_tokens', {
39
39
  id: uuid('id').primaryKey().defaultRandom(),
40
40
  userId: uuid('user_id').notNull().references(() => cmsUsers.id, { onDelete: 'cascade' }),
41
- // invite | reset
41
+ // invite | reset | email (a change of address; the address waits in cms_state)
42
42
  kind: text('kind').notNull(),
43
43
  // SHA-256 of the secret sent in the link; the secret itself is never stored.
44
44
  tokenHash: text('token_hash').notNull(),
@@ -17,7 +17,7 @@
17
17
  "@internationalized/date": "^3.12.2",
18
18
  "@nuxt/ui": "^4.0.0",
19
19
  "@tinyzoo/client": "workspace:*",
20
- "drizzle-orm": "^0.44.0",
20
+ "drizzle-orm": "^0.45.4",
21
21
  "nuxt": "^4.0.0",
22
22
  "nuxt-auth-utils": "^0.5.29",
23
23
  "pg": "^8.16.3",
@@ -27,7 +27,7 @@
27
27
  },
28
28
  "devDependencies": {
29
29
  "@iconify-json/lucide": "^1.2.114",
30
- "drizzle-kit": "^0.31.0",
30
+ "drizzle-kit": "^0.31.11",
31
31
  "tsx": "^4.19.0",
32
32
  "typescript": "^5.7.0",
33
33
  "vue-tsc": "^3.3.14"