From 0b4c4e8295f86729b5a2c809a90ff0b0f7dad9e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 24 Nov 2026 22:23:47 +0100 Subject: [PATCH] M1 (9): dashboard alerts by role MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit IntegrationAlerts reads the admin-only Site integrations global with access control off and showed its error texts to everyone who opened the dashboard. Now: an admin sees what is failing and the link, an editor a neutral "an integration needs attention — ask an administrator", anyone else nothing. CookieCrawlAlert is shown to editors and above (the role that may read the crawl result). Both use userMeetsRole, so a session that still owes its second factor sees neither. dashboardAlerts: { integrations: 'admin' | 'editor' | 'all', cookies: 'editor' | 'all' } loosens it. Co-Authored-By: Claude Fable 5.2 --- src/modules/admin-i18n/texts/integrations.ts | 2 + .../scanner/crawl/CookieCrawlAlert.tsx | 13 ++- .../integrations/IntegrationAlerts.tsx | 28 ++++- src/plugin.ts | 4 +- src/types.ts | 21 +++- test/cookieCrawlIntegration.test.ts | 8 +- test/dashboardAlerts.test.ts | 110 ++++++++++++++++++ 7 files changed, 173 insertions(+), 13 deletions(-) create mode 100644 test/dashboardAlerts.test.ts diff --git a/src/modules/admin-i18n/texts/integrations.ts b/src/modules/admin-i18n/texts/integrations.ts index 3ad331d..448b308 100644 --- a/src/modules/admin-i18n/texts/integrations.ts +++ b/src/modules/admin-i18n/texts/integrations.ts @@ -4,6 +4,7 @@ import { defineTexts } from '../define.js' export const integrationsTexts = defineTexts({ en: { // Dashboard alert (IntegrationAlerts) + alertsAskAdmin: 'Ask an administrator to look at it.', alertsHeading: 'An integration needs attention. The site still works.', alertsLink: 'Go to Site integrations', alertsUnknownError: 'Unknown error.', @@ -62,6 +63,7 @@ export const integrationsTexts = defineTexts({ testEmailWithFile: 'Attach a 10 MB test file', }, pl: { + alertsAskAdmin: 'Poproś administratora, aby to sprawdził.', alertsHeading: 'Integracja wymaga uwagi. Witryna nadal działa.', alertsLink: 'Przejdź do integracji', alertsUnknownError: 'Nieznany błąd.', diff --git a/src/modules/consent/scanner/crawl/CookieCrawlAlert.tsx b/src/modules/consent/scanner/crawl/CookieCrawlAlert.tsx index 263c5c5..9f1cd80 100644 --- a/src/modules/consent/scanner/crawl/CookieCrawlAlert.tsx +++ b/src/modules/consent/scanner/crawl/CookieCrawlAlert.tsx @@ -2,6 +2,7 @@ import type { Payload } from 'payload' import type { CookieScanLabels } from '../labels.js' +import { userMeetsRole } from '../../../access/predicates.js' import { COOKIE_APPROVAL_VIEW_PATH, countPendingCookies } from '../approval.js' import { COOKIE_REVIEW_SLUG } from '../collection.js' import { COOKIE_SCAN_LABELS, labelFor } from '../labels.js' @@ -11,12 +12,19 @@ type Props = { adminRoute?: string /** Cookie approval is on: remind while cookies wait, link to the approval view. Default true. */ approval?: boolean + /** + * Who sees the alert: `'editor'` (default — the role that may read the crawl result and the + * cookie review) or `'all'` (everyone who opens the dashboard, as before). + */ + audience?: 'all' | 'editor' /** The browser crawl is on: report violations and failed crawls. Default true. */ crawl?: boolean /** Injected by Payload into admin server components. */ i18n?: { language?: string } labels?: Record payload?: Payload + /** Injected by Payload into admin server components — the account looking at the dashboard. */ + user?: null | Record } type CrawlDoc = { error?: null | string; status?: null | string; summary?: { newUnknown?: null | number; violations?: null | number } | null } @@ -29,8 +37,11 @@ const fill = (template: string, values: Record) => * link to the approval view), and — with the crawl — violations or a failed * crawl. Renders nothing when nothing needs attention, and never throws. */ -export async function CookieCrawlAlert({ adminRoute = '/admin', approval = true, crawl = true, i18n, labels = COOKIE_SCAN_LABELS, payload }: Props) { +export async function CookieCrawlAlert({ adminRoute = '/admin', approval = true, audience = 'editor', crawl = true, i18n, labels = COOKIE_SCAN_LABELS, payload, user }: Props) { if (!payload) {return null} + // The crawl result and the review list are for editors and above; the widget reads them with + // access control off, so it asks the same question itself (the second factor included). + if (audience !== 'all' && !(user && userMeetsRole({ payload, user }, 'editor'))) {return null} let doc: CrawlDoc = {} if (crawl) { try { diff --git a/src/modules/integrations/IntegrationAlerts.tsx b/src/modules/integrations/IntegrationAlerts.tsx index 93a9a13..01900e4 100644 --- a/src/modules/integrations/IntegrationAlerts.tsx +++ b/src/modules/integrations/IntegrationAlerts.tsx @@ -2,6 +2,7 @@ import type { Payload } from 'payload' import type { IntegrationStatus } from './status.js' +import { userMeetsRole } from '../access/predicates.js' import { turnstileMissingKey } from '../turnstile/config.js' import { type IntegrationLabel, resolveLabel, serverText, STATUS_CODE_TEXTS } from './texts.js' @@ -10,10 +11,18 @@ type Props = { adminRoute?: string /** Status groups to check: field name → label (one string, or one per language). */ checks?: Record + /** + * Who sees WHAT is failing (the error text and the link to Site integrations): `'admin'` + * (default — the role that may read that global), `'editor'`, or `'all'` (everyone who opens + * the dashboard, as before). Below that, an editor sees a neutral line; anyone else nothing. + */ + details?: 'admin' | 'all' | 'editor' /** Injected by Payload into admin server components. */ i18n?: { language?: string; t?: (key: never, vars?: Record) => string } /** Injected by Payload into admin server components. */ payload?: Payload + /** Injected by Payload into admin server components — the account looking at the dashboard. */ + user?: null | Record } const DEFAULT_CHECKS: Record = { @@ -25,9 +34,16 @@ const DEFAULT_CHECKS: Record = { * Dashboard alert (admin.components.beforeDashboard): lists integrations that * are currently failing, with a link to Site integrations. Renders nothing when * everything is fine — and never throws (DB not ready → nothing). + * + * The texts come from the Site integrations global, which only admins may read: the widget + * reads it with access control off, so it decides itself who gets them (`details`). A + * session that still owes its second factor gets nothing (`userMeetsRole` includes it). */ -export async function IntegrationAlerts({ adminRoute = '/admin', checks = DEFAULT_CHECKS, i18n, payload }: Props) { +export async function IntegrationAlerts({ adminRoute = '/admin', checks = DEFAULT_CHECKS, details = 'admin', i18n, payload, user }: Props) { if (!payload) {return null} + const sees = (role: 'admin' | 'editor') => Boolean(user) && userMeetsRole({ payload, user }, role) + const full = details === 'all' || sees(details) + if (!full && !sees('editor')) {return null} let doc: Record try { doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record @@ -57,8 +73,18 @@ export async function IntegrationAlerts({ adminRoute = '/admin', checks = DEFAUL } if (!failing.length) {return null} + // Not allowed the detail: that something needs attention, and whom to ask — nothing of what or why. + if (!full) { + return ( +
+ {serverText(i18nLike, 'alertsHeading')} {serverText(i18nLike, 'alertsAskAdmin')} +
+ ) + } + return (
{ ...(config.admin?.components ?? {}), beforeDashboard: [ ...(config.admin?.components?.beforeDashboard ?? []), - { path: '@intecion/ipal-kit/admin#CookieCrawlAlert', serverProps: { adminRoute, approval: alertApproval, crawl: alertCrawl, labels } }, + { path: '@intecion/ipal-kit/admin#CookieCrawlAlert', serverProps: { adminRoute, approval: alertApproval, crawl: alertCrawl, labels, ...(options.dashboardAlerts?.cookies ? { audience: options.dashboardAlerts.cookies } : {}) } }, ], }, } @@ -823,7 +823,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { ...(config.admin?.components?.beforeDashboard ?? []), { path: '@intecion/ipal-kit/admin#IntegrationAlerts', - serverProps: { adminRoute: options.adminRoute ?? '/admin' }, + serverProps: { adminRoute: options.adminRoute ?? '/admin', ...(options.dashboardAlerts?.integrations ? { details: options.dashboardAlerts.integrations } : {}) }, }, ], }, diff --git a/src/types.ts b/src/types.ts index baf97fc..10c6719 100644 --- a/src/types.ts +++ b/src/types.ts @@ -101,6 +101,22 @@ export type IpalOptions = { */ cookieScanner?: boolean | CookieScannerOptions + /** + * Forms — form-builder collections (forms, form-submissions) plus the + * callable submitForm (Turnstile + persistence + SMTP-from-panel email). + */ + /** + * Who sees the plugin's dashboard alerts. They read data that only some + * roles may read, so each decides for itself: + * `integrations` — who gets WHAT is failing in Site integrations (error text + * and link): `'admin'` (default), `'editor'`, `'all'`; an editor below that + * sees a neutral "an integration needs attention — ask an administrator", + * anyone else nothing. `cookies` — who sees the cookie crawl / approval + * alert: `'editor'` (default) or `'all'`. `'all'` = as before. A session + * that still owes its second factor sees none of them. + */ + dashboardAlerts?: { cookies?: 'all' | 'editor'; integrations?: 'admin' | 'all' | 'editor' } + /** * GET /api/ipal/doctor — read-only counts for `ipal-doctor --url` (users without 2FA, cookies * waiting for approval, versions). Answers 404 until IPAL_DOCTOR_TOKEN (≥ 32 characters) is set; @@ -125,11 +141,6 @@ export type IpalOptions = { * Building blocks: buildFillEmptyLocalesGlobalHook / …CollectionHook. */ fillEmptyLocales?: { 'cookie-review'?: string[]; 'cookie-settings'?: string[] } | boolean - - /** - * Forms — form-builder collections (forms, form-submissions) plus the - * callable submitForm (Turnstile + persistence + SMTP-from-panel email). - */ forms?: FormsOption /** diff --git a/test/cookieCrawlIntegration.test.ts b/test/cookieCrawlIntegration.test.ts index f70a708..ae2121e 100644 --- a/test/cookieCrawlIntegration.test.ts +++ b/test/cookieCrawlIntegration.test.ts @@ -139,7 +139,7 @@ describe('cookie crawl — panel button → service → results', () => { expect(crawl.violations.map((v: { name: string }) => v.name).sort()).toEqual(['_fbp', 'tracker.invalid']) expect(sendEmail).toHaveBeenCalledWith(expect.objectContaining({ subject: expect.stringContaining('2'), to: ['dpo@acme.pl'] })) - expect(await CookieCrawlAlert({ payload })).not.toBeNull() + expect(await CookieCrawlAlert({ audience: 'all', payload })).not.toBeNull() sendEmail.mockRestore() }, 60_000) @@ -158,8 +158,8 @@ describe('cookie crawl — panel button → service → results', () => { const crawl = (await payload.findGlobal({ slug: 'cookie-crawl' as never })) as unknown as CrawlDoc expect(crawl.summary.violations).toBe(0) // No crawl problem left; only the approval reminder remains (drafts from the first crawl wait). - expect(await CookieCrawlAlert({ approval: false, payload })).toBeNull() - expect(await CookieCrawlAlert({ crawl: false, payload })).not.toBeNull() + expect(await CookieCrawlAlert({ approval: false, audience: 'all', payload })).toBeNull() + expect(await CookieCrawlAlert({ audience: 'all', crawl: false, payload })).not.toBeNull() }) test('a failed crawl is reported and the next one may start', async () => { @@ -168,6 +168,6 @@ describe('cookie crawl — panel button → service → results', () => { expect((await call(2, { body: { error: 'site down', jobId, ok: false }, token: TOKEN })).status).toBe(200) const status = (await (await call(0, { user: editor })).json()) as Record expect(status).toMatchObject({ error: 'site down', status: 'failed' }) - expect(await CookieCrawlAlert({ payload })).not.toBeNull() + expect(await CookieCrawlAlert({ audience: 'all', payload })).not.toBeNull() }) }) diff --git a/test/dashboardAlerts.test.ts b/test/dashboardAlerts.test.ts new file mode 100644 index 0000000..2bf97b8 --- /dev/null +++ b/test/dashboardAlerts.test.ts @@ -0,0 +1,110 @@ +/** + * M1: dashboard alerts by role. The widgets read data only some roles may read (with access control off), so + * they decide themselves who sees what: an admin the detail, an editor a neutral line, nobody else anything — + * and a session that still owes its second factor nothing at all. + */ +import type React from 'react' + +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, test } from 'vitest' + +import { CookieCrawlAlert } from '../src/modules/consent/scanner/crawl/CookieCrawlAlert.js' +import { IntegrationAlerts } from '../src/modules/integrations/IntegrationAlerts.js' +import { ipalKit } from '../src/plugin.js' + +const ERROR_TEXT = 'SMTP-ERROR-DETAIL: 535 authentication failed for mailer@example.com' +const payloadWith = (twoFactor: boolean) => ({ + config: { + admin: { user: 'users' }, + collections: [{ slug: 'users', auth: true, fields: [{ name: 'roles', type: 'select' }] }], + custom: { ipal: { staffCollections: ['users'], ...(twoFactor ? { twoFactor: { collection: 'users', requireSetup: true } } : {}) } }, + }, + count: async () => ({ totalDocs: 2 }), + findGlobal: async ({ slug }: { slug: string }) => + slug === 'site-integrations' + ? { emailStatus: { code: 'custom', message: ERROR_TEXT, state: 'degraded' }, turnstileSecretKey: 's', turnstileSiteKey: 'k' } + : { error: 'CRAWL-ERROR-DETAIL', status: 'failed', summary: { newUnknown: 0, violations: 0 } }, +}) +const user = (roles: string[], more: Record = {}) => ({ id: 1, collection: 'users', roles, ...more }) +const html = async (node: Promise) => { + const out = await node + return out ? renderToStaticMarkup(out as React.ReactElement) : '' +} +const integrations = (u: unknown, props: Record = {}, twoFactor = false) => html(IntegrationAlerts({ payload: payloadWith(twoFactor) as never, user: u as never, ...props })) +const cookies = (u: unknown, props: Record = {}, twoFactor = false) => html(CookieCrawlAlert({ payload: payloadWith(twoFactor) as never, user: u as never, ...props })) + +describe('IntegrationAlerts', () => { + test('an admin sees what is failing and the link', async () => { + const out = await integrations(user(['admin'])) + expect(out).toContain('SMTP-ERROR-DETAIL') + expect(out).toContain('/admin/globals/site-integrations') + expect(out).toContain('role="alert"') + }) + + test('an editor sees that something needs attention and whom to ask — no detail, no link', async () => { + const out = await integrations(user(['editor'])) + expect(out).toContain('An integration needs attention') + expect(out).toContain('Ask an administrator') + expect(out).not.toContain('SMTP-ERROR-DETAIL') + expect(out).not.toContain('mailer@example.com') + expect(out).not.toContain('site-integrations') + expect(out).toContain('role="status"') + }) + + test('a plain user, a visitor account, nobody: nothing', async () => { + expect(await integrations(user(['user']))).toBe('') + expect(await integrations({ id: 1, collection: 'customers', roles: ['admin'] })).toBe('') + expect(await integrations(null)).toBe('') + expect(await integrations(undefined)).toBe('') + }) + + test('a session that still owes its second factor sees nothing — admin or editor', async () => { + const owes = { _strategy: 'local-jwt', hasTotp: true } + expect(await integrations(user(['admin'], owes), {}, true)).toBe('') + expect(await integrations(user(['editor'], owes), {}, true)).toBe('') + expect(await integrations(user(['admin'], { _strategy: 'local-jwt', hasTotp: false }), {}, true)).toBe('') // TOTP not set up + expect(await integrations(user(['admin'], { _strategy: 'totp', hasTotp: true }), {}, true)).toContain('SMTP-ERROR-DETAIL') + }) + + test('details: editor / all loosen it; nothing failing renders nothing for anyone', async () => { + expect(await integrations(user(['editor']), { details: 'editor' })).toContain('SMTP-ERROR-DETAIL') + expect(await integrations(user(['user']), { details: 'editor' })).toBe('') + expect(await integrations(user(['user']), { details: 'all' })).toContain('SMTP-ERROR-DETAIL') + expect(await integrations(null, { details: 'all' })).toContain('SMTP-ERROR-DETAIL') // as before the change + const fine = { ...payloadWith(false), findGlobal: async () => ({ turnstileSecretKey: 's', turnstileSiteKey: 'k' }) } + expect(await html(IntegrationAlerts({ payload: fine as never, user: user(['admin']) as never }))).toBe('') + }) + + test('Polish for a Polish panel', async () => { + expect(await integrations(user(['editor']), { i18n: { language: 'pl' } })).toContain('Poproś administratora') + }) +}) + +describe('CookieCrawlAlert', () => { + test('editors and admins see it; others, and a session that owes its code, do not', async () => { + expect(await cookies(user(['admin']))).toContain('cookie-crawl-alert') + expect(await cookies(user(['editor']))).toContain('CRAWL-ERROR-DETAIL') // the crawl result is theirs to read + expect(await cookies(user(['user']))).toBe('') + expect(await cookies(null)).toBe('') + expect(await cookies(user(['editor'], { _strategy: 'local-jwt', hasTotp: true }), {}, true)).toBe('') + expect(await cookies(user(['user']), { audience: 'all' })).toContain('cookie-crawl-alert') + }) +}) + +describe('ipalKit({ dashboardAlerts })', () => { + const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } + const propsOf = async (options: Record) => { + const config = await ipalKit({ cookieScanner: { crawl: true }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x' } as never) + return JSON.stringify(config.admin?.components?.beforeDashboard) + } + + test('default: the components decide (admin detail, editor cookies); the option is passed on', async () => { + const plain = await propsOf({}) + expect(plain).toContain('IntegrationAlerts') + expect(plain).not.toContain('"details"') + expect(plain).not.toContain('"audience"') + const loose = await propsOf({ dashboardAlerts: { cookies: 'all', integrations: 'all' } }) + expect(loose).toContain('"details":"all"') + expect(loose).toContain('"audience":"all"') + }) +})