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.
- 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/package.json +9 -10
- 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/_collab/socket.ts +68 -20
- 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/store/redis.ts +9 -1
- package/server/utils/cmsAudit.ts +10 -2
- package/server/utils/cmsAuth.ts +15 -4
- package/server/utils/cmsCollabServer.ts +22 -9
- package/server/utils/cmsEmailChange.ts +193 -0
- package/server/utils/cmsEmailChangeRules.ts +108 -0
- package/server/utils/cmsEmails.ts +155 -9
- package/server/utils/cmsPrivacy.ts +60 -11
- package/server/utils/cmsRetention.ts +4 -0
- package/src/system.ts +1 -1
- package/starter/package.json +2 -2
|
@@ -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
|
+
})
|
|
@@ -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 })
|
|
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
|
})
|
|
@@ -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 }
|
|
@@ -1,13 +1,34 @@
|
|
|
1
1
|
import { CMS_ROLES, eq, sql } from 'tinyzoo'
|
|
2
2
|
import { z } from 'zod'
|
|
3
3
|
|
|
4
|
-
// PATCH /api/cms/_users/:id — change someone's role, or disable /
|
|
5
|
-
// You cannot change your own role or
|
|
6
|
-
//
|
|
4
|
+
// PATCH /api/cms/_users/:id — change someone's role or sign-in email, or disable /
|
|
5
|
+
// re-enable them. You cannot change your own role, email or access here (your own
|
|
6
|
+
// email changes on your account page, with your password and a confirmation link),
|
|
7
|
+
// and the last active administrator always stays. Disabling, a new role and a new
|
|
8
|
+
// email sign the person out everywhere at once.
|
|
9
|
+
//
|
|
10
|
+
// A new email needs the administrator's own password (`password`): a session left open
|
|
11
|
+
// on a shared computer, or stolen, must not be enough to move someone's account to
|
|
12
|
+
// another mailbox. Wrong passwords count against the same limits as failed sign-ins of
|
|
13
|
+
// the administrator's address. The new email takes effect at once (the administrator
|
|
14
|
+
// vouches for it): links already sent stop working (a password reset waiting in the old
|
|
15
|
+
// mailbox would otherwise still open the account), the old address is told and the new
|
|
16
|
+
// one gets a note — unless the account is disabled: nobody can sign in with it, so
|
|
17
|
+
// neither address hears "sign in with the new one". For someone who has not accepted
|
|
18
|
+
// their invitation yet, the invitation goes to the new address instead (the old link
|
|
19
|
+
// stops working) and its link is returned, as when resending.
|
|
20
|
+
//
|
|
21
|
+
// Unlike a change the person makes, the notice to the old address carries no link that
|
|
22
|
+
// undoes it: the old mailbox is often the reason for the change (left, handed over), and
|
|
23
|
+
// such a link would give the account to whoever reads it now. The protection here is the
|
|
24
|
+
// administrator's password; someone who has that can do far more than this anyway.
|
|
7
25
|
const body = z.object({
|
|
8
26
|
role: z.enum(CMS_ROLES).optional(),
|
|
9
27
|
status: z.enum(['active', 'disabled']).optional(),
|
|
28
|
+
email: emailSchema.pipe(z.string().max(254)).optional(),
|
|
29
|
+
password: z.string().max(200).optional(),
|
|
10
30
|
})
|
|
31
|
+
const WINDOW = 15 * 60_000
|
|
11
32
|
|
|
12
33
|
export default defineEventHandler(async (event) => {
|
|
13
34
|
assertBuiltinAuth()
|
|
@@ -17,29 +38,109 @@ export default defineEventHandler(async (event) => {
|
|
|
17
38
|
const { db, reg } = useCms()
|
|
18
39
|
const [target] = await db.select().from(reg.cmsUsers).where(eq(reg.cmsUsers.id, id))
|
|
19
40
|
if (!target) throw createError({ statusCode: 404, statusMessage: 'Not found' })
|
|
20
|
-
if (id === me.id)
|
|
41
|
+
if (id === me.id) {
|
|
42
|
+
throw createError({ statusCode: 409, statusMessage: data.email !== undefined ? 'Change your own email on your account page' : 'You cannot change your own role or access', data: { code: 'self' } })
|
|
43
|
+
}
|
|
21
44
|
if (data.status === 'active' && target.status === 'invited') {
|
|
22
45
|
throw createError({ statusCode: 409, statusMessage: 'This person has not accepted the invitation yet' })
|
|
23
46
|
}
|
|
24
47
|
|
|
48
|
+
const newEmail = data.email !== undefined && data.email !== target.email ? data.email : null
|
|
49
|
+
let links: { invite?: string; signIn?: string } = {}
|
|
50
|
+
if (newEmail) {
|
|
51
|
+
await checkOwnPassword(event, me.id, me.email, data.password)
|
|
52
|
+
if (isDemoAccount(target.email)) throw createError({ statusCode: 403, statusMessage: 'The demo account keeps its email', data: { code: 'demo_account' } })
|
|
53
|
+
if (await emailTaken(db, reg, newEmail, id)) throw emailInUse()
|
|
54
|
+
// Resolved before anything changes: without a public address (production) nothing happens.
|
|
55
|
+
links = target.status === 'invited' ? { invite: adminLink(event, '/admin/invite/') } : { signIn: adminLink(event, '/admin/login') }
|
|
56
|
+
}
|
|
57
|
+
|
|
25
58
|
const losesAdmin = target.role === 'admin' && target.status === 'active'
|
|
26
59
|
&& ((data.role && data.role !== 'admin') || data.status === 'disabled')
|
|
27
60
|
|
|
28
|
-
const set: Record<string, unknown> = {
|
|
29
|
-
if (data.
|
|
61
|
+
const set: Record<string, unknown> = { updatedAt: new Date() }
|
|
62
|
+
if (data.role) set.role = data.role
|
|
63
|
+
if (data.status) set.status = data.status
|
|
64
|
+
if (newEmail) set.email = newEmail
|
|
65
|
+
if (data.status === 'disabled' || (data.role && data.role !== target.role) || newEmail) {
|
|
30
66
|
set.sessionVersion = sql`${reg.cmsUsers.sessionVersion} + 1`
|
|
31
67
|
}
|
|
32
68
|
// Check-and-change under one lock, so two administrators demoting each other at the
|
|
33
69
|
// same moment cannot both pass the "another active admin remains" check.
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
70
|
+
let updated: any
|
|
71
|
+
try {
|
|
72
|
+
updated = await db.transaction(async (tx: any) => {
|
|
73
|
+
await tx.execute(sql`select pg_advisory_xact_lock(${ADMIN_GUARD_LOCK})`)
|
|
74
|
+
if (losesAdmin) await assertAnotherActiveAdmin(tx, reg, id)
|
|
75
|
+
const [row] = await tx.update(reg.cmsUsers).set(set).where(eq(reg.cmsUsers.id, id)).returning()
|
|
76
|
+
if (row && newEmail) {
|
|
77
|
+
await endLinksOf(tx, reg, id, ['reset', 'email', 'invite'])
|
|
78
|
+
// Ways back from earlier changes go too: the administrator chose this address,
|
|
79
|
+
// often because an old mailbox is someone else's now.
|
|
80
|
+
await endRevertLinks(tx, reg, id)
|
|
81
|
+
}
|
|
82
|
+
return row
|
|
83
|
+
})
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
// Two changes to the same address at the same moment: the unique index lets one through.
|
|
87
|
+
if (isUniqueViolation(err)) throw emailInUse()
|
|
88
|
+
throw err
|
|
89
|
+
}
|
|
40
90
|
if (!updated) throw createError({ statusCode: 404, statusMessage: 'Not found' })
|
|
41
91
|
|
|
42
92
|
if (data.role && data.role !== target.role) await audit(event, 'user.role', { recordId: id, meta: { from: target.role, to: data.role } })
|
|
43
93
|
if (data.status && data.status !== target.status) await audit(event, data.status === 'disabled' ? 'user.disable' : 'user.enable', { recordId: id })
|
|
44
|
-
|
|
94
|
+
|
|
95
|
+
let invitation: { inviteUrl: string; emailed: boolean } | undefined
|
|
96
|
+
if (newEmail) {
|
|
97
|
+
await audit(event, 'user.email', { recordId: id, meta: { email: newEmail, previousEmail: target.email } })
|
|
98
|
+
const locale = updated.locale || me.locale || requestLocale(event)
|
|
99
|
+
if (links.invite && updated.status === 'invited') {
|
|
100
|
+
// Not accepted yet: the invitation goes to the new address (nothing to the old one — it may be a typo, a stranger's).
|
|
101
|
+
const secret = await issueToken(db, reg, { userId: id, kind: 'invite', ttlMs: INVITE_TTL_MS, createdBy: me.id })
|
|
102
|
+
const inviteUrl = links.invite + secret
|
|
103
|
+
let emailed = false
|
|
104
|
+
try {
|
|
105
|
+
emailed = await sendCmsMail(inviteEmail({ to: newEmail, inviter: me.name || me.email || 'An administrator', url: inviteUrl, role: updated.role, locale }))
|
|
106
|
+
}
|
|
107
|
+
catch (err) {
|
|
108
|
+
console.error('[cms] could not send the invitation email', redactEmails(safeErrorMessage(err)))
|
|
109
|
+
}
|
|
110
|
+
invitation = { inviteUrl, emailed }
|
|
111
|
+
}
|
|
112
|
+
else if (links.signIn && updated.status === 'active') {
|
|
113
|
+
const signInUrl = links.signIn
|
|
114
|
+
event.waitUntil((async () => {
|
|
115
|
+
for (const msg of [emailChangedNotice({ to: target.email, newEmail, byAdmin: true, locale }), emailSetNotice({ to: newEmail, url: signInUrl, locale })]) {
|
|
116
|
+
await sendCmsMail(msg).catch((err) => console.error('[cms] could not send the email change notice', redactEmails(safeErrorMessage(err))))
|
|
117
|
+
}
|
|
118
|
+
})())
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return { user: { id: updated.id, email: updated.email, name: updated.name, role: updated.role, status: updated.status }, ...invitation }
|
|
45
122
|
})
|
|
123
|
+
|
|
124
|
+
/** The acting administrator's own password, for a change of someone's email (422 on `password` when wrong or missing). */
|
|
125
|
+
async function checkOwnPassword(event: any, myId: string, myEmail: string | undefined, password: string | undefined) {
|
|
126
|
+
const ip = clientIp(event)
|
|
127
|
+
const signInKey = `login:email:${normalizeEmail(myEmail ?? '')}`
|
|
128
|
+
if (!(await rateLimit(`login:ip:${ip}`, 30, WINDOW)) || !(await rateLimit(signInKey, 10, WINDOW))) {
|
|
129
|
+
throw tooManyRequests(event, 'Too many attempts; wait a few minutes and try again', WINDOW)
|
|
130
|
+
}
|
|
131
|
+
const { db, reg } = useCms()
|
|
132
|
+
const [u] = await db.select().from(reg.cmsUsers).where(eq(reg.cmsUsers.id, myId))
|
|
133
|
+
const ok = u?.passwordHash && password
|
|
134
|
+
? await verifyPassword(u.passwordHash, password)
|
|
135
|
+
: (await verifyPassword(await dummyPasswordHash(), password ?? ''), false)
|
|
136
|
+
if (!ok) {
|
|
137
|
+
await audit(event, 'account.email_failed', { meta: { ip } })
|
|
138
|
+
throw createError({ statusCode: 422, statusMessage: 'Validation failed', data: [{ path: ['password'], message: password ? 'Wrong password' : 'Required' }] })
|
|
139
|
+
}
|
|
140
|
+
await rateLimitRefund(`login:ip:${ip}`, WINDOW)
|
|
141
|
+
await rateLimitRefund(signInKey, WINDOW)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function emailInUse() {
|
|
145
|
+
return createError({ statusCode: 409, statusMessage: 'This address already has access', data: [{ path: ['email'], code: 'unique', message: 'Already has access' }] })
|
|
146
|
+
}
|
|
@@ -17,7 +17,8 @@ export default defineEventHandler(async (event) => {
|
|
|
17
17
|
const { db, reg } = useCms()
|
|
18
18
|
|
|
19
19
|
const [existing] = await db.select({ id: reg.cmsUsers.id }).from(reg.cmsUsers).where(eq(reg.cmsUsers.email, data.email))
|
|
20
|
-
|
|
20
|
+
// An address another account can still take back (a way back from a change) counts as taken.
|
|
21
|
+
if (existing || await emailReserved(db, reg, data.email)) {
|
|
21
22
|
throw createError({ statusCode: 409, statusMessage: 'This person already has access', data: [{ path: ['email'], code: 'unique', message: 'Already has access' }] })
|
|
22
23
|
}
|
|
23
24
|
|
package/server/store/redis.ts
CHANGED
|
@@ -8,11 +8,19 @@ import type { CmsStoreConfig, SharedStore } from './types'
|
|
|
8
8
|
// The subscriber connection is the opposite — it waits and re-subscribes after
|
|
9
9
|
// every reconnect, so an instance that booted before Redis was up still hears the
|
|
10
10
|
// other replicas once it is.
|
|
11
|
+
//
|
|
12
|
+
// RESP2 on every connection (`protocol: 2`), as with ioredis 5. ioredis 6 opens with
|
|
13
|
+
// `HELLO 3` and falls back to RESP2 only on the replies Redis itself gives; a proxy or
|
|
14
|
+
// managed service that answers `HELLO` some other way would fail the connection, and
|
|
15
|
+
// the site would quietly run on memory. Nothing here needs RESP3.
|
|
16
|
+
export const REDIS_PROTOCOL = 2 as const
|
|
17
|
+
|
|
11
18
|
export async function createRedisStore(cfg: CmsStoreConfig): Promise<SharedStore | null> {
|
|
12
19
|
if (!cfg.redisUrl) return null
|
|
13
20
|
const { default: Redis } = await import('ioredis')
|
|
14
21
|
const prefix = cfg.prefix || 'cms'
|
|
15
22
|
const client = new Redis(cfg.redisUrl, {
|
|
23
|
+
protocol: REDIS_PROTOCOL,
|
|
16
24
|
maxRetriesPerRequest: 1,
|
|
17
25
|
enableOfflineQueue: false,
|
|
18
26
|
commandTimeout: 500,
|
|
@@ -57,7 +65,7 @@ export async function createRedisStore(cfg: CmsStoreConfig): Promise<SharedStore
|
|
|
57
65
|
},
|
|
58
66
|
async subscribe(channel, handler) {
|
|
59
67
|
if (!subscriber) {
|
|
60
|
-
subscriber = new Redis(cfg.redisUrl, { maxRetriesPerRequest: null, enableOfflineQueue: true, connectTimeout: 2_000 })
|
|
68
|
+
subscriber = new Redis(cfg.redisUrl, { protocol: REDIS_PROTOCOL, maxRetriesPerRequest: null, enableOfflineQueue: true, connectTimeout: 2_000 })
|
|
61
69
|
subscriber.on('error', (err) => console.error('[cms] redis subscriber', err.message))
|
|
62
70
|
subscriber.on('message', (ch: string, msg: string) => {
|
|
63
71
|
for (const h of handlers.get(ch) ?? []) h(msg)
|
package/server/utils/cmsAudit.ts
CHANGED
|
@@ -3,10 +3,18 @@
|
|
|
3
3
|
* never fails the request that triggered it.
|
|
4
4
|
*
|
|
5
5
|
* Actions: auth.setup, auth.setup_failed, auth.login, auth.login_failed, auth.logout, auth.reset_request,
|
|
6
|
-
* auth.reset, auth.invite_accept, account.update, account.password,
|
|
7
|
-
*
|
|
6
|
+
* auth.reset, auth.invite_accept, account.update, account.password, account.email_request,
|
|
7
|
+
* account.email_failed, account.email_cancel, account.email, account.email_revert, user.invite, user.resend,
|
|
8
|
+
* user.role, user.email, user.disable, user.enable, user.delete, entry.create,
|
|
8
9
|
* entry.update, entry.delete, entry.publish, entry.unpublish, settings.update,
|
|
9
10
|
* media.upload, media.delete, retention.purge, privacy.export, privacy.delete.
|
|
11
|
+
*
|
|
12
|
+
* A change of sign-in email names the new address as `meta.email` and the old one as
|
|
13
|
+
* `meta.previousEmail` (`account.email_request`: asked for, by the person; `account.email`:
|
|
14
|
+
* made, when the link was opened; `account.email_revert`: undone from the old mailbox, `email`
|
|
15
|
+
* being the address restored; `user.email`: made by an administrator, on the person's id).
|
|
16
|
+
* `account.email_failed` is a wrong password when asking for a change (yours, or an
|
|
17
|
+
* administrator's own for someone else's). The privacy tools find and erase both (cmsPrivacy.ts).
|
|
10
18
|
*/
|
|
11
19
|
export async function audit(
|
|
12
20
|
event: any,
|
package/server/utils/cmsAuth.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { z } from 'zod'
|
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Built-in accounts: sessions (sealed cookie via nuxt-auth-utils), one-time links
|
|
7
|
-
* for invites and
|
|
7
|
+
* for invites, password resets and email changes, and the helpers the auth and team endpoints share.
|
|
8
8
|
*
|
|
9
9
|
* Password hashing is nuxt-auth-utils' scrypt.
|
|
10
10
|
*/
|
|
@@ -31,6 +31,15 @@ export const emailSchema = z.string().trim().toLowerCase().pipe(z.email())
|
|
|
31
31
|
const toBase64Url = (bytes: Uint8Array) =>
|
|
32
32
|
btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
33
33
|
|
|
34
|
+
/** A new one-time link secret: 32 random bytes, base64url. */
|
|
35
|
+
export const newLinkSecret = () => toBase64Url(crypto.getRandomValues(new Uint8Array(32)))
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* What a one-time link is for: an invitation, a password reset, confirming a new email
|
|
39
|
+
* address, or undoing a change of address (sent to the old one).
|
|
40
|
+
*/
|
|
41
|
+
export type CmsTokenKind = 'invite' | 'reset' | 'email' | 'email-revert'
|
|
42
|
+
|
|
34
43
|
export async function sha256Hex(text: string): Promise<string> {
|
|
35
44
|
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
|
|
36
45
|
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
@@ -38,13 +47,15 @@ export async function sha256Hex(text: string): Promise<string> {
|
|
|
38
47
|
|
|
39
48
|
export const INVITE_TTL_MS = 7 * 24 * 60 * 60 * 1000
|
|
40
49
|
export const RESET_TTL_MS = 60 * 60 * 1000
|
|
50
|
+
export const EMAIL_CHANGE_TTL_MS = 24 * 60 * 60 * 1000
|
|
51
|
+
export const EMAIL_REVERT_TTL_MS = 7 * 24 * 60 * 60 * 1000
|
|
41
52
|
|
|
42
53
|
/**
|
|
43
54
|
* Create a one-time link secret for a user. Earlier unused links of the same kind
|
|
44
55
|
* stop working (a resent invite replaces the old one). Only the hash is stored.
|
|
45
56
|
*/
|
|
46
|
-
export async function issueToken(db: any, reg: CmsRegistry, opts: { userId: string; kind:
|
|
47
|
-
const secret =
|
|
57
|
+
export async function issueToken(db: any, reg: CmsRegistry, opts: { userId: string; kind: CmsTokenKind; ttlMs: number; createdBy?: string | null }): Promise<string> {
|
|
58
|
+
const secret = newLinkSecret()
|
|
48
59
|
const t = reg.cmsTokens
|
|
49
60
|
await db.transaction(async (tx: any) => {
|
|
50
61
|
await tx.update(t).set({ usedAt: new Date() })
|
|
@@ -61,7 +72,7 @@ export async function issueToken(db: any, reg: CmsRegistry, opts: { userId: stri
|
|
|
61
72
|
}
|
|
62
73
|
|
|
63
74
|
/** The valid (unused, unexpired) token row for a secret, with its user — or null. */
|
|
64
|
-
export async function findToken(db: any, reg: CmsRegistry, secret: string, kind:
|
|
75
|
+
export async function findToken(db: any, reg: CmsRegistry, secret: string, kind: CmsTokenKind) {
|
|
65
76
|
if (!secret || secret.length > 200) return null
|
|
66
77
|
const t = reg.cmsTokens
|
|
67
78
|
const [row] = await db.select().from(t).where(and(
|