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
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { and, eq, gte, inArray, isNull, ne, sql } from 'tinyzoo'
|
|
2
|
+
import type { CmsRegistry } from 'tinyzoo'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Changing an account's email address (the database side; the rules are in
|
|
6
|
+
* cmsEmailChangeRules.ts).
|
|
7
|
+
*
|
|
8
|
+
* A person asks with their password; a one-time link (cms_tokens, kind 'email', only
|
|
9
|
+
* its hash stored, 24 hours) goes to the new address, and the address it is for waits
|
|
10
|
+
* in cms_state under `email-change:<userId>` — with the token's id, so only the newest
|
|
11
|
+
* link counts, and the account's session version, so a password change cancels it.
|
|
12
|
+
* Kept in cms_state rather than a new column so that sites need no migration for it;
|
|
13
|
+
* there is at most one row per account, removed when the change is made or cancelled,
|
|
14
|
+
* when it is found dead on reading, when the account is removed or erased, by the daily
|
|
15
|
+
* retention run once expired, and replaced by the next request.
|
|
16
|
+
*
|
|
17
|
+
* Once a change is made, the notice to the old address carries a way back: a one-time
|
|
18
|
+
* link (kind 'email-revert', 7 days) with the old address waiting in cms_state under
|
|
19
|
+
* `email-revert:<userId>:<tokenId>`. Whoever still reads the old mailbox can restore it
|
|
20
|
+
* and choose a new password (POST /api/cms/_auth/email/revert): the answer to someone who
|
|
21
|
+
* knew the password and confirmed a change to their own address at once.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Lock the account's row for the rest of the transaction. The routes that claim a link
|
|
26
|
+
* and then end the account's other links (confirm, revert) take it first, so two of
|
|
27
|
+
* them at once wait for each other instead of deadlocking on each other's links.
|
|
28
|
+
*/
|
|
29
|
+
export async function lockUser(tx: any, reg: CmsRegistry, userId: string): Promise<void> {
|
|
30
|
+
await tx.select({ id: reg.cmsUsers.id }).from(reg.cmsUsers).where(eq(reg.cmsUsers.id, userId)).for('update')
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Ask for a change: a new link (earlier email links stop working) and the address it is for. Returns the link's secret. */
|
|
34
|
+
export async function startEmailChange(db: any, reg: CmsRegistry, opts: { userId: string; email: string; sessionVersion: number }): Promise<string> {
|
|
35
|
+
const secret = newLinkSecret()
|
|
36
|
+
const t = reg.cmsTokens
|
|
37
|
+
const s = reg.cmsState
|
|
38
|
+
const expiresAt = new Date(Date.now() + EMAIL_CHANGE_TTL_MS)
|
|
39
|
+
await db.transaction(async (tx: any) => {
|
|
40
|
+
await tx.update(t).set({ usedAt: new Date() }).where(and(eq(t.userId, opts.userId), eq(t.kind, 'email'), isNull(t.usedAt)))
|
|
41
|
+
const [row] = await tx.insert(t).values({
|
|
42
|
+
userId: opts.userId, kind: 'email', tokenHash: await sha256Hex(secret), expiresAt, createdBy: opts.userId,
|
|
43
|
+
}).returning({ id: t.id })
|
|
44
|
+
const value: PendingEmailChange = { tokenId: row.id, email: opts.email, sv: opts.sessionVersion, expiresAt: expiresAt.toISOString() }
|
|
45
|
+
await tx.insert(s).values({ key: emailChangeStateKey(opts.userId), value })
|
|
46
|
+
.onConflictDoUpdate({ target: s.key, set: { value, updatedAt: sql`now()` } })
|
|
47
|
+
})
|
|
48
|
+
return secret
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The change an account is waiting for, if any (whether or not its link still works: see emailChangeUsable). */
|
|
52
|
+
export async function readEmailChange(db: any, reg: CmsRegistry, userId: string): Promise<PendingEmailChange | null> {
|
|
53
|
+
const [row] = await db.select().from(reg.cmsState).where(eq(reg.cmsState.key, emailChangeStateKey(userId)))
|
|
54
|
+
return asPendingEmailChange(row?.value)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The change an account is waiting for, if it can still happen. One that can't (its link
|
|
59
|
+
* used, replaced or expired, the password changed since) is deleted on the way: nothing
|
|
60
|
+
* else would ever read it again.
|
|
61
|
+
*/
|
|
62
|
+
export async function readLiveEmailChange(db: any, reg: CmsRegistry, userId: string): Promise<PendingEmailChange | null> {
|
|
63
|
+
const pending = await readEmailChange(db, reg, userId)
|
|
64
|
+
if (!pending) return null
|
|
65
|
+
const [token] = await db.select().from(reg.cmsTokens).where(eq(reg.cmsTokens.id, pending.tokenId))
|
|
66
|
+
const [user] = await db.select().from(reg.cmsUsers).where(eq(reg.cmsUsers.id, userId))
|
|
67
|
+
if (!emailChangeDead(pending, token, user)) return pending
|
|
68
|
+
await forgetEmailChange(db, reg, userId, pending.tokenId)
|
|
69
|
+
return null
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Delete an account's pending change — only the one for `tokenId` when given, so a
|
|
74
|
+
* request that replaced it in the meantime stays.
|
|
75
|
+
*/
|
|
76
|
+
export async function forgetEmailChange(db: any, reg: CmsRegistry, userId: string, tokenId?: string): Promise<void> {
|
|
77
|
+
const s = reg.cmsState
|
|
78
|
+
const key = eq(s.key, emailChangeStateKey(userId))
|
|
79
|
+
await db.delete(s).where(tokenId ? and(key, sql`${s.value}->>'tokenId' = ${tokenId}`) : key)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* After the address changed (or to cancel a change): links already sent stop working —
|
|
84
|
+
* password resets and email changes always (a reset link in the old mailbox would
|
|
85
|
+
* otherwise still open the account), `invite` too when asked — and the pending change
|
|
86
|
+
* is forgotten. The ways back (`email-revert`) are not touched here: they belong to the
|
|
87
|
+
* old mailboxes, see endRevertLinks.
|
|
88
|
+
*/
|
|
89
|
+
export async function endLinksOf(db: any, reg: CmsRegistry, userId: string, kinds: CmsTokenKind[] = ['reset', 'email']): Promise<void> {
|
|
90
|
+
const t = reg.cmsTokens
|
|
91
|
+
await db.update(t).set({ usedAt: new Date() }).where(and(eq(t.userId, userId), inArray(t.kind, kinds), isNull(t.usedAt)))
|
|
92
|
+
await forgetEmailChange(db, reg, userId)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Can't this account take the address? Another account has it (invited, active or
|
|
97
|
+
* disabled alike), or it is the public demo account's (whoever signs in with the demo's
|
|
98
|
+
* published details would get the account). The unique index on cms_users.email is
|
|
99
|
+
* the backstop for two changes to the same address at the same moment.
|
|
100
|
+
*/
|
|
101
|
+
export async function emailTaken(db: any, reg: CmsRegistry, email: string, exceptUserId: string): Promise<boolean> {
|
|
102
|
+
if (isDemoAccount(email)) return true
|
|
103
|
+
const u = reg.cmsUsers
|
|
104
|
+
const [row] = await db.select({ id: u.id }).from(u).where(and(eq(u.email, email), ne(u.id, exceptUserId)))
|
|
105
|
+
return !!row || await emailReserved(db, reg, email, exceptUserId)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Is the address held for another account's way back? While a link that undoes a change
|
|
110
|
+
* still works, the old address stays reserved for that account: nobody can be invited
|
|
111
|
+
* with it or move to it. Otherwise someone who changed the address with the password
|
|
112
|
+
* alone could block the owner's way back by giving the old address to another account
|
|
113
|
+
* (an administrator's session can invite one).
|
|
114
|
+
*/
|
|
115
|
+
export async function emailReserved(db: any, reg: CmsRegistry, email: string, exceptUserId?: string): Promise<boolean> {
|
|
116
|
+
const s = reg.cmsState
|
|
117
|
+
const rows: { key: string }[] = await db.select({ key: s.key }).from(s).where(and(
|
|
118
|
+
sql`${s.key} like ${`${EMAIL_REVERT_STATE_PREFIX}%`}`,
|
|
119
|
+
sql`lower(btrim(${s.value}->>'email')) = ${email}`,
|
|
120
|
+
// expiresAt is always an ISO string written by toISOString(), so text comparison is time order.
|
|
121
|
+
sql`coalesce(${s.value}->>'expiresAt', '') > ${new Date().toISOString()}`,
|
|
122
|
+
))
|
|
123
|
+
return rows.some((r) => !exceptUserId || !r.key.startsWith(`${EMAIL_REVERT_STATE_PREFIX}${exceptUserId}:`))
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ── the way back ───────────────────────────────────────────────────────────────
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* A link that undoes a change just made, for the notice to the old address. Unlike other
|
|
130
|
+
* links, earlier ones of the same kind keep working: after A → B → C the oldest mailbox
|
|
131
|
+
* (A, the owner's if anyone's) must still be able to take the account back.
|
|
132
|
+
*/
|
|
133
|
+
export async function issueEmailRevert(db: any, reg: CmsRegistry, opts: { userId: string; email: string; createdBy?: string | null }): Promise<string> {
|
|
134
|
+
const secret = newLinkSecret()
|
|
135
|
+
const t = reg.cmsTokens
|
|
136
|
+
const expiresAt = new Date(Date.now() + EMAIL_REVERT_TTL_MS)
|
|
137
|
+
const [row] = await db.insert(t).values({
|
|
138
|
+
userId: opts.userId, kind: 'email-revert', tokenHash: await sha256Hex(secret), expiresAt, createdBy: opts.createdBy ?? null,
|
|
139
|
+
}).returning({ id: t.id })
|
|
140
|
+
const value: EmailRevert = { email: opts.email, expiresAt: expiresAt.toISOString() }
|
|
141
|
+
await db.insert(reg.cmsState).values({ key: emailRevertStateKey(opts.userId, row.id), value })
|
|
142
|
+
return secret
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** The address a way-back link restores, or null when it has none (any more). */
|
|
146
|
+
export async function readEmailRevert(db: any, reg: CmsRegistry, userId: string, tokenId: string): Promise<EmailRevert | null> {
|
|
147
|
+
const [row] = await db.select().from(reg.cmsState).where(eq(reg.cmsState.key, emailRevertStateKey(userId, tokenId)))
|
|
148
|
+
const revert = asEmailRevert(row?.value)
|
|
149
|
+
return revert && new Date(revert.expiresAt).getTime() > Date.now() ? revert : null
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Ways back stop working: all of an account's (`since` omitted), or those issued at or
|
|
154
|
+
* after `since` — when one is used, the links of later changes go (they would undo the
|
|
155
|
+
* restore), while older ones stay valid (they lead further back, to an earlier owner).
|
|
156
|
+
*/
|
|
157
|
+
export async function endRevertLinks(db: any, reg: CmsRegistry, userId: string, since?: Date): Promise<void> {
|
|
158
|
+
const t = reg.cmsTokens
|
|
159
|
+
// A link already used keeps the time it was used; its row in cms_state goes all the same.
|
|
160
|
+
const ended: { id: string }[] = await db.update(t).set({ usedAt: sql`coalesce(${t.usedAt}, now())` })
|
|
161
|
+
.where(and(eq(t.userId, userId), eq(t.kind, 'email-revert'), since ? gte(t.createdAt, since) : undefined))
|
|
162
|
+
.returning({ id: t.id })
|
|
163
|
+
const s = reg.cmsState
|
|
164
|
+
if (!since) await db.delete(s).where(sql`${s.key} like ${emailRevertStatePattern(userId)}`)
|
|
165
|
+
else if (ended.length) await db.delete(s).where(inArray(s.key, ended.map((r) => emailRevertStateKey(userId, r.id))))
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ── privacy and housekeeping ───────────────────────────────────────────────────
|
|
169
|
+
|
|
170
|
+
const emailStateKeys = (s: CmsRegistry['cmsState']) =>
|
|
171
|
+
sql`(${s.key} like ${`${EMAIL_CHANGE_STATE_PREFIX}%`} or ${s.key} like ${`${EMAIL_REVERT_STATE_PREFIX}%`})`
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The pending changes and ways back that name an address (privacy lookup, export and
|
|
175
|
+
* erasure): a change waiting for it, or a way back that would restore it.
|
|
176
|
+
*/
|
|
177
|
+
export async function findEmailStates(db: any, reg: CmsRegistry, email: string): Promise<{ key: string; kind: 'change' | 'revert'; userId: string; expiresAt: string | null }[]> {
|
|
178
|
+
const s = reg.cmsState
|
|
179
|
+
const rows: any[] = await db.select().from(s).where(and(emailStateKeys(s), sql`lower(btrim(${s.value}->>'email')) = ${email}`))
|
|
180
|
+
return rows.map((r) => {
|
|
181
|
+
const change = r.key.startsWith(EMAIL_CHANGE_STATE_PREFIX)
|
|
182
|
+
const rest = r.key.slice((change ? EMAIL_CHANGE_STATE_PREFIX : EMAIL_REVERT_STATE_PREFIX).length)
|
|
183
|
+
return { key: r.key, kind: change ? 'change' : 'revert', userId: rest.split(':')[0]!, expiresAt: typeof r.value?.expiresAt === 'string' ? r.value.expiresAt : null }
|
|
184
|
+
})
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Delete expired pending changes and ways back (the daily retention run). Returns how many went. */
|
|
188
|
+
export async function sweepEmailStates(db: any, reg: CmsRegistry): Promise<number> {
|
|
189
|
+
const s = reg.cmsState
|
|
190
|
+
// expiresAt is always an ISO string written by toISOString(), so text comparison is time order.
|
|
191
|
+
const gone: any[] = await db.delete(s).where(and(emailStateKeys(s), sql`coalesce(${s.value}->>'expiresAt', '') < ${new Date().toISOString()}`)).returning({ key: s.key })
|
|
192
|
+
return gone.length
|
|
193
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pure rules of changing an account's email address (no database, no Nitro):
|
|
3
|
+
* what a pending change looks like, when its link may still be used, and how an
|
|
4
|
+
* address is shown in a notice that goes to the *old* mailbox.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** A change waiting for its link to be opened, kept in cms_state under `email-change:<userId>`. */
|
|
8
|
+
export interface PendingEmailChange {
|
|
9
|
+
/** The cms_tokens row whose secret was mailed to the new address. */
|
|
10
|
+
tokenId: string
|
|
11
|
+
/** The new address (normalised: trimmed, lower-cased). */
|
|
12
|
+
email: string
|
|
13
|
+
/** The account's session version when the change was asked for. */
|
|
14
|
+
sv: number
|
|
15
|
+
expiresAt: string
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const EMAIL_CHANGE_STATE_PREFIX = 'email-change:'
|
|
19
|
+
export const emailChangeStateKey = (userId: string) => `${EMAIL_CHANGE_STATE_PREFIX}${userId}`
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A way back from a change that was made, kept in cms_state under
|
|
23
|
+
* `email-revert:<userId>:<tokenId>`: the address the account had before (the link went
|
|
24
|
+
* there, in the "your email was changed" notice). One row per change, so after A → B → C
|
|
25
|
+
* the link in A's mailbox still restores A.
|
|
26
|
+
*/
|
|
27
|
+
export interface EmailRevert {
|
|
28
|
+
/** The address to restore (the account's address before the change). */
|
|
29
|
+
email: string
|
|
30
|
+
expiresAt: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export const EMAIL_REVERT_STATE_PREFIX = 'email-revert:'
|
|
34
|
+
export const emailRevertStateKey = (userId: string, tokenId: string) => `${EMAIL_REVERT_STATE_PREFIX}${userId}:${tokenId}`
|
|
35
|
+
/** A LIKE pattern for every way back of one account (user ids are uuids: no `%` or `_` to escape). */
|
|
36
|
+
export const emailRevertStatePattern = (userId: string) => `${EMAIL_REVERT_STATE_PREFIX}${userId}:%`
|
|
37
|
+
|
|
38
|
+
export function asEmailRevert(value: unknown): EmailRevert | null {
|
|
39
|
+
const v = value as Partial<EmailRevert> | null
|
|
40
|
+
if (!v || typeof v !== 'object' || typeof v.email !== 'string' || typeof v.expiresAt !== 'string') return null
|
|
41
|
+
return { email: v.email, expiresAt: v.expiresAt }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A stored value, if it has the shape of a pending change (cms_state is plain JSON). */
|
|
45
|
+
export function asPendingEmailChange(value: unknown): PendingEmailChange | null {
|
|
46
|
+
const v = value as Partial<PendingEmailChange> | null
|
|
47
|
+
if (!v || typeof v !== 'object') return null
|
|
48
|
+
if (typeof v.tokenId !== 'string' || typeof v.email !== 'string' || typeof v.sv !== 'number' || typeof v.expiresAt !== 'string') return null
|
|
49
|
+
return { tokenId: v.tokenId, email: v.email, sv: v.sv, expiresAt: v.expiresAt }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* May this link still change the address? Only the newest request counts (its token is
|
|
54
|
+
* the one recorded), only before it expires, and only while the account's session
|
|
55
|
+
* version is the one it had when the change was asked for: a password change or reset,
|
|
56
|
+
* disabling the account or a role change since then cancels it. (That is how the owner
|
|
57
|
+
* stops a change somebody else asked for: "change your password".)
|
|
58
|
+
*/
|
|
59
|
+
export function emailChangeUsable(
|
|
60
|
+
pending: PendingEmailChange | null,
|
|
61
|
+
token: { id: string; expiresAt: Date | string },
|
|
62
|
+
user: { status: string; sessionVersion: number },
|
|
63
|
+
now = new Date(),
|
|
64
|
+
): pending is PendingEmailChange {
|
|
65
|
+
if (!pending) return false
|
|
66
|
+
if (pending.tokenId !== token.id) return false
|
|
67
|
+
if (user.status !== 'active' || user.sessionVersion !== pending.sv) return false
|
|
68
|
+
return new Date(token.expiresAt).getTime() > now.getTime() && new Date(pending.expiresAt).getTime() > now.getTime()
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Is a pending change dead for good (so its cms_state row can go)? Its own link was
|
|
73
|
+
* used, replaced or is gone, it expired, or the account moved on (session version,
|
|
74
|
+
* status). Unlike emailChangeUsable this looks at the pending change's own token, not
|
|
75
|
+
* at whichever link somebody opened: an older link must not delete a newer request.
|
|
76
|
+
*/
|
|
77
|
+
export function emailChangeDead(
|
|
78
|
+
pending: PendingEmailChange,
|
|
79
|
+
ownToken: { id: string; expiresAt: Date | string; usedAt: Date | string | null } | null | undefined,
|
|
80
|
+
user: { status: string; sessionVersion: number } | null | undefined,
|
|
81
|
+
now = new Date(),
|
|
82
|
+
): boolean {
|
|
83
|
+
if (!ownToken || ownToken.usedAt || !user) return true
|
|
84
|
+
return !emailChangeUsable(pending, ownToken, user, now)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* An address as a notice to the old mailbox shows it: enough for the owner to recognise
|
|
89
|
+
* their own new address, not enough to hand it in full to whoever reads the old mailbox
|
|
90
|
+
* now (a shared or handed-over work address is the usual reason to change it).
|
|
91
|
+
* `jana.novakova@example.com` → `j…a@example.com`; `jan@x.cz` → `j…@x.cz` (a short local
|
|
92
|
+
* part shows only its first character: two of three would all but spell it out).
|
|
93
|
+
*/
|
|
94
|
+
export function maskEmail(email: string): string {
|
|
95
|
+
const at = email.lastIndexOf('@')
|
|
96
|
+
if (at <= 0) return '…'
|
|
97
|
+
const local = email.slice(0, at)
|
|
98
|
+
const domain = email.slice(at + 1)
|
|
99
|
+
const chars = [...local]
|
|
100
|
+
const shown = chars.length <= 3 ? `${chars[0]}…` : `${chars[0]}…${chars[chars.length - 1]}`
|
|
101
|
+
return `${shown}@${domain}`
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Was this a Postgres unique violation (Drizzle keeps the driver's error as `cause`)? */
|
|
105
|
+
export function isUniqueViolation(err: unknown): boolean {
|
|
106
|
+
const e = err as { code?: string; cause?: { code?: string } } | null
|
|
107
|
+
return (e?.code ?? e?.cause?.code) === '23505'
|
|
108
|
+
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import { INVITE_TTL_MS } from './cmsAuth'
|
|
1
|
+
import { EMAIL_CHANGE_TTL_MS, EMAIL_REVERT_TTL_MS, INVITE_TTL_MS } from './cmsAuth'
|
|
2
|
+
import { maskEmail } from './cmsEmailChangeRules'
|
|
2
3
|
import { resolveText } from 'tinyzoo'
|
|
3
4
|
|
|
4
|
-
// The emails the CMS sends: an invitation
|
|
5
|
+
// The emails the CMS sends: an invitation, a password-reset link, and the ones about a
|
|
6
|
+
// change of email address (the link to the new address, notices to the old one). Plain, neutral
|
|
5
7
|
// HTML that survives every mail client, with a text version. Czech, English and German,
|
|
6
8
|
// chosen by the recipient's interface language (or the admin's default).
|
|
7
9
|
|
|
@@ -18,6 +20,30 @@ const copy = {
|
|
|
18
20
|
resetAction: 'Choose a new password',
|
|
19
21
|
resetExpiry: 'The link works for 1 hour. If you didn’t ask for this, ignore this email — your password stays the same.',
|
|
20
22
|
fallback: 'If the button does not work, copy this address into your browser:',
|
|
23
|
+
emailConfirmSubject: (site: string) => `Confirm your new email address for ${site}`,
|
|
24
|
+
emailConfirmIntro: (site: string) => `You asked to sign in to ${site} with this email address. Confirm it with the link below.`,
|
|
25
|
+
emailConfirmAction: 'Confirm the new address',
|
|
26
|
+
emailConfirmExpiry: (hours: number) => `The link works for ${hours} hours. Until you confirm, you keep signing in with your current address. If you didn’t ask for this, ignore this email.`,
|
|
27
|
+
emailRequestedSubject: (site: string) => `Your sign-in email for ${site} is about to change`,
|
|
28
|
+
emailRequestedIntro: (site: string, to: string) => `Someone signed in to your account at ${site} asked to change its sign-in email to ${to}. Nothing changes until the new address is confirmed.`,
|
|
29
|
+
emailRequestedAction: 'Choose a new password',
|
|
30
|
+
emailRequestedFooter: 'If it was you, there is nothing to do. If not, someone knows your password: choose a new password right away. Until the new address is confirmed, that cancels the change and signs everyone else out. If it has been confirmed already, another email will come here with a link that undoes it.',
|
|
31
|
+
emailChangedSubject: (site: string) => `Your sign-in email for ${site} was changed`,
|
|
32
|
+
emailChangedIntro: (site: string, to: string) => `The sign-in email of your account at ${site} was changed to ${to}. From now on, sign in with the new address.`,
|
|
33
|
+
emailChangedByAdminIntro: (site: string, to: string) => `An administrator changed the sign-in email of your account at ${site} to ${to}. From now on, sign in with the new address.`,
|
|
34
|
+
emailChangedFooter: 'If you didn’t expect this, contact the administrator of the site.',
|
|
35
|
+
emailRevertAction: 'Undo the change',
|
|
36
|
+
emailRevertFooter: (days: number) => `If it wasn’t you, open the link within ${days} days: your account gets this address back, you choose a new password and everyone else is signed out. If it was you, there is nothing to do, but don’t pass this email on: the link gives the account back to whoever opens it.`,
|
|
37
|
+
emailSetSubject: (site: string) => `Your sign-in email for ${site}`,
|
|
38
|
+
emailSetIntro: (site: string) => `An administrator set this address as the sign-in email of your account at ${site}. Sign in with it and your usual password.`,
|
|
39
|
+
emailSetAction: 'Sign in',
|
|
40
|
+
emailSetFooter: 'If you didn’t expect this, contact the administrator of the site.',
|
|
41
|
+
emailRevertedSubject: (site: string) => `Your sign-in email for ${site} was set back`,
|
|
42
|
+
emailRevertedIntro: (site: string, to: string) => `The sign-in email of your account at ${site} was set back to ${to} with the undo link sent to that address. A new password was chosen and everyone was signed out.`,
|
|
43
|
+
emailRevertedFooter: 'If you didn’t expect this, contact the administrator of the site.',
|
|
44
|
+
emailInUseSubject: (site: string) => `Your email address at ${site}`,
|
|
45
|
+
emailInUseIntro: (site: string) => `Someone asked to use this address for another account at ${site}, but it already belongs to an account there. Nothing was changed.`,
|
|
46
|
+
emailInUseFooter: 'If it was you, sign in with this address instead. Otherwise, ignore this email.',
|
|
21
47
|
},
|
|
22
48
|
cs: {
|
|
23
49
|
inviteSubject: (site: string) => `Pozvánka: ${site}`,
|
|
@@ -29,6 +55,30 @@ const copy = {
|
|
|
29
55
|
resetAction: 'Nastavit nové heslo',
|
|
30
56
|
resetExpiry: 'Odkaz platí 1 hodinu. Pokud jste o obnovení nežádali, e-mail ignorujte — vaše heslo zůstává stejné.',
|
|
31
57
|
fallback: 'Pokud tlačítko nefunguje, zkopírujte tuto adresu do prohlížeče:',
|
|
58
|
+
emailConfirmSubject: (site: string) => `Potvrďte novou e-mailovou adresu: ${site}`,
|
|
59
|
+
emailConfirmIntro: (site: string) => `Požádali jste o přihlašování do webu ${site} touto e-mailovou adresou. Potvrďte ji přes odkaz níže.`,
|
|
60
|
+
emailConfirmAction: 'Potvrdit novou adresu',
|
|
61
|
+
emailConfirmExpiry: (hours: number) => `Odkaz platí ${hours} hodin. Dokud adresu nepotvrdíte, přihlašujete se dál tou současnou. Pokud jste o změnu nežádali, e-mail ignorujte.`,
|
|
62
|
+
emailRequestedSubject: (site: string) => `Žádost o změnu přihlašovacího e-mailu: ${site}`,
|
|
63
|
+
emailRequestedIntro: (site: string, to: string) => `Někdo přihlášený k vašemu účtu na webu ${site} požádal o změnu přihlašovacího e-mailu na ${to}. Dokud nová adresa není potvrzená, nic se nemění.`,
|
|
64
|
+
emailRequestedAction: 'Nastavit nové heslo',
|
|
65
|
+
emailRequestedFooter: 'Pokud jste to byli vy, nemusíte nic dělat. Pokud ne, někdo zná vaše heslo: hned si nastavte nové. Dokud nová adresa není potvrzená, tím se změna zruší a všichni ostatní se odhlásí. Pokud už potvrzená je, přijde sem další e-mail s odkazem, kterým změnu vrátíte.',
|
|
66
|
+
emailChangedSubject: (site: string) => `Přihlašovací e-mail byl změněn: ${site}`,
|
|
67
|
+
emailChangedIntro: (site: string, to: string) => `Přihlašovací e-mail vašeho účtu na webu ${site} byl změněn na ${to}. Odteď se přihlašujte novou adresou.`,
|
|
68
|
+
emailChangedByAdminIntro: (site: string, to: string) => `Administrátor změnil přihlašovací e-mail vašeho účtu na webu ${site} na ${to}. Odteď se přihlašujte novou adresou.`,
|
|
69
|
+
emailChangedFooter: 'Pokud jste změnu nečekali, obraťte se na administrátora webu.',
|
|
70
|
+
emailRevertAction: 'Vrátit změnu',
|
|
71
|
+
emailRevertFooter: (days: number) => `Pokud jste to nebyli vy, otevřete do ${days} dnů odkaz: účet dostane zpět tuto adresu, nastavíte si nové heslo a všichni ostatní se odhlásí. Pokud jste to byli vy, nemusíte nic dělat, jen tento e-mail nikomu nepřeposílejte: kdo odkaz otevře, tomu se účet vrátí.`,
|
|
72
|
+
emailSetSubject: (site: string) => `Váš přihlašovací e-mail: ${site}`,
|
|
73
|
+
emailSetIntro: (site: string) => `Administrátor nastavil tuto adresu jako přihlašovací e-mail vašeho účtu na webu ${site}. Přihlaste se jí a svým obvyklým heslem.`,
|
|
74
|
+
emailSetAction: 'Přihlásit se',
|
|
75
|
+
emailSetFooter: 'Pokud jste změnu nečekali, obraťte se na administrátora webu.',
|
|
76
|
+
emailRevertedSubject: (site: string) => `Přihlašovací e-mail byl vrácen: ${site}`,
|
|
77
|
+
emailRevertedIntro: (site: string, to: string) => `Přihlašovací e-mail vašeho účtu na webu ${site} byl vrácen na ${to} odkazem pro vrácení změny, který přišel na tu adresu. Bylo nastaveno nové heslo a všichni byli odhlášeni.`,
|
|
78
|
+
emailRevertedFooter: 'Pokud jste to nečekali, obraťte se na administrátora webu.',
|
|
79
|
+
emailInUseSubject: (site: string) => `Vaše e-mailová adresa: ${site}`,
|
|
80
|
+
emailInUseIntro: (site: string) => `Někdo chtěl tuto adresu použít pro jiný účet na webu ${site}, ale už k ní jeden účet patří. Nic se nezměnilo.`,
|
|
81
|
+
emailInUseFooter: 'Pokud jste to byli vy, přihlaste se touto adresou. Jinak e-mail ignorujte.',
|
|
32
82
|
},
|
|
33
83
|
de: {
|
|
34
84
|
inviteSubject: (site: string) => `Einladung zu ${site}`,
|
|
@@ -40,6 +90,30 @@ const copy = {
|
|
|
40
90
|
resetAction: 'Neues Passwort festlegen',
|
|
41
91
|
resetExpiry: 'Der Link ist 1 Stunde gültig. Wenn Sie das nicht angefordert haben, ignorieren Sie diese E-Mail. Ihr Passwort bleibt unverändert.',
|
|
42
92
|
fallback: 'Falls die Schaltfläche nicht funktioniert, kopieren Sie diese Adresse in Ihren Browser:',
|
|
93
|
+
emailConfirmSubject: (site: string) => `Neue E-Mail-Adresse für ${site} bestätigen`,
|
|
94
|
+
emailConfirmIntro: (site: string) => `Sie möchten sich bei ${site} mit dieser E-Mail-Adresse anmelden. Bestätigen Sie sie über den Link unten.`,
|
|
95
|
+
emailConfirmAction: 'Neue Adresse bestätigen',
|
|
96
|
+
emailConfirmExpiry: (hours: number) => `Der Link ist ${hours} Stunden gültig. Bis zur Bestätigung melden Sie sich weiter mit Ihrer bisherigen Adresse an. Wenn Sie das nicht angefordert haben, ignorieren Sie diese E-Mail.`,
|
|
97
|
+
emailRequestedSubject: (site: string) => `Ihre Anmelde-E-Mail für ${site} soll geändert werden`,
|
|
98
|
+
emailRequestedIntro: (site: string, to: string) => `Jemand, der in Ihrem Konto bei ${site} angemeldet ist, möchte die Anmelde-E-Mail in ${to} ändern. Bis die neue Adresse bestätigt ist, ändert sich nichts.`,
|
|
99
|
+
emailRequestedAction: 'Neues Passwort festlegen',
|
|
100
|
+
emailRequestedFooter: 'Wenn Sie das waren, ist nichts zu tun. Wenn nicht, kennt jemand Ihr Passwort: Legen Sie sofort ein neues fest. Solange die neue Adresse nicht bestätigt ist, bricht das die Änderung ab und meldet alle anderen ab. Ist sie schon bestätigt, kommt hierher eine weitere E-Mail mit einem Link, der die Änderung rückgängig macht.',
|
|
101
|
+
emailChangedSubject: (site: string) => `Ihre Anmelde-E-Mail für ${site} wurde geändert`,
|
|
102
|
+
emailChangedIntro: (site: string, to: string) => `Die Anmelde-E-Mail Ihres Kontos bei ${site} wurde in ${to} geändert. Melden Sie sich ab jetzt mit der neuen Adresse an.`,
|
|
103
|
+
emailChangedByAdminIntro: (site: string, to: string) => `Ein Administrator hat die Anmelde-E-Mail Ihres Kontos bei ${site} in ${to} geändert. Melden Sie sich ab jetzt mit der neuen Adresse an.`,
|
|
104
|
+
emailChangedFooter: 'Wenn Sie das nicht erwartet haben, wenden Sie sich an den Administrator der Website.',
|
|
105
|
+
emailRevertAction: 'Änderung rückgängig machen',
|
|
106
|
+
emailRevertFooter: (days: number) => `Wenn Sie das nicht waren, öffnen Sie den Link innerhalb von ${days} Tagen: Ihr Konto bekommt diese Adresse zurück, Sie legen ein neues Passwort fest und alle anderen werden abgemeldet. Wenn Sie das waren, ist nichts zu tun, aber leiten Sie diese E-Mail nicht weiter: Wer den Link öffnet, bekommt das Konto zurück.`,
|
|
107
|
+
emailSetSubject: (site: string) => `Ihre Anmelde-E-Mail für ${site}`,
|
|
108
|
+
emailSetIntro: (site: string) => `Ein Administrator hat diese Adresse als Anmelde-E-Mail Ihres Kontos bei ${site} festgelegt. Melden Sie sich damit und mit Ihrem gewohnten Passwort an.`,
|
|
109
|
+
emailSetAction: 'Anmelden',
|
|
110
|
+
emailSetFooter: 'Wenn Sie das nicht erwartet haben, wenden Sie sich an den Administrator der Website.',
|
|
111
|
+
emailRevertedSubject: (site: string) => `Ihre Anmelde-E-Mail für ${site} wurde zurückgesetzt`,
|
|
112
|
+
emailRevertedIntro: (site: string, to: string) => `Die Anmelde-E-Mail Ihres Kontos bei ${site} wurde mit dem Link zum Rückgängigmachen, der an diese Adresse ging, auf ${to} zurückgesetzt. Ein neues Passwort wurde festgelegt und alle wurden abgemeldet.`,
|
|
113
|
+
emailRevertedFooter: 'Wenn Sie das nicht erwartet haben, wenden Sie sich an den Administrator der Website.',
|
|
114
|
+
emailInUseSubject: (site: string) => `Ihre E-Mail-Adresse bei ${site}`,
|
|
115
|
+
emailInUseIntro: (site: string) => `Jemand wollte diese Adresse für ein anderes Konto bei ${site} verwenden, sie gehört dort aber schon zu einem Konto. Es wurde nichts geändert.`,
|
|
116
|
+
emailInUseFooter: 'Wenn Sie das waren, melden Sie sich mit dieser Adresse an. Andernfalls ignorieren Sie diese E-Mail.',
|
|
43
117
|
},
|
|
44
118
|
} satisfies Record<Locale, Record<string, unknown>>
|
|
45
119
|
|
|
@@ -90,16 +164,24 @@ export function emailContext(locale?: string | null): { locale: Locale; site: st
|
|
|
90
164
|
return { locale: lang, site: resolveText(admin.name, lang, ['en']) || 'CMS' }
|
|
91
165
|
}
|
|
92
166
|
|
|
93
|
-
function layout(opts: { intro: string; action
|
|
94
|
-
const url = escapeHtml(opts.url)
|
|
167
|
+
function layout(opts: { intro: string; action?: string; url?: string; footer: string; fallback: string }) {
|
|
168
|
+
const url = opts.url ? escapeHtml(opts.url) : ''
|
|
169
|
+
const button = opts.action && opts.url
|
|
170
|
+
? `<p style="margin:0 0 24px"><a href="${url}" style="display:inline-block;background:#171717;color:#fff;text-decoration:none;padding:10px 16px;border-radius:6px;font-size:14px;font-weight:600">${escapeHtml(opts.action)}</a></p>
|
|
171
|
+
`
|
|
172
|
+
: ''
|
|
173
|
+
const fallback = opts.action && opts.url
|
|
174
|
+
? `<p style="margin:0;font-size:12px;line-height:1.5;color:#a3a3a3">${escapeHtml(opts.fallback)}<br><span style="word-break:break-all">${url}</span></p>
|
|
175
|
+
`
|
|
176
|
+
: ''
|
|
95
177
|
const html = `<!doctype html><html><body style="margin:0;padding:24px;background:#fafafa;font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:#171717">
|
|
96
178
|
<div style="max-width:480px;margin:0 auto;background:#fff;border:1px solid #e5e5e5;border-radius:8px;padding:28px">
|
|
97
179
|
<p style="margin:0 0 20px;font-size:15px;line-height:1.55">${escapeHtml(opts.intro)}</p>
|
|
98
|
-
<p style="margin:0 0
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
180
|
+
${button}<p style="margin:0 0 16px;font-size:13px;line-height:1.5;color:#737373">${escapeHtml(opts.footer)}</p>
|
|
181
|
+
${fallback}</div></body></html>`
|
|
182
|
+
const text = opts.action && opts.url
|
|
183
|
+
? `${opts.intro}\n\n${opts.action}: ${opts.url}\n\n${opts.footer}\n`
|
|
184
|
+
: `${opts.intro}\n\n${opts.footer}\n`
|
|
103
185
|
return { html, text }
|
|
104
186
|
}
|
|
105
187
|
|
|
@@ -123,3 +205,67 @@ export function resetEmail(opts: { to: string; url: string; locale?: string | nu
|
|
|
123
205
|
...layout({ intro: c.resetIntro, action: c.resetAction, url: opts.url, footer: c.resetExpiry, fallback: c.fallback }),
|
|
124
206
|
}
|
|
125
207
|
}
|
|
208
|
+
|
|
209
|
+
// ── a change of email address ──────────────────────────────────────────────────
|
|
210
|
+
|
|
211
|
+
/** To the new address: the link that makes the change. */
|
|
212
|
+
export function emailConfirmEmail(opts: { to: string; url: string; locale?: string | null }) {
|
|
213
|
+
const { locale, site } = emailContext(opts.locale)
|
|
214
|
+
const c = copy[locale]
|
|
215
|
+
const hours = Math.round(EMAIL_CHANGE_TTL_MS / 3_600_000)
|
|
216
|
+
return { to: opts.to, subject: c.emailConfirmSubject(site), ...layout({ intro: c.emailConfirmIntro(site), action: c.emailConfirmAction, url: opts.url, footer: c.emailConfirmExpiry(hours), fallback: c.fallback }) }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* To the old address when a change is asked for: if it was not them, somebody knows the
|
|
221
|
+
* password — a new one cancels the change while it waits; once it is made, the next
|
|
222
|
+
* notice carries the way back.
|
|
223
|
+
*/
|
|
224
|
+
export function emailRequestedNotice(opts: { to: string; newEmail: string; url: string; locale?: string | null }) {
|
|
225
|
+
const { locale, site } = emailContext(opts.locale)
|
|
226
|
+
const c = copy[locale]
|
|
227
|
+
return { to: opts.to, subject: c.emailRequestedSubject(site), ...layout({ intro: c.emailRequestedIntro(site, maskEmail(opts.newEmail)), action: c.emailRequestedAction, url: opts.url, footer: c.emailRequestedFooter, fallback: c.fallback }) }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* To the old address once the change is made (by the person, or by an administrator).
|
|
232
|
+
* With `revertUrl` (a change the person made), it carries the link that undoes it.
|
|
233
|
+
*/
|
|
234
|
+
export function emailChangedNotice(opts: { to: string; newEmail: string; byAdmin?: boolean; revertUrl?: string; locale?: string | null }) {
|
|
235
|
+
const { locale, site } = emailContext(opts.locale)
|
|
236
|
+
const c = copy[locale]
|
|
237
|
+
const intro = opts.byAdmin ? c.emailChangedByAdminIntro(site, maskEmail(opts.newEmail)) : c.emailChangedIntro(site, maskEmail(opts.newEmail))
|
|
238
|
+
const days = Math.round(EMAIL_REVERT_TTL_MS / 86_400_000)
|
|
239
|
+
const parts = opts.revertUrl
|
|
240
|
+
? { action: c.emailRevertAction, url: opts.revertUrl, footer: c.emailRevertFooter(days) }
|
|
241
|
+
: { footer: c.emailChangedFooter }
|
|
242
|
+
return { to: opts.to, subject: c.emailChangedSubject(site), ...layout({ intro, ...parts, fallback: c.fallback }) }
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** To the new address when an administrator set it: from now on this is how they sign in. */
|
|
246
|
+
export function emailSetNotice(opts: { to: string; url: string; locale?: string | null }) {
|
|
247
|
+
const { locale, site } = emailContext(opts.locale)
|
|
248
|
+
const c = copy[locale]
|
|
249
|
+
return { to: opts.to, subject: c.emailSetSubject(site), ...layout({ intro: c.emailSetIntro(site), action: c.emailSetAction, url: opts.url, footer: c.emailSetFooter, fallback: c.fallback }) }
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* To the address a way back replaced (the newer one): the account went back to the old
|
|
254
|
+
* address. Whoever reads this mailbox may be the owner, locked out by someone who reads
|
|
255
|
+
* the old one now; they must hear of it.
|
|
256
|
+
*/
|
|
257
|
+
export function emailRevertedNotice(opts: { to: string; restoredEmail: string; locale?: string | null }) {
|
|
258
|
+
const { locale, site } = emailContext(opts.locale)
|
|
259
|
+
const c = copy[locale]
|
|
260
|
+
return { to: opts.to, subject: c.emailRevertedSubject(site), ...layout({ intro: c.emailRevertedIntro(site, maskEmail(opts.restoredEmail)), footer: c.emailRevertedFooter, fallback: c.fallback }) }
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* To an address someone asked to move to that already has an account: the person asking
|
|
265
|
+
* is not told (it would tell them who has an account), the owner of the address is.
|
|
266
|
+
*/
|
|
267
|
+
export function emailInUseNotice(opts: { to: string; locale?: string | null }) {
|
|
268
|
+
const { locale, site } = emailContext(opts.locale)
|
|
269
|
+
const c = copy[locale]
|
|
270
|
+
return { to: opts.to, subject: c.emailInUseSubject(site), ...layout({ intro: c.emailInUseIntro(site), footer: c.emailInUseFooter, fallback: c.fallback }) }
|
|
271
|
+
}
|
package/server/utils/cmsLive.ts
CHANGED
|
@@ -44,6 +44,8 @@ interface LocalPeer {
|
|
|
44
44
|
socket: LiveSocket
|
|
45
45
|
user: CmsUser
|
|
46
46
|
sv: number
|
|
47
|
+
/** When the session this socket was admitted with was signed in (it ends with that session). */
|
|
48
|
+
iat: number
|
|
47
49
|
topics: Map<string, Watch>
|
|
48
50
|
/** Messages are handled one at a time, in order. */
|
|
49
51
|
queue: Promise<void>
|
|
@@ -111,7 +113,7 @@ export function stopLive(): void {
|
|
|
111
113
|
|
|
112
114
|
// ── connections ──
|
|
113
115
|
|
|
114
|
-
export function liveOpen(socket: LiveSocket, user: CmsUser, sv: number): void {
|
|
116
|
+
export function liveOpen(socket: LiveSocket, user: CmsUser, sv: number, iat: number): void {
|
|
115
117
|
const mine = [...local.values()].filter((p) => p.user.id === user.id)
|
|
116
118
|
if (mine.length >= MAX_SOCKETS_PER_USER) {
|
|
117
119
|
// Too many tabs: the oldest one gives way.
|
|
@@ -120,7 +122,7 @@ export function liveOpen(socket: LiveSocket, user: CmsUser, sv: number): void {
|
|
|
120
122
|
liveClose(oldest.socket)
|
|
121
123
|
}
|
|
122
124
|
const now = Date.now()
|
|
123
|
-
local.set(socket.id, { socket, user, sv, topics: new Map(), queue: Promise.resolve(), openedAt: now, seenAt: now, burst: { at: now, n: 0 } })
|
|
125
|
+
local.set(socket.id, { socket, user, sv, iat, topics: new Map(), queue: Promise.resolve(), openedAt: now, seenAt: now, burst: { at: now, n: 0 } })
|
|
124
126
|
start()
|
|
125
127
|
}
|
|
126
128
|
|
|
@@ -332,8 +334,9 @@ async function recheckAccounts(): Promise<void> {
|
|
|
332
334
|
const byId = new Map(rows.map((r) => [r.id, r]))
|
|
333
335
|
for (const p of [...local.values()]) {
|
|
334
336
|
const u = byId.get(p.user.id)
|
|
335
|
-
// A changed role reconnects too, so watches are re-authorised under the new one
|
|
336
|
-
|
|
337
|
+
// A changed role reconnects too, so watches are re-authorised under the new one; a
|
|
338
|
+
// session past its 14 days (from its sign-in) ends here as it does over HTTP.
|
|
339
|
+
if (!u || u.status !== 'active' || u.sv !== p.sv || u.role !== p.user.role || !signedInRecently({ cms: { iat: p.iat } })) {
|
|
337
340
|
p.socket.close(4401, 'Session no longer valid')
|
|
338
341
|
liveClose(p.socket)
|
|
339
342
|
}
|