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.
- package/app/components/CmsDayPicker.vue +5 -1
- package/app/components/CmsFieldColor.vue +3 -3
- package/app/components/CmsFieldDate.vue +5 -3
- package/app/components/CmsFieldGallery.vue +1 -1
- package/app/components/CmsFieldRelationOne.vue +1 -1
- package/app/components/CmsFieldText.vue +1 -1
- package/app/components/CmsListFilters.vue +1 -1
- package/app/components/CmsMoment.vue +1 -1
- package/app/components/CmsPasswordInput.vue +1 -1
- package/app/components/CmsPreviewPanel.vue +4 -4
- package/app/components/CmsPublishReview.vue +1 -1
- package/app/components/CmsRevisions.vue +1 -1
- package/app/components/CmsRichTextEditor.vue +3 -3
- package/app/components/CmsSingletonForm.vue +1 -1
- package/app/components/CmsTreeList.vue +3 -3
- package/app/i18n/cs.ts +43 -0
- package/app/i18n/de.ts +43 -0
- package/app/i18n/en.ts +43 -0
- package/app/middleware/cms-auth.global.ts +1 -1
- package/app/pages/admin/[entity]/[id].vue +9 -9
- package/app/pages/admin/[entity]/index.vue +7 -7
- package/app/pages/admin/account.vue +96 -4
- package/app/pages/admin/email/[token].vue +70 -0
- package/app/pages/admin/email/revert/[token].vue +70 -0
- package/app/pages/admin/media.vue +1 -1
- package/app/pages/admin/privacy.vue +6 -2
- package/app/pages/admin/styleguide.vue +1 -1
- package/app/pages/admin/team.vue +75 -2
- package/app/utils/cmsIssues.ts +2 -0
- package/cli/generate.ts +2 -1
- package/cli/index.ts +1 -1
- package/cli/upgrade.ts +24 -6
- package/cli/versions.ts +2 -2
- package/forms/index.ts +0 -3
- package/module.ts +33 -9
- package/nuxt.config.ts +4 -3
- package/package.json +11 -12
- package/server/api/cms/_auth/email/[token].get.ts +16 -0
- package/server/api/cms/_auth/email/confirm.post.ts +73 -0
- package/server/api/cms/_auth/email/index.delete.ts +11 -0
- package/server/api/cms/_auth/email/index.get.ts +10 -0
- package/server/api/cms/_auth/email/index.post.ts +86 -0
- package/server/api/cms/_auth/email/revert/[token].get.ts +15 -0
- package/server/api/cms/_auth/email/revert.post.ts +68 -0
- package/server/api/cms/_auth/me.patch.ts +1 -1
- package/server/api/cms/_auth/password.post.ts +1 -1
- package/server/api/cms/_collab/socket.ts +68 -20
- package/server/api/cms/_live.ts +1 -1
- package/server/api/cms/_privacy/export.post.ts +5 -1
- package/server/api/cms/_privacy/lookup.post.ts +5 -2
- package/server/api/cms/_users/[id].delete.ts +3 -0
- package/server/api/cms/_users/[id].patch.ts +114 -13
- package/server/api/cms/_users/index.post.ts +2 -1
- package/server/middleware/cms-session.ts +2 -0
- package/server/plugins/cms-0-config-check.ts +32 -7
- package/server/store/redis.ts +9 -1
- package/server/utils/cmsAudit.ts +10 -2
- package/server/utils/cmsAuth.ts +42 -6
- package/server/utils/cmsCollabServer.ts +27 -12
- package/server/utils/cmsEmailChange.ts +193 -0
- package/server/utils/cmsEmailChangeRules.ts +108 -0
- package/server/utils/cmsEmails.ts +155 -9
- package/server/utils/cmsLive.ts +7 -4
- package/server/utils/cmsPrivacy.ts +60 -11
- package/server/utils/cmsRetention.ts +4 -0
- package/server/utils/cmsSession.ts +42 -9
- package/src/appSecret.ts +88 -0
- package/src/index.ts +1 -1
- package/src/presets.ts +1 -33
- package/src/system.ts +1 -1
- package/starter/.env.example +3 -2
- package/starter/package.json +4 -4
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tinyzoo",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Code-first, distributable CMS for Nuxt 4 (Layer + Module).",
|
|
6
6
|
"license": "UNLICENSED",
|
|
@@ -51,10 +51,10 @@
|
|
|
51
51
|
],
|
|
52
52
|
"dependencies": {
|
|
53
53
|
"@fastify/busboy": "^3.2.6",
|
|
54
|
-
"@hocuspocus/extension-redis": "^
|
|
55
|
-
"@hocuspocus/provider": "^
|
|
56
|
-
"@hocuspocus/server": "^
|
|
57
|
-
"@nuxt/kit": "^4.
|
|
54
|
+
"@hocuspocus/extension-redis": "^4.8.0",
|
|
55
|
+
"@hocuspocus/provider": "^4.8.0",
|
|
56
|
+
"@hocuspocus/server": "^4.8.0",
|
|
57
|
+
"@nuxt/kit": "^4.6.4",
|
|
58
58
|
"@tiptap/core": "^3.34.0",
|
|
59
59
|
"@tiptap/extension-collaboration": "^3.34.0",
|
|
60
60
|
"@tiptap/extension-collaboration-caret": "3.34.0",
|
|
@@ -65,14 +65,13 @@
|
|
|
65
65
|
"@tiptap/vue-3": "^3.34.0",
|
|
66
66
|
"@tiptap/y-tiptap": "^3.3.0",
|
|
67
67
|
"@types/node": ">=20",
|
|
68
|
-
"@types/nodemailer": "^8.0.2",
|
|
69
68
|
"@types/pg": "^8.11.0",
|
|
70
69
|
"aws4fetch": "^1.0.20",
|
|
71
|
-
"drizzle-orm": "^0.
|
|
70
|
+
"drizzle-orm": "^0.45.4",
|
|
72
71
|
"image-size": "^2.0.2",
|
|
73
|
-
"ioredis": "^
|
|
72
|
+
"ioredis": "^6.0.0",
|
|
74
73
|
"jiti": "^2.6.0",
|
|
75
|
-
"nodemailer": "^
|
|
74
|
+
"nodemailer": "^10.6.0",
|
|
76
75
|
"pg": "^8.16.3",
|
|
77
76
|
"sharp": "^0.35.5",
|
|
78
77
|
"tsx": "^4.19.0",
|
|
@@ -80,14 +79,14 @@
|
|
|
80
79
|
"zod": "^4.0.0"
|
|
81
80
|
},
|
|
82
81
|
"devDependencies": {
|
|
83
|
-
"drizzle-kit": "^0.31.
|
|
82
|
+
"drizzle-kit": "^0.31.11",
|
|
84
83
|
"typescript": "^5.7.0"
|
|
85
84
|
},
|
|
86
85
|
"peerDependencies": {
|
|
87
86
|
"@internationalized/date": "^3.12.2",
|
|
88
87
|
"@nuxt/ui": "^4.9.0",
|
|
89
|
-
"nuxt": "^4.4
|
|
90
|
-
"nuxt-auth-utils": "^0.
|
|
88
|
+
"nuxt": "^4.6.4",
|
|
89
|
+
"nuxt-auth-utils": "^0.6.2"
|
|
91
90
|
},
|
|
92
91
|
"bin": {
|
|
93
92
|
"tinyzoo": "./cli/index.ts"
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// GET /api/cms/_auth/email/:token — what the confirmation page shows: the new address
|
|
2
|
+
// the link is for. 410 when the link no longer works (expired, used, replaced by a
|
|
3
|
+
// newer request, or cancelled by a password change). Opening the page changes
|
|
4
|
+
// nothing: mail scanners open links too. The change is a POST (confirm.post.ts).
|
|
5
|
+
export default defineEventHandler(async (event) => {
|
|
6
|
+
assertBuiltinAuth()
|
|
7
|
+
if (!(await rateLimit(`email-confirm:ip:${clientIp(event)}`, 40, 15 * 60_000))) throw tooManyRequests(event, 'Too many attempts; try again later', 15 * 60_000)
|
|
8
|
+
const { db, reg } = useCms()
|
|
9
|
+
const found = await findToken(db, reg, getRouterParam(event, 'token') ?? '', 'email')
|
|
10
|
+
// The account's pending change, if it can still happen (a dead one is deleted here).
|
|
11
|
+
const pending = found ? await readLiveEmailChange(db, reg, found.user.id) : null
|
|
12
|
+
if (!found || !emailChangeUsable(pending, found.token, found.user)) {
|
|
13
|
+
throw createError({ statusCode: 410, statusMessage: 'This link has expired or was already used' })
|
|
14
|
+
}
|
|
15
|
+
return { email: pending.email }
|
|
16
|
+
})
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { and, eq, isNull, sql } from 'tinyzoo'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
// POST /api/cms/_auth/email/confirm — make the change of sign-in email the link was sent
|
|
5
|
+
// for. Works signed in or not: the password was checked when the change was asked for,
|
|
6
|
+
// and the link proves the new mailbox; it is bound to one account and one address.
|
|
7
|
+
//
|
|
8
|
+
// Like a password change, it ends every session of the account (the address is half of
|
|
9
|
+
// how it signs in). A browser signed in to this same account stays signed in, now with
|
|
10
|
+
// the new address; any other browser's session is left alone. The old address is told,
|
|
11
|
+
// with a link that undoes the change (revert.post.ts): someone who knew the password
|
|
12
|
+
// could ask for a change to their own address and confirm it at once, and the owner,
|
|
13
|
+
// who still reads the old mailbox, gets the account back with it.
|
|
14
|
+
const body = z.object({ token: z.string().min(1).max(200) })
|
|
15
|
+
const GONE = 'This link has expired or was already used'
|
|
16
|
+
|
|
17
|
+
export default defineEventHandler(async (event) => {
|
|
18
|
+
assertBuiltinAuth()
|
|
19
|
+
if (!(await rateLimit(`email-confirm:ip:${clientIp(event)}`, 40, 15 * 60_000))) throw tooManyRequests(event, 'Too many attempts; try again later', 15 * 60_000)
|
|
20
|
+
const data = parseOr422(body, await readBody(event))
|
|
21
|
+
const { db, reg } = useCms()
|
|
22
|
+
const found = await findToken(db, reg, data.token, 'email')
|
|
23
|
+
const pending = found ? await readLiveEmailChange(db, reg, found.user.id) : null
|
|
24
|
+
if (!found || !emailChangeUsable(pending, found.token, found.user)) throw createError({ statusCode: 410, statusMessage: GONE })
|
|
25
|
+
const before = found.user
|
|
26
|
+
// Resolved before anything changes: without a public address (production) nothing happens.
|
|
27
|
+
const revertBase = adminLink(event, '/admin/email/revert/')
|
|
28
|
+
|
|
29
|
+
const taken = () => createError({ statusCode: 409, statusMessage: 'This address already belongs to another account', data: { code: 'email_taken' } })
|
|
30
|
+
if (await emailTaken(db, reg, pending.email, before.id)) {
|
|
31
|
+
// Only this link and its request end: a newer request made meanwhile stays.
|
|
32
|
+
await db.update(reg.cmsTokens).set({ usedAt: new Date() })
|
|
33
|
+
.where(and(eq(reg.cmsTokens.id, found.token.id), isNull(reg.cmsTokens.usedAt)))
|
|
34
|
+
await forgetEmailChange(db, reg, before.id, found.token.id)
|
|
35
|
+
throw taken()
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
let updated: any
|
|
39
|
+
let revertSecret = ''
|
|
40
|
+
try {
|
|
41
|
+
updated = await db.transaction(async (tx: any) => {
|
|
42
|
+
await lockUser(tx, reg, before.id)
|
|
43
|
+
// Claim the link atomically: of two simultaneous requests only one gets the row.
|
|
44
|
+
const [claimed] = await tx.update(reg.cmsTokens).set({ usedAt: new Date() })
|
|
45
|
+
.where(and(eq(reg.cmsTokens.id, found.token.id), isNull(reg.cmsTokens.usedAt))).returning({ id: reg.cmsTokens.id })
|
|
46
|
+
if (!claimed) throw createError({ statusCode: 410, statusMessage: GONE })
|
|
47
|
+
const u = reg.cmsUsers
|
|
48
|
+
const [row] = await tx.update(u)
|
|
49
|
+
.set({ email: pending.email, sessionVersion: sql`${u.sessionVersion} + 1`, updatedAt: new Date() })
|
|
50
|
+
.where(and(eq(u.id, before.id), eq(u.sessionVersion, pending.sv), eq(u.status, 'active'))).returning()
|
|
51
|
+
if (!row) throw createError({ statusCode: 410, statusMessage: GONE })
|
|
52
|
+
// Reset and email links already sent (to the old address, or an older request) stop working.
|
|
53
|
+
await endLinksOf(tx, reg, before.id, ['reset', 'email'])
|
|
54
|
+
// The way back, for the notice to the old address.
|
|
55
|
+
revertSecret = await issueEmailRevert(tx, reg, { userId: before.id, email: before.email, createdBy: before.id })
|
|
56
|
+
return row
|
|
57
|
+
})
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
// Two accounts confirming the same address at once: the unique index lets one through.
|
|
61
|
+
if (isUniqueViolation(err)) throw taken()
|
|
62
|
+
throw err
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const sameAccount = getCmsSession(event)?.id === updated.id
|
|
66
|
+
if (sameAccount) await continueCmsSession(event, updated) // the sign-in time stays
|
|
67
|
+
await audit(event, 'account.email', { userId: updated.id, meta: { email: updated.email, previousEmail: before.email } })
|
|
68
|
+
|
|
69
|
+
const locale = updated.locale || requestLocale(event)
|
|
70
|
+
event.waitUntil(sendCmsMail(emailChangedNotice({ to: before.email, newEmail: updated.email, revertUrl: revertBase + revertSecret, locale }))
|
|
71
|
+
.catch((err) => console.error('[cms] could not send the email changed notice', redactEmails(safeErrorMessage(err)))))
|
|
72
|
+
return { email: updated.email, signedIn: sameAccount }
|
|
73
|
+
})
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// DELETE /api/cms/_auth/email — cancel your pending change of sign-in email: the link
|
|
2
|
+
// that was sent stops working.
|
|
3
|
+
export default defineEventHandler(async (event) => {
|
|
4
|
+
assertBuiltinAuth()
|
|
5
|
+
const me = requireCmsUser(event)
|
|
6
|
+
const { db, reg } = useCms()
|
|
7
|
+
const pending = await readEmailChange(db, reg, me.id)
|
|
8
|
+
await endLinksOf(db, reg, me.id, ['email'])
|
|
9
|
+
if (pending) await audit(event, 'account.email_cancel', { meta: { email: pending.email } })
|
|
10
|
+
return { ok: true }
|
|
11
|
+
})
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// GET /api/cms/_auth/email — the change of your sign-in email that is waiting for its
|
|
2
|
+
// link to be opened, if any: { pending: { email, expiresAt } | null }. A change that can
|
|
3
|
+
// no longer happen (expired, cancelled by a new password) is forgotten on the way.
|
|
4
|
+
export default defineEventHandler(async (event) => {
|
|
5
|
+
assertBuiltinAuth()
|
|
6
|
+
const me = requireCmsUser(event)
|
|
7
|
+
const { db, reg } = useCms()
|
|
8
|
+
const pending = await readLiveEmailChange(db, reg, me.id)
|
|
9
|
+
return { pending: pending ? { email: pending.email, expiresAt: pending.expiresAt } : null }
|
|
10
|
+
})
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { eq } from 'tinyzoo'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
// POST /api/cms/_auth/email — ask to change your own sign-in email. Needs your current
|
|
5
|
+
// password. Nothing changes yet: a one-time link goes to the new address (it makes the
|
|
6
|
+
// change, see confirm.post.ts) and a notice to the current one (if it was not you, a new
|
|
7
|
+
// password cancels the change while it waits; once it is made, the next notice to the
|
|
8
|
+
// old address carries a link that undoes it, see revert.post.ts).
|
|
9
|
+
//
|
|
10
|
+
// Wrong passwords count against the same limits as failed sign-ins of this account
|
|
11
|
+
// (per address and per client address), so this is no second door for guessing it.
|
|
12
|
+
//
|
|
13
|
+
// The answer is the same whether or not the new address already has an account: the
|
|
14
|
+
// person asking is not told who has one. The owner of that address gets a notice
|
|
15
|
+
// instead of the link, and the change waits until it expires or is cancelled. The
|
|
16
|
+
// lookup and the emails happen after the response, so its timing tells nothing either.
|
|
17
|
+
const body = z.object({
|
|
18
|
+
email: emailSchema.pipe(z.string().max(254)),
|
|
19
|
+
password: z.string().max(200),
|
|
20
|
+
})
|
|
21
|
+
const WINDOW = 15 * 60_000
|
|
22
|
+
|
|
23
|
+
export default defineEventHandler(async (event) => {
|
|
24
|
+
assertBuiltinAuth()
|
|
25
|
+
const me = requireCmsUser(event)
|
|
26
|
+
if (isDemoAccount(me.email)) throw createError({ statusCode: 403, statusMessage: 'The demo account keeps its email', data: { code: 'demo_account' } })
|
|
27
|
+
const data = parseOr422(body, await readBody(event))
|
|
28
|
+
const ip = clientIp(event)
|
|
29
|
+
const signInKey = `login:email:${normalizeEmail(me.email ?? '')}`
|
|
30
|
+
if (!(await rateLimit(`login:ip:${ip}`, 30, WINDOW)) || !(await rateLimit(signInKey, 10, WINDOW))) {
|
|
31
|
+
throw tooManyRequests(event, 'Too many attempts; wait a few minutes and try again', WINDOW)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const { db, reg } = useCms()
|
|
35
|
+
const [u] = await db.select().from(reg.cmsUsers).where(eq(reg.cmsUsers.id, me.id))
|
|
36
|
+
const ok = u?.passwordHash
|
|
37
|
+
? await verifyPassword(u.passwordHash, data.password)
|
|
38
|
+
: (await verifyPassword(await dummyPasswordHash(), data.password), false)
|
|
39
|
+
if (!u || !ok) {
|
|
40
|
+
await audit(event, 'account.email_failed', { meta: { ip } })
|
|
41
|
+
throw createError({ statusCode: 422, statusMessage: 'Validation failed', data: [{ path: ['password'], message: 'Wrong password' }] })
|
|
42
|
+
}
|
|
43
|
+
await rateLimitRefund(`login:ip:${ip}`, WINDOW)
|
|
44
|
+
await rateLimitRefund(signInKey, WINDOW)
|
|
45
|
+
|
|
46
|
+
if (data.email === u.email) {
|
|
47
|
+
throw createError({ statusCode: 422, statusMessage: 'Validation failed', data: [{ path: ['email'], code: 'same_email', message: 'This is already your address' }] })
|
|
48
|
+
}
|
|
49
|
+
// A handful of requests an hour: each one sends two emails. Per account, per address
|
|
50
|
+
// written to (many accounts must not flood one stranger's mailbox) and per client.
|
|
51
|
+
const HOUR = 60 * 60_000
|
|
52
|
+
const allowed = (await rateLimit(`email-change:${u.id}`, 5, HOUR))
|
|
53
|
+
&& (await rateLimit(`email-change:to:${data.email}`, 3, HOUR))
|
|
54
|
+
&& (await rateLimit(`email-change:ip:${ip}`, 10, HOUR))
|
|
55
|
+
if (!allowed) throw tooManyRequests(event, 'Too many requests; try again later', HOUR)
|
|
56
|
+
if (u.sessionVersion !== event.context.cmsSessionVersion) {
|
|
57
|
+
await clearUserSession(event)
|
|
58
|
+
throw createError({ statusCode: 401, statusMessage: 'Authentication required' })
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Resolved while the request is alive (the configured public address, the person's language).
|
|
62
|
+
const linkBase = adminLink(event, '/admin/email/')
|
|
63
|
+
const forgotUrl = adminLink(event, '/admin/forgot')
|
|
64
|
+
const locale = u.locale || requestLocale(event)
|
|
65
|
+
const secret = await startEmailChange(db, reg, { userId: u.id, email: data.email, sessionVersion: u.sessionVersion })
|
|
66
|
+
const expiresAt = new Date(Date.now() + EMAIL_CHANGE_TTL_MS)
|
|
67
|
+
|
|
68
|
+
const work = (async () => {
|
|
69
|
+
const inUse = await emailTaken(db, reg, data.email, u.id)
|
|
70
|
+
await audit(event, 'account.email_request', { userId: u.id, meta: { email: data.email, previousEmail: u.email, ...(inUse ? { inUse: true } : {}) } })
|
|
71
|
+
const send = async (msg: Parameters<typeof sendCmsMail>[0], what: string) => {
|
|
72
|
+
try {
|
|
73
|
+
await sendCmsMail(msg)
|
|
74
|
+
}
|
|
75
|
+
catch (err) {
|
|
76
|
+
console.error(`[cms] could not send the ${what} email`, redactEmails(safeErrorMessage(err)))
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// The old address first: its owner hears before the link can be opened.
|
|
80
|
+
await send(emailRequestedNotice({ to: u.email, newEmail: data.email, url: forgotUrl, locale }), 'email change notice')
|
|
81
|
+
await send(inUse ? emailInUseNotice({ to: data.email, locale }) : emailConfirmEmail({ to: data.email, url: linkBase + secret, locale }), inUse ? 'address-in-use' : 'email confirmation')
|
|
82
|
+
})().catch((err) => console.error('[cms] email change request failed', redactEmails(safeErrorMessage(err))))
|
|
83
|
+
event.waitUntil(work)
|
|
84
|
+
|
|
85
|
+
return { pending: { email: data.email, expiresAt } }
|
|
86
|
+
})
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// GET /api/cms/_auth/email/revert/:token — what the "undo the change" page shows: the
|
|
2
|
+
// address the account gets back. 410 when the link no longer works (expired, used, or
|
|
3
|
+
// a change before it was undone). Opening the page changes nothing (mail scanners open
|
|
4
|
+
// links); the undo is a POST with a new password (revert.post.ts).
|
|
5
|
+
export default defineEventHandler(async (event) => {
|
|
6
|
+
assertBuiltinAuth()
|
|
7
|
+
if (!(await rateLimit(`email-revert:view:ip:${clientIp(event)}`, 40, 15 * 60_000))) throw tooManyRequests(event, 'Too many attempts; try again later', 15 * 60_000)
|
|
8
|
+
const { db, reg } = useCms()
|
|
9
|
+
const found = await findToken(db, reg, getRouterParam(event, 'token') ?? '', 'email-revert')
|
|
10
|
+
const revert = found ? await readEmailRevert(db, reg, found.user.id, found.token.id) : null
|
|
11
|
+
if (!found || !revert || found.user.status !== 'active') {
|
|
12
|
+
throw createError({ statusCode: 410, statusMessage: 'This link has expired or was already used' })
|
|
13
|
+
}
|
|
14
|
+
return { email: revert.email }
|
|
15
|
+
})
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { and, eq, isNull, sql } from 'tinyzoo'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
// POST /api/cms/_auth/email/revert { token, password } — undo a change of sign-in email
|
|
5
|
+
// with the link from the "your email was changed" notice to the old address.
|
|
6
|
+
//
|
|
7
|
+
// The threat it answers: someone who knows the password (and no more) asks for a change
|
|
8
|
+
// to their own address and confirms it at once. Cancelling by a new password is too
|
|
9
|
+
// slow for that, and from then on a password reset would go to them. The old mailbox
|
|
10
|
+
// is the proof here, as it is for a reset link, so this one step:
|
|
11
|
+
// - gives the account its old address back (unless another account has it now: 409,
|
|
12
|
+
// nothing changes — an administrator has to sort that out),
|
|
13
|
+
// - sets the new password chosen on the page — in the same step, because the person
|
|
14
|
+
// who made the change knows the old one: restoring the address alone would let them
|
|
15
|
+
// straight back in,
|
|
16
|
+
// - ends every session (session version) and every reset and email link, forgets a
|
|
17
|
+
// pending change, and ends the ways back of later changes (they would undo this);
|
|
18
|
+
// those of earlier changes stay, they lead further back,
|
|
19
|
+
// - signs this browser in, as a reset does, and is audited (account.email_revert),
|
|
20
|
+
// - tells the address it replaces: the owner of that mailbox may have made the change
|
|
21
|
+
// (an old work mailbox read by someone else now), and must not be locked out unheard.
|
|
22
|
+
const body = z.object({ token: z.string().min(1).max(200), password: passwordSchema })
|
|
23
|
+
const GONE = 'This link has expired or was already used'
|
|
24
|
+
|
|
25
|
+
export default defineEventHandler(async (event) => {
|
|
26
|
+
assertBuiltinAuth()
|
|
27
|
+
if (!(await rateLimit(`email-revert:ip:${clientIp(event)}`, 20, 15 * 60_000))) throw tooManyRequests(event, 'Too many attempts; try again later', 15 * 60_000)
|
|
28
|
+
const data = parseOr422(body, await readBody(event))
|
|
29
|
+
const { db, reg } = useCms()
|
|
30
|
+
const found = await findToken(db, reg, data.token, 'email-revert')
|
|
31
|
+
const revert = found ? await readEmailRevert(db, reg, found.user.id, found.token.id) : null
|
|
32
|
+
if (!found || !revert || found.user.status !== 'active') throw createError({ statusCode: 410, statusMessage: GONE })
|
|
33
|
+
const before = found.user
|
|
34
|
+
|
|
35
|
+
const taken = () => createError({ statusCode: 409, statusMessage: 'This address now belongs to another account', data: { code: 'email_taken' } })
|
|
36
|
+
if (await emailTaken(db, reg, revert.email, before.id)) throw taken()
|
|
37
|
+
|
|
38
|
+
const passwordHash = await hashPassword(data.password)
|
|
39
|
+
let user: any
|
|
40
|
+
try {
|
|
41
|
+
user = await db.transaction(async (tx: any) => {
|
|
42
|
+
await lockUser(tx, reg, before.id)
|
|
43
|
+
// Claim the link atomically: of two simultaneous requests only one gets the row.
|
|
44
|
+
const [claimed] = await tx.update(reg.cmsTokens).set({ usedAt: new Date() })
|
|
45
|
+
.where(and(eq(reg.cmsTokens.id, found.token.id), isNull(reg.cmsTokens.usedAt))).returning({ id: reg.cmsTokens.id })
|
|
46
|
+
if (!claimed) throw createError({ statusCode: 410, statusMessage: GONE })
|
|
47
|
+
const u = reg.cmsUsers
|
|
48
|
+
const [row] = await tx.update(u)
|
|
49
|
+
.set({ email: revert.email, passwordHash, sessionVersion: sql`${u.sessionVersion} + 1`, updatedAt: new Date(), lastLoginAt: new Date() })
|
|
50
|
+
.where(and(eq(u.id, before.id), eq(u.status, 'active'))).returning()
|
|
51
|
+
if (!row) throw createError({ statusCode: 410, statusMessage: GONE })
|
|
52
|
+
await endLinksOf(tx, reg, before.id, ['reset', 'email'])
|
|
53
|
+
await endRevertLinks(tx, reg, before.id, found.token.createdAt)
|
|
54
|
+
return row
|
|
55
|
+
})
|
|
56
|
+
}
|
|
57
|
+
catch (err) {
|
|
58
|
+
if (isUniqueViolation(err)) throw taken()
|
|
59
|
+
throw err
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
await startCmsSession(event, user)
|
|
63
|
+
await audit(event, 'account.email_revert', { userId: user.id, meta: { email: user.email, previousEmail: before.email } })
|
|
64
|
+
const locale = user.locale || requestLocale(event)
|
|
65
|
+
event.waitUntil(sendCmsMail(emailRevertedNotice({ to: before.email, restoredEmail: user.email, locale }))
|
|
66
|
+
.catch((err) => console.error('[cms] could not send the email reverted notice', redactEmails(safeErrorMessage(err)))))
|
|
67
|
+
return { user: sessionUser(user) }
|
|
68
|
+
})
|
|
@@ -26,7 +26,7 @@ export default defineEventHandler(async (event) => {
|
|
|
26
26
|
await clearUserSession(event)
|
|
27
27
|
throw createError({ statusCode: 401, statusMessage: 'Authentication required' })
|
|
28
28
|
}
|
|
29
|
-
await
|
|
29
|
+
await continueCmsSession(event, u) // the sign-in time stays: this does not make the session last longer
|
|
30
30
|
await audit(event, 'account.update', { meta: { fields: Object.keys(data) } })
|
|
31
31
|
return { user: sessionUser(u) }
|
|
32
32
|
})
|
|
@@ -23,7 +23,7 @@ export default defineEventHandler(async (event) => {
|
|
|
23
23
|
await clearUserSession(event)
|
|
24
24
|
throw createError({ statusCode: 401, statusMessage: 'Authentication required' })
|
|
25
25
|
}
|
|
26
|
-
await
|
|
26
|
+
await continueCmsSession(event, updated) // the sign-in time stays
|
|
27
27
|
await audit(event, 'account.password')
|
|
28
28
|
return { ok: true }
|
|
29
29
|
})
|
|
@@ -2,15 +2,43 @@
|
|
|
2
2
|
// own port. Admitted like the realtime socket (same origin, valid session); which
|
|
3
3
|
// documents it may open is decided per document (cmsCollabServer.onAuthenticate).
|
|
4
4
|
//
|
|
5
|
-
// Hocuspocus
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
5
|
+
// Hocuspocus 4 takes any WebSocket-like object and a web Request, and is fed the
|
|
6
|
+
// messages and the close by whoever owns the socket — here the crossws hooks below,
|
|
7
|
+
// the way Hocuspocus' own server does it. Frames that arrive while `open` is still
|
|
8
|
+
// waiting for the server are kept and handed over in order.
|
|
9
|
+
//
|
|
10
|
+
// Two things still need the real `ws` socket behind the crossws peer, which sits at
|
|
11
|
+
// `peer._internal.ws` (crossws-private): the message size limit, and the pings.
|
|
12
|
+
// Hocuspocus 4 closes a connection that has been silent for a minute and no longer
|
|
13
|
+
// pings by itself (Hocuspocus 3 did): this handler pings every heartbeat and counts the
|
|
14
|
+
// pong as activity, so a tab that is open but quiet (in the background) stays
|
|
15
|
+
// connected and a dead one is noticed. Checked here; a miss closes the connection
|
|
16
|
+
// with a logged error instead of running without them.
|
|
9
17
|
const MAX_SOCKETS_PER_USER = 10
|
|
10
18
|
// Shared-editing messages are small; the `ws` default (100 MiB) is not.
|
|
11
19
|
const MAX_PAYLOAD_BYTES = 2 * 1024 * 1024
|
|
20
|
+
/** Frames a socket may send before the server has taken it (it sends a handful). */
|
|
21
|
+
const MAX_EARLY_FRAMES = 100
|
|
22
|
+
const PING_MS = 30_000
|
|
12
23
|
const socketsByUser = new Map<string, Set<any>>()
|
|
13
24
|
|
|
25
|
+
interface CollabPeerState {
|
|
26
|
+
userId: string
|
|
27
|
+
/** Hocuspocus' side of the socket, once `open` has handed it over. */
|
|
28
|
+
connection?: { handleMessage(data: Uint8Array): void; handleClose(event?: { code: number; reason: string }): void }
|
|
29
|
+
/** Frames received before that. */
|
|
30
|
+
early: Uint8Array[]
|
|
31
|
+
closed?: { code: number; reason: string }
|
|
32
|
+
ping?: ReturnType<typeof setInterval>
|
|
33
|
+
}
|
|
34
|
+
const peers = new WeakMap<object, CollabPeerState>()
|
|
35
|
+
|
|
36
|
+
function forget(peer: any, state: CollabPeerState) {
|
|
37
|
+
const mine = socketsByUser.get(state.userId)
|
|
38
|
+
mine?.delete(peer)
|
|
39
|
+
if (mine && !mine.size) socketsByUser.delete(state.userId)
|
|
40
|
+
}
|
|
41
|
+
|
|
14
42
|
export default defineWebSocketHandler({
|
|
15
43
|
upgrade(request: any) {
|
|
16
44
|
return admitAdminSocket(request)
|
|
@@ -19,12 +47,13 @@ export default defineWebSocketHandler({
|
|
|
19
47
|
const user = peer.context?.cmsUser
|
|
20
48
|
if (!user) return peer.close(4401, 'Unauthorized')
|
|
21
49
|
const ws = peer._internal?.ws
|
|
22
|
-
|
|
23
|
-
if (!ws || typeof ws.on !== 'function' || !req?.headers) {
|
|
50
|
+
if (!ws?._receiver || typeof ws._receiver._maxPayload !== 'number' || typeof ws.ping !== 'function' || typeof ws.on !== 'function') {
|
|
24
51
|
console.error('[cms] collab: no raw socket behind the crossws peer — has crossws changed? Refusing.')
|
|
25
52
|
return peer.close(1011, 'Shared editing unavailable')
|
|
26
53
|
}
|
|
27
|
-
|
|
54
|
+
ws._receiver._maxPayload = MAX_PAYLOAD_BYTES
|
|
55
|
+
const state: CollabPeerState = { userId: user.id, early: [] }
|
|
56
|
+
peers.set(peer, state)
|
|
28
57
|
// Too many tabs: the oldest gives way (as on the realtime socket).
|
|
29
58
|
const mine = socketsByUser.get(user.id) ?? new Set()
|
|
30
59
|
if (mine.size >= MAX_SOCKETS_PER_USER) {
|
|
@@ -32,20 +61,39 @@ export default defineWebSocketHandler({
|
|
|
32
61
|
mine.delete(oldest)
|
|
33
62
|
oldest?.close?.(4429, 'Too many open tabs')
|
|
34
63
|
}
|
|
35
|
-
mine.add(
|
|
64
|
+
mine.add(peer)
|
|
36
65
|
socketsByUser.set(user.id, mine)
|
|
37
|
-
ws.on('close', () => {
|
|
38
|
-
mine.delete(ws)
|
|
39
|
-
if (!mine.size) socketsByUser.delete(user.id)
|
|
40
|
-
})
|
|
41
|
-
// One socket carries every document the page has open.
|
|
42
|
-
ws.setMaxListeners?.(Number.POSITIVE_INFINITY)
|
|
43
|
-
ws.on('error', (err: unknown) => console.error('[cms] collab socket error', (err as Error)?.message ?? err))
|
|
44
66
|
const server = await useCollabServer()
|
|
45
|
-
|
|
67
|
+
if (state.closed) return // gone while the server started
|
|
68
|
+
const connection = server.handleConnection(peer.websocket, peer.request, { user, sv: peer.context.cmsSessionVersion, iat: peer.context.cmsSignedInAt })
|
|
69
|
+
state.connection = connection
|
|
70
|
+
ws.on('pong', () => connection.touch())
|
|
71
|
+
state.ping = setInterval(() => {
|
|
72
|
+
try { ws.ping() }
|
|
73
|
+
catch { /* closing */ }
|
|
74
|
+
}, cmsTimerMs('CMS_TEST_COLLAB_HEARTBEAT_MS', PING_MS))
|
|
75
|
+
;(state.ping as any).unref?.()
|
|
76
|
+
for (const frame of state.early.splice(0)) connection.handleMessage(frame)
|
|
77
|
+
},
|
|
78
|
+
message(peer: any, message: any) {
|
|
79
|
+
const state = peers.get(peer)
|
|
80
|
+
if (!state) return
|
|
81
|
+
const data: Uint8Array = message.uint8Array()
|
|
82
|
+
if (state.connection) return state.connection.handleMessage(data)
|
|
83
|
+
if (state.early.length >= MAX_EARLY_FRAMES) return peer.close(1008, 'Too many messages')
|
|
84
|
+
state.early.push(data)
|
|
85
|
+
},
|
|
86
|
+
close(peer: any, event: any) {
|
|
87
|
+
const state = peers.get(peer)
|
|
88
|
+
if (!state) return
|
|
89
|
+
state.closed = { code: Number(event?.code) || 1005, reason: String(event?.reason ?? '') }
|
|
90
|
+
state.early.length = 0
|
|
91
|
+
if (state.ping) clearInterval(state.ping)
|
|
92
|
+
forget(peer, state)
|
|
93
|
+
state.connection?.handleClose(state.closed)
|
|
94
|
+
peers.delete(peer)
|
|
95
|
+
},
|
|
96
|
+
error(_peer: any, err: any) {
|
|
97
|
+
console.error('[cms] collab socket error', err?.message ?? err)
|
|
46
98
|
},
|
|
47
|
-
// Hocuspocus owns the socket from `open` on; these stay deliberately inert.
|
|
48
|
-
message() {},
|
|
49
|
-
close() {},
|
|
50
|
-
error() {},
|
|
51
99
|
})
|
package/server/api/cms/_live.ts
CHANGED
|
@@ -16,7 +16,7 @@ export default defineWebSocketHandler({
|
|
|
16
16
|
// (the `ws` default is 100 MiB). crossws-private, so only when it is there.
|
|
17
17
|
const ws = peer._internal?.ws
|
|
18
18
|
if (ws?._receiver && typeof ws._receiver._maxPayload === 'number') ws._receiver._maxPayload = 16 * 1024
|
|
19
|
-
liveOpen(peer, user, peer.context.cmsSessionVersion)
|
|
19
|
+
liveOpen(peer, user, peer.context.cmsSessionVersion, peer.context.cmsSignedInAt)
|
|
20
20
|
},
|
|
21
21
|
message(peer: any, message: any) {
|
|
22
22
|
return liveMessage(peer, message.text())
|
|
@@ -10,12 +10,16 @@ export default defineEventHandler(async (event) => {
|
|
|
10
10
|
const found = await findSubmissions(db, reg, email)
|
|
11
11
|
const account = await findAccount(db, reg, email)
|
|
12
12
|
const entries = await findAuditEntries(db, reg, email, account?.id ?? null)
|
|
13
|
+
const states = await findEmailStates(db, reg, email)
|
|
13
14
|
const document = {
|
|
14
15
|
exportedAt: new Date().toISOString(),
|
|
15
16
|
email,
|
|
16
17
|
formSubmissions: found.map(({ form, row }) => submissionView(form, row)),
|
|
17
18
|
account: account ? accountView(account) : null,
|
|
18
|
-
|
|
19
|
+
// A change of address names another address too; it is left out where it isn't this person's (auditExportMeta).
|
|
20
|
+
auditEntries: entries.map((a) => ({ id: a.id, createdAt: a.createdAt, action: a.action, entity: a.entity, recordId: a.recordId, userId: a.userId, meta: auditExportMeta(a, email, account?.id ?? null) })),
|
|
21
|
+
// A change of sign-in address waiting for this one to be confirmed, or a way back to it after a change.
|
|
22
|
+
emailChanges: states.map((r) => ({ kind: r.kind === 'change' ? 'waiting for confirmation' : 'way back to this address', accountId: r.userId, expiresAt: r.expiresAt })),
|
|
19
23
|
}
|
|
20
24
|
// The audit entry records that an export happened and its size, never the address.
|
|
21
25
|
await audit(event, 'privacy.export', { meta: { submissions: found.length, account: !!account, auditEntries: entries.length } })
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { sql } from 'tinyzoo'
|
|
2
2
|
|
|
3
3
|
// POST /api/cms/_privacy/lookup { email } — what is stored about one email address:
|
|
4
|
-
// form submissions whose email fields match, the CMS account with that address
|
|
5
|
-
// audit entries about it. Administrators only, rate limited; the address travels in the
|
|
4
|
+
// form submissions whose email fields match, the CMS account with that address, the
|
|
5
|
+
// audit entries about it and how many changes of sign-in address name it. Administrators only, rate limited; the address travels in the
|
|
6
6
|
// body (not the URL), so it does not end up in access logs.
|
|
7
7
|
export default defineEventHandler(async (event) => {
|
|
8
8
|
const me = requireCmsAdmin(event)
|
|
@@ -13,10 +13,13 @@ export default defineEventHandler(async (event) => {
|
|
|
13
13
|
const found = await findSubmissions(db, reg, email)
|
|
14
14
|
const account = await findAccount(db, reg, email)
|
|
15
15
|
const entries = await findAuditEntries(db, reg, email, account?.id ?? null, 50)
|
|
16
|
+
// A change of sign-in address waiting for this one, or a way back to it (cms_state).
|
|
17
|
+
const states = await findEmailStates(db, reg, email)
|
|
16
18
|
return {
|
|
17
19
|
email,
|
|
18
20
|
submissions: found.map(({ form, row }) => ({ ...submissionView(form, row), formLabel: form.label })),
|
|
19
21
|
account: account ? accountView(account) : null,
|
|
22
|
+
emailChanges: states.length,
|
|
20
23
|
audit: { total: entries.length >= 50 ? await countAudit(db, reg, email, account?.id ?? null) : entries.length, latest: entries.slice(0, 20).map((a) => ({ id: a.id, action: a.action, entity: a.entity, createdAt: a.createdAt })) },
|
|
21
24
|
}
|
|
22
25
|
})
|
|
@@ -15,6 +15,9 @@ export default defineEventHandler(async (event) => {
|
|
|
15
15
|
await tx.execute(sql`select pg_advisory_xact_lock(${ADMIN_GUARD_LOCK})`)
|
|
16
16
|
if (target.role === 'admin' && target.status === 'active') await assertAnotherActiveAdmin(tx, reg, id)
|
|
17
17
|
await tx.delete(reg.cmsUsers).where(eq(reg.cmsUsers.id, id))
|
|
18
|
+
// A pending change of email address and the ways back (cms_state, not cascaded) go with the account.
|
|
19
|
+
await tx.delete(reg.cmsState).where(eq(reg.cmsState.key, emailChangeStateKey(id)))
|
|
20
|
+
await tx.delete(reg.cmsState).where(sql`${reg.cmsState.key} like ${emailRevertStatePattern(id)}`)
|
|
18
21
|
})
|
|
19
22
|
await audit(event, 'user.delete', { recordId: id, meta: { email: target.email } })
|
|
20
23
|
return { ok: true }
|