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
|
@@ -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
|
|
|
@@ -38,4 +38,6 @@ export default defineEventHandler(async (event) => {
|
|
|
38
38
|
// The version this request was authorised with; writes that re-sign the session
|
|
39
39
|
// must not upgrade a session past a concurrent password change (see me.patch).
|
|
40
40
|
event.context.cmsSessionVersion = u.sessionVersion
|
|
41
|
+
// When this browser signed in: a session written again keeps it (continueCmsSession).
|
|
42
|
+
event.context.cmsSignedInAt = session.cms.iat
|
|
41
43
|
})
|
|
@@ -1,11 +1,16 @@
|
|
|
1
|
+
import { cmsDeprecated } from 'tinyzoo'
|
|
2
|
+
|
|
1
3
|
// Check the settings a production server cannot work without, when it starts: the platform
|
|
2
4
|
// then shows a start that failed with the variable's name, instead of a server that
|
|
3
5
|
// answers "ready" and fails the first sign-in (or the first request) with a bare 500.
|
|
4
|
-
// -
|
|
6
|
+
// - NUXT_APP_SECRET: at least 32 characters (nuxt-auth-utils seals the session cookie with
|
|
7
|
+
// a key derived from it). Until 0.5, NUXT_SESSION_PASSWORD (or nuxt.config's
|
|
8
|
+
// runtimeConfig.session.password) stands in for it when it is not set (src/appSecret.ts),
|
|
9
|
+
// with a deprecation warning;
|
|
5
10
|
// - a database address: NUXT_CMS_DATABASE_URL or DATABASE_URL;
|
|
6
11
|
// - NUXT_CMS_PUBLIC_URL: not fatal, but the sitemap and the links in emails need it — one warning.
|
|
7
|
-
// Development keeps its defaults (
|
|
8
|
-
//
|
|
12
|
+
// Development keeps its defaults (Nuxt generates an app secret, the dev database is in
|
|
13
|
+
// .env); a prerender during the build has no runtime settings either.
|
|
9
14
|
export default defineNitroPlugin(() => {
|
|
10
15
|
if (process.env.NODE_ENV !== 'production' || import.meta.prerender) return
|
|
11
16
|
const config = useRuntimeConfig()
|
|
@@ -13,10 +18,30 @@ export default defineNitroPlugin(() => {
|
|
|
13
18
|
|
|
14
19
|
const problems: string[] = []
|
|
15
20
|
if (cmsAuthMode() === 'builtin') {
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
21
|
+
const secret = (config as any).appSecret
|
|
22
|
+
// The variable Nitro read the app secret from: NITRO_APP_SECRET when it is there (even
|
|
23
|
+
// empty), otherwise the site's prefix (NUXT_, or nitro.envPrefix).
|
|
24
|
+
const prefix = String((config as any).nitro?.envPrefix || 'NUXT_')
|
|
25
|
+
const secretVar = process.env.NITRO_APP_SECRET !== undefined ? 'NITRO_APP_SECRET' : `${prefix}APP_SECRET`
|
|
26
|
+
// What stood in for it (src/appSecret.ts): NUXT_SESSION_PASSWORD, or nuxt.config's runtimeConfig.session.password.
|
|
27
|
+
const from = (globalThis as any)[Symbol.for('tinyzoo.appSecretFrom')] as string | undefined
|
|
28
|
+
const name = from ? `${from} (used because ${secretVar} is not set)` : secretVar
|
|
29
|
+
if (secret !== undefined && secret !== null && secret !== '' && typeof secret !== 'string') {
|
|
30
|
+
const kind = Array.isArray(secret) ? 'a list' : typeof secret === 'object' ? 'an object' : `a ${typeof secret}`
|
|
31
|
+
problems.push(`${name} was read as ${kind}, not as text (the environment is parsed as JSON where it can be). `
|
|
32
|
+
+ 'Make one with: openssl rand -base64 32')
|
|
33
|
+
}
|
|
34
|
+
else if (String(secret ?? '').length < 32) {
|
|
35
|
+
problems.push(`${name} is ${secret ? 'only ' + String(secret).length + ' characters long' : 'not set'}; it must be at least 32 characters `
|
|
36
|
+
+ '(the sign-in cookie is sealed with a key derived from it). Make one with: openssl rand -base64 32')
|
|
37
|
+
}
|
|
38
|
+
else if (from) {
|
|
39
|
+
const move = from === 'runtimeConfig.session.password'
|
|
40
|
+
? `Move the value to ${prefix}APP_SECRET in the environment and remove it from nuxt.config`
|
|
41
|
+
: `Rename the variable to ${prefix}APP_SECRET`
|
|
42
|
+
cmsDeprecated('env:NUXT_SESSION_PASSWORD', `${from} is used as the app secret because ${secretVar} is not set: nuxt-auth-utils 0.6 `
|
|
43
|
+
+ `no longer reads it. ${move}; with the same value nobody is signed out again. Until then, nuxt-auth-utils' own warning `
|
|
44
|
+
+ 'that it "is not used anymore" can be ignored: tinyzoo uses it.', { removeIn: '0.5.0' })
|
|
20
45
|
}
|
|
21
46
|
}
|
|
22
47
|
if (!(process.env.NUXT_CMS_DATABASE_URL || process.env.DATABASE_URL || cms.databaseUrl)) {
|
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(
|
|
@@ -79,9 +90,34 @@ export function sessionUser(u: any) {
|
|
|
79
90
|
return { id: u.id as string, email: u.email as string, name: (u.name as string) || u.email, role: u.role as string, locale: (u.locale as string | null) ?? null }
|
|
80
91
|
}
|
|
81
92
|
|
|
82
|
-
/**
|
|
93
|
+
/**
|
|
94
|
+
* Sign the person in on this browser (replaces any previous session). The session keeps the
|
|
95
|
+
* time of the sign-in (`cms.iat`, ms): it ends `runtimeConfig.session.maxAge` after it
|
|
96
|
+
* (activeAccountOf), however often it is written again since. nuxt-auth-utils 0.6 only
|
|
97
|
+
* counts its own age from the last write, so without this a stolen cookie that keeps
|
|
98
|
+
* changing something (a name, the language) would never end.
|
|
99
|
+
*/
|
|
83
100
|
export async function startCmsSession(event: any, u: any): Promise<void> {
|
|
84
|
-
await
|
|
101
|
+
await sealCmsSession(event, u, Date.now())
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Write the session of the person already signed in on this browser again (a changed name,
|
|
106
|
+
* language, password or email), keeping the time they signed in: no later than `maxAge`
|
|
107
|
+
* after that, they sign in again. Without that time (not signed in on this request) nothing
|
|
108
|
+
* is written: 401.
|
|
109
|
+
*/
|
|
110
|
+
export async function continueCmsSession(event: any, u: any): Promise<void> {
|
|
111
|
+
const signedInAt = event.context?.cmsSignedInAt
|
|
112
|
+
if (typeof signedInAt !== 'number' || event.context?.cmsUser?.id !== u.id) {
|
|
113
|
+
await clearUserSession(event)
|
|
114
|
+
throw createError({ statusCode: 401, statusMessage: 'Authentication required' })
|
|
115
|
+
}
|
|
116
|
+
await sealCmsSession(event, u, signedInAt)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function sealCmsSession(event: any, u: any, iat: number): Promise<void> {
|
|
120
|
+
await replaceUserSession(event, { user: sessionUser(u), cms: { uid: u.id as string, sv: u.sessionVersion as number, iat } } as any)
|
|
85
121
|
}
|
|
86
122
|
|
|
87
123
|
// ── links in emails ────────────────────────────────────────────────────────────
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { and, eq, inArray, sql } from 'tinyzoo'
|
|
2
2
|
import { Hocuspocus } from '@hocuspocus/server'
|
|
3
3
|
import * as Y from 'yjs'
|
|
4
|
+
import { REDIS_PROTOCOL } from '../store/redis'
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* The shared-editing engine (Hocuspocus), on the app's own port: it opens no server
|
|
@@ -27,6 +28,8 @@ interface CollabContext {
|
|
|
27
28
|
/** The one Yjs client this connection may speak for in cursor (awareness) updates. */
|
|
28
29
|
clientId?: number
|
|
29
30
|
sv: number
|
|
31
|
+
/** When the session this socket was admitted with was signed in (it ends with that session). */
|
|
32
|
+
iat: number
|
|
30
33
|
epoch: string
|
|
31
34
|
access: 'write' | 'read'
|
|
32
35
|
checkedAt: number
|
|
@@ -64,7 +67,7 @@ interface Presence {
|
|
|
64
67
|
async function createPresence(redisUrl: string, prefix: string): Promise<Presence> {
|
|
65
68
|
const { default: IORedis } = await import('ioredis')
|
|
66
69
|
// Like the shared store: never wait on a Redis that is down (callers fall back to the 90 s window).
|
|
67
|
-
const redis = new IORedis(redisUrl, { maxRetriesPerRequest: 1, enableOfflineQueue: false, commandTimeout: 500, connectTimeout: 2_000 })
|
|
70
|
+
const redis = new IORedis(redisUrl, { protocol: REDIS_PROTOCOL, maxRetriesPerRequest: 1, enableOfflineQueue: false, commandTimeout: 500, connectTimeout: 2_000 })
|
|
68
71
|
redis.on('error', (err) => console.error('[cms] collab presence', err.message))
|
|
69
72
|
const key = (name: string) => `${prefix}:presence:${name}`
|
|
70
73
|
return {
|
|
@@ -75,7 +78,7 @@ async function createPresence(redisUrl: string, prefix: string): Promise<Presenc
|
|
|
75
78
|
await redis.zrem(key(name), REPLICA_ID)
|
|
76
79
|
},
|
|
77
80
|
async othersHere(name) {
|
|
78
|
-
const res = await redis.multi().zremrangebyscore(key(name), '-inf', Date.now()).zrange(key(name), 0, -1).exec()
|
|
81
|
+
const res = await redis.multi().zremrangebyscore(key(name), '-inf', Date.now()).zrange(key(name), 0, '-1').exec()
|
|
79
82
|
const [err, members] = res?.[1] ?? [new Error('empty transaction result'), null]
|
|
80
83
|
if (err || !Array.isArray(members)) throw err ?? new Error('presence list missing')
|
|
81
84
|
return members.some((m) => m !== REPLICA_ID)
|
|
@@ -92,6 +95,8 @@ let instance: Hocuspocus | null = null
|
|
|
92
95
|
let starting: Promise<Hocuspocus> | null = null
|
|
93
96
|
let heartbeat: ReturnType<typeof setInterval> | null = null
|
|
94
97
|
let lastPurge = 0
|
|
98
|
+
/** The heartbeat while it runs: a document's last tab waits for it before marking the document idle. */
|
|
99
|
+
let beating: Promise<void> | null = null
|
|
95
100
|
/** The epoch each loaded document belongs to (what it may store into). */
|
|
96
101
|
const loadedEpoch = new Map<string, string>()
|
|
97
102
|
/** Documents opened on each socket. */
|
|
@@ -115,7 +120,7 @@ function dropSocket(ws: any, code = 4401, reason = 'Not permitted') {
|
|
|
115
120
|
|
|
116
121
|
/** Is this account still allowed this document, and with which access? */
|
|
117
122
|
async function recheck(ctx: CollabContext): Promise<'write' | 'read' | null> {
|
|
118
|
-
const u = await
|
|
123
|
+
const u = await activeAccount(ctx.user.id, ctx.sv, ctx.iat)
|
|
119
124
|
if (!u || u.role !== ctx.user.role) return null
|
|
120
125
|
const target = parseCollabName(collabName(ctx.target.entityName, ctx.target.id, ctx.target.locale))
|
|
121
126
|
return target ? collabAccess({ ...ctx.user, role: u.role }, target) : null
|
|
@@ -195,7 +200,7 @@ async function startCollabServer(): Promise<Hocuspocus> {
|
|
|
195
200
|
const redisUrl = String((useRuntimeConfig().cms as any)?.redis?.url || process.env.REDIS_URL || '')
|
|
196
201
|
if (redisUrl) {
|
|
197
202
|
const [{ Redis: RedisExtension }, { default: IORedis }] = await Promise.all([import('@hocuspocus/extension-redis'), import('ioredis')])
|
|
198
|
-
extensions.push(new RedisExtension({ createClient: () => new IORedis(redisUrl, { maxRetriesPerRequest: null }) as any, prefix: `${cmsStorePrefix()}:collab` } as any))
|
|
203
|
+
extensions.push(new RedisExtension({ createClient: () => new IORedis(redisUrl, { protocol: REDIS_PROTOCOL, maxRetriesPerRequest: null }) as any, prefix: `${cmsStorePrefix()}:collab` } as any))
|
|
199
204
|
}
|
|
200
205
|
|
|
201
206
|
// "Nobody has it open" is known the moment the last tab leaves: with one instance
|
|
@@ -233,7 +238,7 @@ async function startCollabServer(): Promise<Hocuspocus> {
|
|
|
233
238
|
// Only the canonical spelling of a name.
|
|
234
239
|
if (!target || target.name !== documentName) throw new Error('Unknown document')
|
|
235
240
|
// The account as it is now (disabled, demoted, signed out everywhere?).
|
|
236
|
-
const u = await
|
|
241
|
+
const u = await activeAccount(socketUser.id, context.sv, context.iat)
|
|
237
242
|
if (!u) throw new Error('Session no longer valid')
|
|
238
243
|
const user: CmsUser = { ...socketUser, role: u.role, name: u.name || socketUser.name }
|
|
239
244
|
const access = await collabAccess(user, target)
|
|
@@ -262,7 +267,7 @@ async function startCollabServer(): Promise<Hocuspocus> {
|
|
|
262
267
|
docs.add(documentName)
|
|
263
268
|
docsBySocket.set(socketId, docs)
|
|
264
269
|
if (access === 'read') connectionConfig.readOnly = true
|
|
265
|
-
return { user, displayName: displayName(u.name, u.email), sv: context.sv, epoch: row.epoch, access, checkedAt: Date.now(), target: { entityName: target.entity.name, id: target.id, locale: target.locale } } satisfies CollabContext
|
|
270
|
+
return { user, displayName: displayName(u.name, u.email), sv: context.sv, iat: context.iat, epoch: row.epoch, access, checkedAt: Date.now(), target: { entityName: target.entity.name, id: target.id, locale: target.locale } } satisfies CollabContext
|
|
266
271
|
},
|
|
267
272
|
|
|
268
273
|
async onLoadDocument({ documentName, document, context }) {
|
|
@@ -277,7 +282,7 @@ async function startCollabServer(): Promise<Hocuspocus> {
|
|
|
277
282
|
return document
|
|
278
283
|
},
|
|
279
284
|
|
|
280
|
-
async onStoreDocument({ documentName, document,
|
|
285
|
+
async onStoreDocument({ documentName, document, lastContext }) {
|
|
281
286
|
const epoch = loadedEpoch.get(documentName)
|
|
282
287
|
if (!epoch) return
|
|
283
288
|
const state = encodeState(document)
|
|
@@ -294,8 +299,9 @@ async function startCollabServer(): Promise<Hocuspocus> {
|
|
|
294
299
|
const active = await occupied(document)
|
|
295
300
|
const stored: any[] = await db.update(c).set({ state, updatedAt: sql`now()`, activeAt: active ? sql`now()` : null })
|
|
296
301
|
.where(and(eq(c.name, documentName), eq(c.epoch, epoch))).returning({ name: c.name })
|
|
297
|
-
// Who typed last: shown with text that is left behind unsaved.
|
|
298
|
-
|
|
302
|
+
// Who typed last: shown with text that is left behind unsaved. (The context of the
|
|
303
|
+
// connection behind the last change; empty for one that came from another replica.)
|
|
304
|
+
const typist = (lastContext as CollabContext | undefined)?.displayName
|
|
299
305
|
if (stored.length && typist) await noteCollabEditor(documentName, typist).catch(() => {})
|
|
300
306
|
if (!stored.length) {
|
|
301
307
|
// Restarted (or deleted) meanwhile: what is loaded here is an old history.
|
|
@@ -318,6 +324,9 @@ async function startCollabServer(): Promise<Hocuspocus> {
|
|
|
318
324
|
if (docs && !docs.size) docsBySocket.delete(socketId)
|
|
319
325
|
// The last one left: nobody has it open now (not for another minute and a half).
|
|
320
326
|
if (clientsCount === 0) {
|
|
327
|
+
// A heartbeat that counted this tab as a writer may still be writing "being edited":
|
|
328
|
+
// let it finish first, or it would land after "idle" and stay there.
|
|
329
|
+
await beating?.catch(() => {})
|
|
321
330
|
if (redisPresence) {
|
|
322
331
|
// Leave the list first: of two replicas losing their last tab at once, the later one sees it empty.
|
|
323
332
|
await redisPresence.left(documentName).catch(() => {})
|
|
@@ -360,7 +369,10 @@ async function startCollabServer(): Promise<Hocuspocus> {
|
|
|
360
369
|
})
|
|
361
370
|
instance = server
|
|
362
371
|
|
|
363
|
-
heartbeat ??= setInterval(() => {
|
|
372
|
+
heartbeat ??= setInterval(() => {
|
|
373
|
+
if (beating) return
|
|
374
|
+
beating = beat().finally(() => { beating = null })
|
|
375
|
+
}, cmsTimerMs('CMS_TEST_COLLAB_HEARTBEAT_MS', HEARTBEAT_MS))
|
|
364
376
|
;(heartbeat as any).unref?.()
|
|
365
377
|
return server
|
|
366
378
|
}
|
|
@@ -398,7 +410,10 @@ async function beat() {
|
|
|
398
410
|
if (presence && doc.getConnectionsCount() > 0) await presence.here(doc.name).catch(() => {})
|
|
399
411
|
}
|
|
400
412
|
try {
|
|
401
|
-
|
|
413
|
+
// Only documents that still have a writer now: the re-checks above wait on the database,
|
|
414
|
+
// and a last tab that left meanwhile has marked its document idle.
|
|
415
|
+
const stillEditing = editing.filter((name) => [...(server.documents.get(name)?.getConnections() ?? [])].some((c: any) => !c.readOnly))
|
|
416
|
+
if (stillEditing.length) await db.update(reg.cmsCollab).set({ activeAt: sql`now()` }).where(inArray(reg.cmsCollab.name, stillEditing))
|
|
402
417
|
if (Date.now() - lastPurge > 60 * 60_000) {
|
|
403
418
|
lastPurge = Date.now()
|
|
404
419
|
await db.delete(reg.cmsCollab).where(sql`${reg.cmsCollab.updatedAt} < now() - interval '30 days' and (${reg.cmsCollab.activeAt} is null or ${reg.cmsCollab.activeAt} < now() - interval '1 day')`)
|
|
@@ -445,7 +460,7 @@ export async function stopCollabServer(): Promise<void> {
|
|
|
445
460
|
}
|
|
446
461
|
server.closeConnections()
|
|
447
462
|
// Store what is still pending, then let extensions (Redis) close their clients.
|
|
448
|
-
await Promise.allSettled([...server.documents.values()].map((d) => server.storeDocumentHooks(d, { clientsCount: 0,
|
|
463
|
+
await Promise.allSettled([...server.documents.values()].map((d) => server.storeDocumentHooks(d, { clientsCount: 0, lastContext: {}, lastTransactionOrigin: null, document: d, documentName: d.name, instance: server }, true)))
|
|
449
464
|
await Promise.resolve(server.hooks('onDestroy', { instance: server } as any)).catch(() => {})
|
|
450
465
|
await p?.close()
|
|
451
466
|
}
|