diff --git a/.changeset/34728-notification-settings.md b/.changeset/34728-notification-settings.md new file mode 100644 index 00000000000..72e3fe950a6 --- /dev/null +++ b/.changeset/34728-notification-settings.md @@ -0,0 +1,32 @@ +--- +'@objectstack/service-messaging': patch +'@objectstack/plugin-security': patch +'@objectstack/platform-objects': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(account): a Notification Settings page where each person chooses their own notification topics, channels, digest and quiet hours + +Clause-②: yes +Metadata-protocol: none + +The Account app has a new **Notification Settings** page, under Inbox and only when the messaging service runs. It shows one row per notification topic and one column per channel. Each cell shows whether that notification reaches you on that channel, and where the answer comes from: your own setting, your organization's default, the built-in default, or a mandatory topic. Mandatory topics are always delivered and cannot be switched off. A channel the deployment cannot send on yet says so in its column header. Above the matrix you can set your digest and your quiet hours. + +- **The read: `GET /api/v1/messaging/me/preferences`.** This new door answers the signed-in person's *effective* preferences. The server computes them with the same resolver `emit` uses to filter (`PreferenceResolver.effectiveFor`), so the page shows what is actually sent and computes nothing itself. The door takes no parameters and answers only about the caller: there is no `user` parameter, and any parameter is refused `VALIDATION_ERROR` / `400`. It keeps the posture of `GET /api/v1/messaging/preference-options`: + - an anonymous caller gets `401`; + - a held sign-in gets `403`; + - a source it cannot read is `500` / `INTERNAL_ERROR`, never a partial or "everything on" answer. + + The door reads only what the answer needs: the caller's own rows and the organization's default rows, each by equality on `user_id` within the caller's organization. A read that comes back with more rows than its cap is a fault (`500`), never a page. + + The organization's defaults appear only as `source: 'default'` on the caller's own cells. No other person's row, and no row id except the caller's own, is ever answered. +- **The writes: your own `sys_notification_preference` rows, through the data door, as you.** `member_default`, the baseline set every signed-in person resolves (external members excepted), now carries a grant of read, create and edit on the object, with no delete. Two row policies come with it: + - `sys_notification_preference_self` binds every principal that holds the grant. Its row scope is `user_id == current_user.id`, and its write check is the same expression, so the row as written must still be your own. + - `sys_notification_preference_org_admin` widens organization owners and administrators back to every row of their organization. Its write check is `topic != null`, which holds on every row being created because `topic` is required with a default. If `topic` ever becomes optional, an administrator's create is refused, never widened. + + An ordinary member or a delegated administrator lists only their own rows. Their create with `user_id` omitted, empty or naming another person is refused `403` / `PERMISSION_DENIED`, as is moving their own row to another person or to the organization default. +- **Owners and administrators are unchanged.** They still list every row, create and edit the organization default, create and edit another person's row, and delete in the Setup grid. +- **App-authored grants are narrowed too.** `sys_notification_preference_self` carries no `positions` domain, so it binds every principal that holds a grant on this object, including through an app's own permission set. A role other than organization owner or administrator that an app grants this object reads and writes only its own rows, unless the app declares its own widening policy for that role. + +There is no "reset to the organization's default" button, because that needs a delete, which members are not granted. Changing your digest or quiet hours saves your own general setting, and the page says so beside the control. From then on, that setting applies in place of the organization's defaults to every topic and channel you have not set yourself. diff --git a/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts b/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts index 6f5fdbc2771..abd6b9c0770 100644 --- a/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts +++ b/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts @@ -222,10 +222,13 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', ( .toEqual(['nav_connect_agent']); expect(groupChildren(account.body?.item, 'grp_account_developer')) .toEqual(['nav_account_api_keys', 'nav_account_oauth_apps']); - // The whole served tree, counted: 13 authored ids (the AI Assistant + // The whole served tree, counted: 14 authored ids (the AI Assistant // slot among them) + the one contributed. (12 authored until the - // Mobile App entry, `nav_account_mobile_app`, joined after Profile.) - expect(navIds(account.body?.item)).toHaveLength(14); + // Mobile App entry, `nav_account_mobile_app`, joined after Profile; + // 13 until the Notification Settings entry, + // `nav_account_notification_settings`, joined the Inbox group + // (#34728).) + expect(navIds(account.body?.item)).toHaveLength(15); // …and the entry's TARGET rode along, so the menu item resolves. expect(JSON.stringify(account.body)).toContain('connect_agent'); diff --git a/packages/platform-objects/src/apps/account.app.ts b/packages/platform-objects/src/apps/account.app.ts index db436862ff3..a815797d3a5 100644 --- a/packages/platform-objects/src/apps/account.app.ts +++ b/packages/platform-objects/src/apps/account.app.ts @@ -107,6 +107,23 @@ export const ACCOUNT_APP: App = { icon: 'bell', requiresObject: 'sys_inbox_message', }, + { + // [rulings 6968686390 and 6969143776] The person's own notification + // settings: per topic × channel on/off, digest and quiet hours. A + // console page registered as `account:notification_settings`; it + // reads `GET /api/v1/messaging/me/preferences` (their EFFECTIVE + // preferences, computed by the resolver `emit` uses) and writes + // their own `sys_notification_preference` rows through the data + // door, where `member_default`'s own-row policy decides which rows. + // Gated like Approvals: the capability is the messaging SERVICE, + // which mounts the route the page reads. + id: 'nav_account_notification_settings', + type: 'component', + label: 'Notification Settings', + componentRef: 'account:notification_settings', + icon: 'bell-ring', + requiresService: 'messaging', + }, { // #7234 — the DESTINATION is the Approvals Inbox component, not the // raw `sys_approval_request` grid. The engine-owned table has no diff --git a/packages/platform-objects/src/apps/translations/ar.ts b/packages/platform-objects/src/apps/translations/ar.ts index c37b859098f..b5576f775e0 100644 --- a/packages/platform-objects/src/apps/translations/ar.ts +++ b/packages/platform-objects/src/apps/translations/ar.ts @@ -20,6 +20,7 @@ export const ar: TranslationData = { nav_account_profile: { label: 'الملف الشخصي' }, nav_account_mobile_app: { label: 'تطبيق الجوال' }, nav_account_notifications: { label: 'الإشعارات' }, + nav_account_notification_settings: { label: 'إعدادات الإشعارات' }, nav_account_approvals: { label: 'بانتظار موافقتي' }, nav_account_memberships: { label: 'مؤسساتي' }, nav_account_linked: { label: 'الحسابات المرتبطة' }, diff --git a/packages/platform-objects/src/apps/translations/de.ts b/packages/platform-objects/src/apps/translations/de.ts index abb04663895..a90ba6d2117 100644 --- a/packages/platform-objects/src/apps/translations/de.ts +++ b/packages/platform-objects/src/apps/translations/de.ts @@ -20,6 +20,7 @@ export const de: TranslationData = { nav_account_profile: { label: 'Profil' }, nav_account_mobile_app: { label: 'Mobile-App' }, nav_account_notifications: { label: 'Benachrichtigungen' }, + nav_account_notification_settings: { label: 'Benachrichtigungseinstellungen' }, nav_account_approvals: { label: 'Meine ausstehenden Genehmigungen' }, nav_account_memberships: { label: 'Meine Organisationen' }, nav_account_linked: { label: 'Verknüpfte Konten' }, diff --git a/packages/platform-objects/src/apps/translations/en.ts b/packages/platform-objects/src/apps/translations/en.ts index 87b22e8aaa3..0d94a1f54d2 100644 --- a/packages/platform-objects/src/apps/translations/en.ts +++ b/packages/platform-objects/src/apps/translations/en.ts @@ -35,6 +35,7 @@ export const en: TranslationData = { nav_account_profile: { label: 'Profile' }, nav_account_mobile_app: { label: 'Mobile App' }, nav_account_notifications: { label: 'Notifications' }, + nav_account_notification_settings: { label: 'Notification Settings' }, nav_account_approvals: { label: 'Approvals' }, nav_account_memberships: { label: 'My Organizations' }, nav_account_linked: { label: 'Linked Accounts' }, diff --git a/packages/platform-objects/src/apps/translations/es-ES.ts b/packages/platform-objects/src/apps/translations/es-ES.ts index 334cc0a65ec..414d4372176 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.ts @@ -20,6 +20,7 @@ export const esES: TranslationData = { nav_account_profile: { label: 'Perfil' }, nav_account_mobile_app: { label: 'Aplicación móvil' }, nav_account_notifications: { label: 'Notificaciones' }, + nav_account_notification_settings: { label: 'Configuración de notificaciones' }, nav_account_approvals: { label: 'Aprobaciones pendientes' }, nav_account_memberships: { label: 'Mis organizaciones' }, nav_account_linked: { label: 'Cuentas vinculadas' }, diff --git a/packages/platform-objects/src/apps/translations/fr.ts b/packages/platform-objects/src/apps/translations/fr.ts index 2491089d06c..8512a22f91a 100644 --- a/packages/platform-objects/src/apps/translations/fr.ts +++ b/packages/platform-objects/src/apps/translations/fr.ts @@ -20,6 +20,7 @@ export const fr: TranslationData = { nav_account_profile: { label: 'Profil' }, nav_account_mobile_app: { label: 'Application mobile' }, nav_account_notifications: { label: 'Notifications' }, + nav_account_notification_settings: { label: 'Paramètres de notification' }, nav_account_approvals: { label: 'Mes approbations en attente' }, nav_account_memberships: { label: 'Mes organisations' }, nav_account_linked: { label: 'Comptes liés' }, diff --git a/packages/platform-objects/src/apps/translations/ja-JP.ts b/packages/platform-objects/src/apps/translations/ja-JP.ts index 34a07ff4921..39eabfd756e 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.ts @@ -20,6 +20,7 @@ export const jaJP: TranslationData = { nav_account_profile: { label: 'プロフィール' }, nav_account_mobile_app: { label: 'モバイルアプリ' }, nav_account_notifications: { label: '通知' }, + nav_account_notification_settings: { label: '通知設定' }, nav_account_approvals: { label: '承認待ち' }, nav_account_memberships: { label: '所属組織' }, nav_account_linked: { label: '連携アカウント' }, diff --git a/packages/platform-objects/src/apps/translations/ko.ts b/packages/platform-objects/src/apps/translations/ko.ts index aaec3113de5..98c3ccc6ee0 100644 --- a/packages/platform-objects/src/apps/translations/ko.ts +++ b/packages/platform-objects/src/apps/translations/ko.ts @@ -20,6 +20,7 @@ export const ko: TranslationData = { nav_account_profile: { label: '프로필' }, nav_account_mobile_app: { label: '모바일 앱' }, nav_account_notifications: { label: '알림' }, + nav_account_notification_settings: { label: '알림 설정' }, nav_account_approvals: { label: '내 승인 대기' }, nav_account_memberships: { label: '내 조직' }, nav_account_linked: { label: '연결된 계정' }, diff --git a/packages/platform-objects/src/apps/translations/pt-BR.ts b/packages/platform-objects/src/apps/translations/pt-BR.ts index 7bbf71d9d14..4869a68d45b 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.ts @@ -20,6 +20,7 @@ export const ptBR: TranslationData = { nav_account_profile: { label: 'Perfil' }, nav_account_mobile_app: { label: 'Aplicativo móvel' }, nav_account_notifications: { label: 'Notificações' }, + nav_account_notification_settings: { label: 'Configurações de notificação' }, nav_account_approvals: { label: 'Minhas aprovações pendentes' }, nav_account_memberships: { label: 'Minhas organizações' }, nav_account_linked: { label: 'Contas vinculadas' }, diff --git a/packages/platform-objects/src/apps/translations/ru.ts b/packages/platform-objects/src/apps/translations/ru.ts index a6d7a07cd3c..26a165608d7 100644 --- a/packages/platform-objects/src/apps/translations/ru.ts +++ b/packages/platform-objects/src/apps/translations/ru.ts @@ -20,6 +20,7 @@ export const ru: TranslationData = { nav_account_profile: { label: 'Профиль' }, nav_account_mobile_app: { label: 'Мобильное приложение' }, nav_account_notifications: { label: 'Уведомления' }, + nav_account_notification_settings: { label: 'Настройки уведомлений' }, nav_account_approvals: { label: 'Ждут моего решения' }, nav_account_memberships: { label: 'Мои организации' }, nav_account_linked: { label: 'Связанные учётные записи' }, diff --git a/packages/platform-objects/src/apps/translations/zh-CN.ts b/packages/platform-objects/src/apps/translations/zh-CN.ts index 713a29a3314..0ab64b2e61b 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.ts @@ -20,6 +20,7 @@ export const zhCN: TranslationData = { nav_account_profile: { label: '个人资料' }, nav_account_mobile_app: { label: '移动应用' }, nav_account_notifications: { label: '通知' }, + nav_account_notification_settings: { label: '通知设置' }, nav_account_approvals: { label: '待我审批' }, nav_account_memberships: { label: '我的组织' }, nav_account_linked: { label: '已关联账户' }, diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.ts b/packages/platform-objects/src/apps/translations/zh-Hant.ts index 1d7b1492b4f..876aec38241 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.ts @@ -20,6 +20,7 @@ export const zhHant: TranslationData = { nav_account_profile: { label: '個人資料' }, nav_account_mobile_app: { label: '移動應用' }, nav_account_notifications: { label: '通知' }, + nav_account_notification_settings: { label: '通知設定' }, nav_account_approvals: { label: '待我核准' }, nav_account_memberships: { label: '我的組織' }, nav_account_linked: { label: '已關聯帳戶' }, diff --git a/packages/plugins/plugin-security/package.json b/packages/plugins/plugin-security/package.json index f6e34209c7c..de2d5a76a65 100644 --- a/packages/plugins/plugin-security/package.json +++ b/packages/plugins/plugin-security/package.json @@ -41,6 +41,7 @@ "@objectstack/plugin-audit": "workspace:*", "@objectstack/plugin-sharing": "workspace:*", "@objectstack/service-i18n": "workspace:*", + "@objectstack/service-messaging": "workspace:*", "@types/node": "^26.6.5", "tsx": "^4.23.15", "typescript": "^6.0.3", diff --git a/packages/plugins/plugin-security/src/default-permission-sets.notification-preference.integration.test.ts b/packages/plugins/plugin-security/src/default-permission-sets.notification-preference.integration.test.ts new file mode 100644 index 00000000000..028a365f8c6 --- /dev/null +++ b/packages/plugins/plugin-security/src/default-permission-sets.notification-preference.integration.test.ts @@ -0,0 +1,356 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [rulings 6968686390, 6969143776 and 6973785798] A member reads and writes + * their OWN notification preferences, and nothing else; so does a delegated + * administrator. An organization owner or administrator keeps the Setup grid + * exactly as it was. + * + * `member_default` names `sys_notification_preference` (read, create, edit, no + * delete) and declares two policies on it: + * - `sys_notification_preference_self`: row scope and write check both + * `user_id == current_user.id`, NO `positions`, so it binds every principal + * that resolves the grant; + * - `sys_notification_preference_org_admin`: row scope `id != null`, write + * check `topic != null`, positions the organization owner and administrator + * identities (`delegated_admin` is not in it). + * This suite drives that line and those policies, as shipped, on a real stack: + * + * - the REAL `SecurityPlugin` with the shipped permission sets; + * - the REAL `sys_notification_preference` object (service-messaging), whose + * empty `user_id` is the organization's default for everyone (ADR-0118 D1); + * - the REAL caller resolution (`resolveAuthzContext`, then + * `assembleExecutionContext`) over the identity rows seeded below, so each + * persona's positions are the resolver's answer, not this file's; + * - the REAL `PreferenceResolver`, the filter `emit` runs, over what the + * member wrote. + * + * Each key is load-bearing: without the self policy's `check`, the + * `owner_only_writes` floor joins the write check and a member moves a row + * they created to another person or to the empty user; with `positions` on the + * self policy, a role outside them is matched by no policy and reads and writes + * every row; without the widener, an owner's or administrator's grid narrows + * to their own rows; and a widener check that does not hold on a row being + * created (`id != null`) refuses every administrator create. The ablations are + * in the pull request that landed each. + * + * Refusals assert the wire `code` AND `status` the data door maps the engine's + * error to (ADR-0112), and that nothing was stored. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectKernel, resolveAuthzContext, assembleExecutionContext, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity'; +import { NotificationPreference, PreferenceResolver, PREFERENCE_OBJECT } from '@objectstack/service-messaging'; +import { mapDataError } from '@objectstack/types'; +import { SecurityPlugin } from './security-plugin.js'; +import { defaultPermissionSets } from './objects/default-permission-sets.js'; + +const OBJ = PREFERENCE_OBJECT; +const ORG = 'org_npref'; +/** Two ordinary members, a delegated administrator, an administrator and an owner. */ +const ALICE = 'usr_npref_alice'; +const BOB = 'usr_npref_bob'; +const CAROL = 'usr_npref_carol'; +const DAVE = 'usr_npref_dave'; +const OWEN = 'usr_npref_owen'; + +/** The principals the self policy narrows to their own rows. */ +const NARROWED = [ + { label: 'an ordinary member', key: 'alice', userId: ALICE }, + { label: 'a delegated administrator', key: 'dave', userId: DAVE }, +] as const; +/** The principals the widener keeps on every row of their organization. */ +const WIDENED = [ + { label: 'an organization administrator', key: 'carol', userId: CAROL }, + { label: 'an organization owner', key: 'owen', userId: OWEN }, +] as const; + +const SYS = { isSystem: true, tenantId: ORG } as const; + +type Row = Record; +type Ctx = Record; + +function sqliteDriverPlugin(): Plugin { + return { + name: 'test.driver.sqlite', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService( + 'driver.default', + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + ); + }, + }; +} + +function objectsPlugin(): Plugin { + return { + name: 'test.objects', + type: 'standard', + version: '1.0.0', + dependencies: ['com.objectstack.engine.objectql'], + async init(ctx: PluginContext) { + ctx.getService<{ register(m: unknown): unknown }>('manifest').register({ + id: 'test.notification-preference-grants', + namespace: 'npref', + version: '1.0.0', + type: 'plugin', + name: 'Notification preference grants fixture', + objects: [SysUser, SysMember, SysOrganization, NotificationPreference], + }); + }, + }; +} + +/** The wire answer a refused engine call maps to, as the data door sends it. */ +async function refusal(run: () => Promise): Promise<{ status: number; code: string }> { + let thrown: unknown; + try { + await run(); + } catch (e) { + thrown = e; + } + expect(thrown, `the ${OBJ} call was refused`).toBeDefined(); + const wire = mapDataError(thrown, OBJ); + return { status: wire.status, code: String(wire.body.code) }; +} + +const silent = { info() {}, warn() {}, error() {} }; + +describe('member_default: who reads and writes sys_notification_preference rows', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + const as: Record = {}; + /** Rows seeded as the system: the organization default, a row for bob, and one an administrator wrote for each narrowed persona. */ + const seeded: Record = {}; + + const contextOf = async (userId: string): Promise => { + const authz = await resolveAuthzContext({ + ql, + headers: {}, + getSession: async () => ({ + user: { id: userId }, + session: { id: `ses_${userId}`, userId, activeOrganizationId: ORG }, + }), + } as never); + return assembleExecutionContext({ + authz, + oauth: undefined, + localization: undefined, + requestLocale: undefined, + accessToken: undefined, + } as never) as unknown as Ctx; + }; + + const insert = (ctx: Ctx, data: Row) => ql.insert(OBJ, data, { context: ctx } as never) as Promise; + const update = (ctx: Ctx, id: string, data: Row) => ql.update(OBJ, data, { where: { id }, context: ctx } as never); + const list = async (ctx: Ctx) => (await ql.find(OBJ, { context: ctx } as never)) as Row[]; + const stored = async (where: Row) => (await ql.find(OBJ, { where, context: SYS } as never)) as Row[]; + const storedById = async (id: string) => (await stored({ id }))[0]; + const keys = (rows: Row[]) => rows.map((r) => `${r.user_id ?? '(everyone)'}|${r.topic}|${r.channel}`).sort(); + + beforeAll(async () => { + kernel = new ObjectKernel({ logger: { level: 'silent' } }); + await kernel.use(sqliteDriverPlugin()); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(objectsPlugin()); + await kernel.use(new SecurityPlugin({ defaultPermissionSets })); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + + await ql.insert('sys_organization', { id: ORG, name: 'Preference Co', slug: 'preference-co' }, { context: SYS } as never); + const role: Record = { + [ALICE]: 'member', + [BOB]: 'member', + [CAROL]: 'admin', + [DAVE]: 'delegated_admin', + [OWEN]: 'owner', + }; + for (const userId of Object.keys(role)) { + await ql.insert( + 'sys_user', + { id: userId, name: userId, email: `${userId}@preference-co.test`, email_verified: true }, + { context: SYS } as never, + ); + await ql.insert('sys_member', { user_id: userId, organization_id: ORG, role: role[userId] }, { context: SYS } as never); + } + seeded.everyone = String((await insert(SYS, { topic: 'approval.reminder', channel: 'email', enabled: false })).id); + seeded.bob = String((await insert(SYS, { user_id: BOB, topic: 'collab.mention', channel: 'email', enabled: false })).id); + // A row in each narrowed persona's name an administrator wrote: its `created_by` is not theirs. + for (const { key, userId } of NARROWED) { + seeded[`${key}ByAdmin`] = String((await insert(SYS, { user_id: userId, topic: 'approval.comment', channel: 'inbox', enabled: true })).id); + } + + for (const { key, userId } of [...NARROWED, ...WIDENED]) as[key] = await contextOf(userId); + }, 120_000); + + afterAll(async () => { + if (kernel) await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + }, 30_000); + + it('the fixture is armed: the resolver gives each persona the position this suite is about', () => { + expect(as.alice.positions).toEqual(expect.arrayContaining(['org_member', 'everyone'])); + expect(as.dave.positions).toEqual(expect.arrayContaining(['delegated_admin', 'everyone'])); + expect(as.carol.positions).toEqual(expect.arrayContaining(['org_admin', 'everyone'])); + expect(as.owen.positions).toEqual(expect.arrayContaining(['org_owner', 'everyone'])); + // The delegated administrator is in neither the member domain nor the widener's. + for (const p of ['org_member', 'org_admin', 'org_owner']) expect(as.dave.positions).not.toContain(p); + for (const key of ['carol', 'owen']) expect(as[key].positions).not.toContain('org_member'); + }); + + for (const { label: persona, key, userId } of NARROWED) { + describe(`${persona}, on their own rows`, () => { + it('creates a preference in their own name and lists only their own rows', async () => { + const row = await insert(as[key], { user_id: userId, topic: 'approval.requested', channel: 'email', enabled: false }); + expect((await storedById(String(row.id)))?.user_id).toBe(userId); + const mine = await list(as[key]); + expect(mine.every((r) => r.user_id === userId)).toBe(true); + expect(keys(mine)).toEqual(expect.arrayContaining([`${userId}|approval.requested|email`, `${userId}|approval.comment|inbox`])); + }); + + it('edits their own row, the one they created and the one an administrator wrote in their name', async () => { + const own = String((await insert(as[key], { user_id: userId, topic: 'approval.returned', channel: '*', enabled: true })).id); + await update(as[key], own, { enabled: false, digest: 'daily' }); + expect(await storedById(own)).toMatchObject({ user_id: userId, enabled: false, digest: 'daily' }); + await update(as[key], seeded[`${key}ByAdmin`], { enabled: false }); + expect((await storedById(seeded[`${key}ByAdmin`]))?.enabled).toBe(false); + }); + + it('deletes nothing: the grant carries no delete bit', async () => { + const own = String((await insert(as[key], { user_id: userId, topic: 'approval.escalated', channel: 'email', enabled: false })).id); + expect(await refusal(() => ql.delete(OBJ, { where: { id: own }, context: as[key] } as never))).toEqual({ + status: 403, + code: 'PERMISSION_DENIED', + }); + expect(await storedById(own)).toBeDefined(); + }); + }); + + describe(`${persona} never writes a row that is not their own`, () => { + for (const [label, data] of [ + ['user_id omitted (the default for everyone)', {}], + ['user_id null (the default for everyone)', { user_id: null }], + ["user_id '' (the default for everyone)", { user_id: '' }], + ["another member's user_id", { user_id: BOB }], + ] as const) { + it(`refuses a create with ${label}: 403 PERMISSION_DENIED, nothing stored`, async () => { + const topic = `refused.create.${key}.${label.length}`; + expect(await refusal(() => insert(as[key], { ...data, topic, channel: '*', enabled: false }))).toEqual({ + status: 403, + code: 'PERMISSION_DENIED', + }); + expect(await stored({ topic })).toEqual([]); + }); + } + + it('refuses a create for the default with topic and channel omitted: 403 PERMISSION_DENIED, nothing stored', async () => { + const channel = `refused.defaulted.${key}`; + expect(await refusal(() => insert(as[key], { channel, enabled: false }))).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + expect(await stored({ channel })).toEqual([]); + }); + + for (const [label, to] of [ + ['to another member', BOB], + ['to the empty user (the default for everyone)', null], + ] as const) { + it(`refuses moving a row they created ${label}: 403 PERMISSION_DENIED, the row keeps its owner`, async () => { + const own = String((await insert(as[key], { user_id: userId, topic: `move.${String(to)}`, channel: '*', enabled: false })).id); + expect((await storedById(own))?.created_by).toBe(userId); + expect(await refusal(() => update(as[key], own, { user_id: to }))).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + expect((await storedById(own))?.user_id).toBe(userId); + }); + } + + it('refuses moving a row an administrator wrote in their name: 403 PERMISSION_DENIED', async () => { + expect(await refusal(() => update(as[key], seeded[`${key}ByAdmin`], { user_id: BOB }))).toEqual({ + status: 403, + code: 'PERMISSION_DENIED', + }); + expect((await storedById(seeded[`${key}ByAdmin`]))?.user_id).toBe(userId); + }); + + it("neither reads nor edits the organization's default or another member's row: 404 RECORD_NOT_FOUND", async () => { + const visible = (await list(as[key])).map((r) => String(r.id)); + expect(visible).not.toContain(seeded.everyone); + expect(visible).not.toContain(seeded.bob); + for (const id of [seeded.everyone, seeded.bob]) { + expect(await refusal(() => update(as[key], id, { enabled: true }))).toEqual({ status: 404, code: 'RECORD_NOT_FOUND' }); + expect((await storedById(id))?.enabled).toBe(false); + } + }); + }); + } + + for (const { label: persona, key } of WIDENED) { + describe(`${persona} keeps the Setup grid`, () => { + it("lists every row of the organization, the default and each member's", async () => { + const ids = (await list(as[key])).map((r) => String(r.id)); + expect(ids).toEqual(expect.arrayContaining([seeded.everyone, seeded.bob, seeded.aliceByAdmin, seeded.daveByAdmin])); + }); + + it("creates the organization's default and another person's row", async () => { + const def = await insert(as[key], { topic: `system.upgrade_impact.${key}`, channel: 'email', enabled: false }); + expect((await storedById(String(def.id)))?.user_id ?? null).toBeNull(); + const forBob = await insert(as[key], { user_id: BOB, topic: `system.upgrade_impact.${key}`, channel: 'email', enabled: false }); + expect((await storedById(String(forBob.id)))?.user_id).toBe(BOB); + }); + + it('creates a default with topic omitted: the check judges the defaulted topic', async () => { + // The widener's `check` is `topic != null`, coupled to `topic` being + // required with a default: the write image it judges carries `*`. + const channel = `defaulted.${key}`; + const row = await insert(as[key], { channel, enabled: false }); + expect(await storedById(String(row.id))).toMatchObject({ topic: '*', channel }); + expect((await storedById(String(row.id)))?.user_id ?? null).toBeNull(); + }); + + it("edits the organization's default and another person's row", async () => { + await update(as[key], seeded.everyone, { digest: 'weekly' }); + expect((await storedById(seeded.everyone))?.digest).toBe('weekly'); + await update(as[key], seeded.bob, { enabled: true }); + expect((await storedById(seeded.bob))?.enabled).toBe(true); + await update(as[key], seeded.bob, { enabled: false }); + await update(as[key], seeded.everyone, { digest: 'none' }); + }); + + it('deletes a row, as today', async () => { + const doomed = String((await insert(SYS, { topic: `doomed.${key}`, channel: 'email', enabled: false })).id); + await ql.delete(OBJ, { where: { id: doomed }, context: as[key] } as never); + expect(await storedById(doomed)).toBeUndefined(); + }); + }); + } + + describe('what a member wrote takes effect on the next emit', () => { + const resolver = (mandatoryTopics: string[] = []) => + new PreferenceResolver({ getData: () => ql as never, logger: silent, mandatoryTopics }); + + it("the member's own mute drops that channel for them and for nobody else", async () => { + const topic = 'deal.won'; + const before = await resolver().filter([ALICE, BOB], ['inbox', 'email'], { topic, organizationId: ORG }); + expect(before).toEqual([ + { recipient: ALICE, channels: ['inbox', 'email'] }, + { recipient: BOB, channels: ['inbox', 'email'] }, + ]); + await insert(as.alice, { user_id: ALICE, topic, channel: 'email', enabled: false }); + const after = await resolver().filter([ALICE, BOB], ['inbox', 'email'], { topic, organizationId: ORG }); + expect(after).toEqual([ + { recipient: ALICE, channels: ['inbox'] }, + { recipient: BOB, channels: ['inbox', 'email'] }, + ]); + }); + + it('a mandatory topic is still delivered on every channel, whatever the member wrote', async () => { + const topic = 'security.access_upgrade'; + await insert(as.alice, { user_id: ALICE, topic, channel: '*', enabled: false }); + expect(await resolver().filter([ALICE], ['inbox', 'email'], { topic, organizationId: ORG })).toEqual([]); + expect(await resolver(['security.']).filter([ALICE], ['inbox', 'email'], { topic, organizationId: ORG })).toEqual([ + { recipient: ALICE, channels: ['inbox', 'email'] }, + ]); + }); + }); +}); diff --git a/packages/plugins/plugin-security/src/objects/default-permission-sets.ts b/packages/plugins/plugin-security/src/objects/default-permission-sets.ts index de71003fa3a..841439950bb 100644 --- a/packages/plugins/plugin-security/src/objects/default-permission-sets.ts +++ b/packages/plugins/plugin-security/src/objects/default-permission-sets.ts @@ -772,6 +772,16 @@ const baseDefaultPermissionSets: PermissionSet[] = [ // implicit; making it explicit is the migration, not a widening — the // effective access for a member is byte-identical. sys_user_preference: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false }, + // [rulings 6968686390, 6969143776 and 6973785798] A member's own + // notification preferences: which topics reach them on which channel, + // their digest and their quiet hours (Account → Notification Settings). + // The object is `system-data` ("RLS is the authz"), so WHICH ROWS is the + // `sys_notification_preference_self` policy below, which carries a write + // check and binds every principal holding this grant, and its owner/admin + // widener; read both before touching this line. ⛔ No `allowDelete`, for the anchor reason above + // (ADR-0090 D5): "reset to the administrator's default" is not a + // baseline right. + sys_notification_preference: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false }, // A reader's own named list views (ruling 6570568131 on #28971, letter // C): save and rename their own views, on the preference template. // The object's own owner-only default row scope (`sys_personal_view_self`, @@ -1016,6 +1026,50 @@ const baseDefaultPermissionSets: PermissionSet[] = [ operation: 'all', using: 'user_id == current_user.id', }, + // [rulings 6968686390, 6969143776 and 6973785798] The WHICH-ROWS half of + // the `sys_notification_preference` grant above. A row whose `user_id` is + // EMPTY is the organization's default for everyone (ADR-0118 D1), so a + // member must stay off it on every face. Two policies, the + // `sys_invitation_org_admin` shape (a `positions` domain belongs on the + // WIDENING policy, never on the narrowing one): + // - `sys_notification_preference_self` carries NO `positions`: it binds + // every principal that resolves the grant, so a role that normalizes + // to neither owner nor admin (`delegated_admin`) is narrowed to its + // own rows like an ordinary member. Its `check` is load-bearing: + // without one, the write check is the OR of every applicable `using` + // (`writeCheckPolicies`, case 2), with the `owner_only_writes` floor + // above taking part. A row the member created keeps + // `created_by == current_user.id`, so they could move it to another + // person or to the empty user, muting a topic for the whole + // organization. A declared `check` alone judges the row as written. + // - `sys_notification_preference_org_admin` widens organization owners + // and administrators back to every row (Layer 0, the tenant wall, + // AND-composes ahead of it), so their Setup grid lists, creates, + // edits and deletes as before. `delegated_admin` is deliberately + // absent. + // ⚠ The widener's `check` is `topic != null` ON PURPOSE, coupled to + // `topic` being a REQUIRED field with a `defaultValue`: the insert check + // judges the post-hook write image, where `id` is not yet assigned (so + // `id != null` would refuse every administrator create) but a defaulted + // `topic` always is. If `topic` ever becomes optional, an administrator's + // create is refused, never widened. + // `default-permission-sets.notification-preference.integration.test.ts` + // pins both policies per persona. + { + name: 'sys_notification_preference_self', + object: 'sys_notification_preference', + operation: 'all', + using: 'user_id == current_user.id', + check: 'user_id == current_user.id', + }, + { + name: 'sys_notification_preference_org_admin', + object: 'sys_notification_preference', + operation: 'all', + using: 'id != null', + check: 'topic != null', + positions: [BUILTIN_IDENTITY_ORG_OWNER, BUILTIN_IDENTITY_ORG_ADMIN], + }, { name: 'sys_api_key_self', object: 'sys_api_key', diff --git a/packages/plugins/plugin-security/src/objects/rbac-objects.test.ts b/packages/plugins/plugin-security/src/objects/rbac-objects.test.ts index 23f9d0f2b9b..a93a4e48ba2 100644 --- a/packages/plugins/plugin-security/src/objects/rbac-objects.test.ts +++ b/packages/plugins/plugin-security/src/objects/rbac-objects.test.ts @@ -221,6 +221,12 @@ describe('default permission sets', () => { // `shipped-sets-identity-default-row-scope.test.ts`, // `private-credential-row-scope.test.ts` and // `scim-projection-row-scope.test.ts`; this list only records presence. + // [ruling 6973785798] The notification-preference pair: `_self` binds every + // holder of the grant, and `_org_admin` is its owner/admin widener (the + // `sys_invitation_org_admin` shape). Behaviour per persona is pinned in + // `default-permission-sets.notification-preference.integration.test.ts`. + 'sys_notification_preference_org_admin', + 'sys_notification_preference_self', 'sys_notification_receipt_self', 'sys_oauth_application_self', 'sys_oauth_consent_self', diff --git a/packages/plugins/plugin-security/vitest.config.ts b/packages/plugins/plugin-security/vitest.config.ts index 9260f2164ee..42ee489d3fc 100644 --- a/packages/plugins/plugin-security/vitest.config.ts +++ b/packages/plugins/plugin-security/vitest.config.ts @@ -92,6 +92,14 @@ export default defineConfig({ find: /^@objectstack\/plugin-audit$/, replacement: path.resolve(__dirname, '../plugin-audit/src/index.ts'), }, + // `default-permission-sets.notification-preference.integration.test.ts` + // boots the real `sys_notification_preference` object and drives the + // real `PreferenceResolver` over what a member wrote: both are + // service-messaging's, read from this checkout for the reason above. + { + find: /^@objectstack\/service-messaging$/, + replacement: path.resolve(__dirname, '../../services/service-messaging/src/index.ts'), + }, { find: /^@objectstack\/driver-sqlite-wasm$/, replacement: path.resolve(__dirname, '../../drivers/driver-sqlite-wasm/src/index.ts'), diff --git a/packages/services/service-messaging/src/index.ts b/packages/services/service-messaging/src/index.ts index acbb4bab7ae..19a9b026fc6 100644 --- a/packages/services/service-messaging/src/index.ts +++ b/packages/services/service-messaging/src/index.ts @@ -52,6 +52,13 @@ export type { PreferenceContext, PreferenceTarget, QuietHours, + // The return types of `PreferenceResolver.effectiveFor` / + // `MessagingService.effectivePreferencesFor` (#34728). + EffectivePreferences, + EffectiveTopic, + EffectiveCell, + EffectiveSource, + EffectiveSetting, } from './preference-resolver.js'; // Plugin-facing inbox writes scoped to the authenticated caller (ADR-0030 L5) diff --git a/packages/services/service-messaging/src/messaging-route-ledger.conformance.test.ts b/packages/services/service-messaging/src/messaging-route-ledger.conformance.test.ts index 2e6909eccc9..255c00afdfd 100644 --- a/packages/services/service-messaging/src/messaging-route-ledger.conformance.test.ts +++ b/packages/services/service-messaging/src/messaging-route-ledger.conformance.test.ts @@ -2,8 +2,8 @@ /** * Messaging route-ledger conformance — the package-local guard every - * `*-route-ledger.ts` pairs with. `registerPreferenceOptionsRoutes` and - * `registerInAppMessageRoutes` are standalone, synchronous functions that call + * `*-route-ledger.ts` pairs with. `registerPreferenceOptionsRoutes`, + * `registerMyPreferencesRoutes` and `registerInAppMessageRoutes` are standalone, synchronous functions that call * `http.get` / `http.post` and touch neither argument's services before a * request arrives, so a capturing mock `IHttpServer` * enumerates its real surface (the seam the print and settings ledgers use), @@ -14,6 +14,7 @@ import { describe, it, expect, vi } from 'vitest'; import { registerPreferenceOptionsRoutes } from './preference-options-routes.js'; import { registerInAppMessageRoutes } from './in-app-message-routes.js'; +import { registerMyPreferencesRoutes } from './my-preferences-routes.js'; import { MESSAGING_ROUTE_LEDGER } from './messaging-route-ledger.js'; function createMockServer() { @@ -32,6 +33,7 @@ function createMockServer() { function enumerateMessagingRoutes(): Set { const server = createMockServer(); registerPreferenceOptionsRoutes(server as any, {} as any); + registerMyPreferencesRoutes(server as any, {} as any); registerInAppMessageRoutes(server as any, {} as any); const keys = new Set(); for (const verb of ['get', 'post', 'put', 'patch', 'delete'] as const) { diff --git a/packages/services/service-messaging/src/messaging-route-ledger.ts b/packages/services/service-messaging/src/messaging-route-ledger.ts index f438d90cf01..cfa180757fa 100644 --- a/packages/services/service-messaging/src/messaging-route-ledger.ts +++ b/packages/services/service-messaging/src/messaging-route-ledger.ts @@ -2,7 +2,8 @@ /** * Messaging route ledger — the audited disposition of every HTTP route - * `registerPreferenceOptionsRoutes` (`preference-options-routes.ts`) and + * `registerPreferenceOptionsRoutes` (`preference-options-routes.ts`), + * `registerMyPreferencesRoutes` (`my-preferences-routes.ts`) and * `registerInAppMessageRoutes` (`in-app-message-routes.ts`) mount. * * WHY THIS EXISTS. `MessagingServicePlugin` reaches for the `http-server` @@ -15,8 +16,9 @@ * (`/api/v1/notifications*`) are not here: the runtime dispatcher serves them, * and they are rows of its own ledger. * - * NOT SDK SURFACE. `@objectstack/client` expresses no method for either: the - * consumers are the console's notification preference and template forms, and + * NOT SDK SURFACE. `@objectstack/client` expresses no method for any: the + * consumers are the console's notification preference and template forms, the + * Account app's Notification Settings page, and * the Setup action "Send in-app message" (a same-origin `type: 'api'` action, * which the action doors also forward for an agent), over plain HTTP. That is * a `server-only` disposition. @@ -54,6 +56,8 @@ export interface MessagingRouteLedgerEntry { export const MESSAGING_ROUTE_LEDGER: readonly MessagingRouteLedgerEntry[] = [ { route: 'GET /api/v1/messaging/preference-options', family: 'messaging', disposition: 'server-only', note: 'the topics and channels a notification preference or template can name, for the console\'s pick-or-type inputs; any signed-in member, read-only' }, + { route: 'GET /api/v1/messaging/me/preferences', family: 'messaging', disposition: 'server-only', + note: 'the signed-in person\'s own effective notification preferences (topic x channel, digest, quiet hours, each with its source), for the Account app\'s Notification Settings page; any signed-in person, about themselves only, read-only' }, { route: 'POST /api/v1/messaging/in-app-messages', family: 'messaging', disposition: 'server-only', note: 'an organization administrator\'s in-app message to everyone in, or picked members of, their current organization; the target of the Setup action send_in_app_message on sys_notification' }, ]; diff --git a/packages/services/service-messaging/src/messaging-service-plugin.ts b/packages/services/service-messaging/src/messaging-service-plugin.ts index 59cdca46057..2668f97875c 100644 --- a/packages/services/service-messaging/src/messaging-service-plugin.ts +++ b/packages/services/service-messaging/src/messaging-service-plugin.ts @@ -7,6 +7,7 @@ import { installEgressGuard, type EgressGuard, type EgressPolicy } from '@object import type { IDataEngine, IHttpServer } from '@objectstack/spec/contracts'; import { PREFERENCE_OPTIONS_ROUTE, registerPreferenceOptionsRoutes } from './preference-options-routes.js'; import { IN_APP_MESSAGE_ROUTE, registerInAppMessageRoutes } from './in-app-message-routes.js'; +import { MY_PREFERENCES_ROUTE, registerMyPreferencesRoutes } from './my-preferences-routes.js'; import { resolveMessagingCaller, type MessagingCallerSources } from './messaging-request-caller.js'; import type { PreferenceOptionsEngine } from './preference-options.js'; import { MessagingService } from './messaging-service.js'; @@ -698,9 +699,10 @@ export class MessagingServicePlugin implements Plugin { const http = optional('http-server'); if (!http) { ctx.logger.warn( - `[messaging] no HTTP server is registered, so neither the preference options list (GET ${PREFERENCE_OPTIONS_ROUTE}) ` + - `nor the in-app message door (POST ${IN_APP_MESSAGE_ROUTE}) is mounted: the console draws notification topic ` + - 'and channel as plain text boxes, and the Setup action "Send in-app message" has nothing to call.', + `[messaging] no HTTP server is registered, so neither the preference options list (GET ${PREFERENCE_OPTIONS_ROUTE}), ` + + `the caller's own preferences (GET ${MY_PREFERENCES_ROUTE}) nor the in-app message door (POST ${IN_APP_MESSAGE_ROUTE}) ` + + 'is mounted: the console draws notification topic and channel as plain text boxes, the Account page Notification ' + + 'Settings has nothing to read, and the Setup action "Send in-app message" has nothing to call.', ); return; } @@ -714,8 +716,7 @@ export class MessagingServicePlugin implements Plugin { ? () => kernel.getServiceAsync!('tenancy') : undefined, }; - registerPreferenceOptionsRoutes(http, { - ...callerSources, + const optionSources = { knownChannels: () => service.getKnownChannels(), getData: () => getData() as unknown as PreferenceOptionsEngine | undefined, readFlows: async () => { @@ -724,8 +725,18 @@ export class MessagingServicePlugin implements Plugin { const raw = await protocol.getMetaItems({ type: 'flow' }); return Array.isArray(raw) ? raw : ((raw as { items?: unknown[] } | null)?.items ?? []); }, - }); + }; + registerPreferenceOptionsRoutes(http, { ...callerSources, ...optionSources }); ctx.logger.info(`[messaging] preference options list mounted at GET ${PREFERENCE_OPTIONS_ROUTE}`); + // [rulings 6968686390 and 6969143776] The caller's own effective + // preferences, decided by the same resolver `emit` filters with. + registerMyPreferencesRoutes(http, { + ...callerSources, + ...optionSources, + effectivePreferences: (userId, organizationId, topics, channels) => + service.effectivePreferencesFor(userId, organizationId, topics, channels), + }); + ctx.logger.info(`[messaging] caller's own preferences mounted at GET ${MY_PREFERENCES_ROUTE}`); registerInAppMessageRoutes(http, { resolveCaller: (req) => resolveMessagingCaller(req, callerSources), getMessaging: () => service, diff --git a/packages/services/service-messaging/src/messaging-service.ts b/packages/services/service-messaging/src/messaging-service.ts index c3fd322bf52..59fd3b3e4d7 100644 --- a/packages/services/service-messaging/src/messaging-service.ts +++ b/packages/services/service-messaging/src/messaging-service.ts @@ -10,7 +10,7 @@ import type { Notification, } from './channel.js'; import { RecipientResolver, isRoleAudience } from './recipient-resolver.js'; -import { PreferenceResolver, type PreferenceTarget } from './preference-resolver.js'; +import { PreferenceResolver, type EffectivePreferences, type PreferenceTarget } from './preference-resolver.js'; import type { INotificationOutbox } from './outbox.js'; import type { EnqueueHttpInput, @@ -729,6 +729,22 @@ export class MessagingService { return known; } + /** + * [rulings 6968686390 and 6969143776] One person's effective notification + * preferences, decided by the SAME resolver `emit` filters with (its + * `mandatoryTopics` included). Read by the caller-scoped door + * `GET /api/v1/messaging/me/preferences` (`my-preferences-routes.ts`); see + * `PreferenceResolver.effectiveFor` for what is read and what leaves. + */ + effectivePreferencesFor( + userId: string, + organizationId: string | undefined, + topics: readonly string[], + channels: readonly string[], + ): Promise { + return this.preferences.effectiveFor(userId, organizationId, topics, channels); + } + /* ------------------------------------------------------------------ */ /* Inbox read API (ADR-0030) — backs /api/v1/notifications */ /* */ diff --git a/packages/services/service-messaging/src/my-preferences-routes.integration.test.ts b/packages/services/service-messaging/src/my-preferences-routes.integration.test.ts new file mode 100644 index 00000000000..ee026fd9a58 --- /dev/null +++ b/packages/services/service-messaging/src/my-preferences-routes.integration.test.ts @@ -0,0 +1,385 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The caller's own notification preferences door, + * `GET /api/v1/messaging/me/preferences` (rulings 6968686390 and 6969143776), + * driven through the handler it mounts: the real platform resolver turns the + * request's bearer into an execution context, the topic list is the real + * preference options read, and the answer is the real `MessagingService`'s + * resolver over a real `ObjectQL` / `SqlDriver` (better-sqlite3) holding two + * organizations. + * + * - the answer is the person's EFFECTIVE preferences, cell by cell equal to + * what `emit`'s filter decides for them (one implementation); + * - each cell says where it comes from: their row, the organization's + * default, the built-in default, or a mandatory topic; + * - nothing of another person, or of another organization, leaves the door: + * no row of theirs, no id, and no value of theirs decides a cell; + * - anonymous, a held sign-in and any query parameter are refused by + * envelope before anything is read; a source that cannot be read is a + * fault, never an "everything on" answer. + */ + +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysNotification } from '@objectstack/platform-objects'; +import { ApiErrorSchema, envelopeViolations } from '@objectstack/spec/api'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { MY_PREFERENCES_ROUTE, registerMyPreferencesRoutes } from './my-preferences-routes.js'; +import { MessagingService } from './messaging-service.js'; +import { EFFECTIVE_PREFERENCES_READ_CAP } from './preference-resolver.js'; +import { NotificationPreference } from './objects/notification-preference.object.js'; +import type { MessagingChannel } from './channel.js'; + +const SYS_ORGANIZATION = { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: { type: 'text', label: 'Name' } } }; +const SYS_USER = { name: 'sys_user', label: 'User', managedBy: 'better-auth', fields: { name: { type: 'text', label: 'Name' }, email: { type: 'text', label: 'Email' } } }; +const silent: any = { debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return silent; } }; + +const ALICE = 'usr_alice'; +const BOB = 'usr_bob'; + +/** The sessions the fake auth service knows, by bearer token. */ +const SESSIONS: Record = { + alice: { userId: ALICE, organizationId: 'org_a' }, + nobody: { userId: 'usr_loner' }, + held: { userId: ALICE, organizationId: 'org_a', authGate: { code: 'PASSWORD_EXPIRED', message: 'Your password has expired.' } }, +}; + +const MEMBERSHIPS = [{ id: 'mem_alice', user_id: ALICE, organization_id: 'org_a', role: 'member' }]; + +/** Topics `security.*` are mandatory on this deployment. */ +const MANDATORY = ['security.']; + +let engine: ObjectQL | undefined; + +afterEach(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + engine = undefined; + vi.restoreAllMocks(); +}); + +const sys = (organization: string) => ({ context: { isSystem: true, tenantId: organization } as ExecutionContext }); + +async function boot(): Promise { + const ql = new ObjectQL({ logger: silent }); + ql.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), true); + await ql.init(); + for (const def of [SYS_ORGANIZATION, SYS_USER, SysNotification, NotificationPreference]) { + ql.registry.registerObject(def as any, '@objectstack/service-messaging'); + } + await ql.syncSchemas(); + ql.setTenancyPostureProvider(() => 'isolated'); + for (const id of ['org_a', 'org_b']) await ql.insert('sys_organization', { id, name: id }, { context: { isSystem: true } as ExecutionContext }); + for (const id of [ALICE, BOB]) await ql.insert('sys_user', { id, name: id, email: `${id}@example.test` }, { context: { isSystem: true } as ExecutionContext }); + engine = ql; + return ql; +} + +/** A preference row stored in `organization`, as the Setup grid or the person writes it. */ +async function pref(ql: ObjectQL, organization: string, row: Record): Promise { + return String((await ql.insert('sys_notification_preference', row, sys(organization))).id); +} + +/** `count` rows of `user`'s in `organization`, one per topic `PREFIX.N`, written in chunks the driver can bind. */ +async function bulk(ql: ObjectQL, organization: string, user: string, count: number, prefix = 'bulk'): Promise { + const rows = Array.from({ length: count }, (_, i) => ({ user_id: user, topic: `${prefix}.${i}`, channel: 'inbox', enabled: false })); + for (let i = 0; i < rows.length; i += 500) await ql.insert('sys_notification_preference', rows.slice(i, i + 500), sys(organization)); +} + +function channel(id: string): MessagingChannel { + return { id, send: async () => ({ status: 'sent' }) } as unknown as MessagingChannel; +} + +function door(ql: ObjectQL, opts: { failFlows?: boolean } = {}) { + const handlers = new Map Promise>(); + const http = { + get: vi.fn((path: string, handler: (req: unknown, res: unknown) => Promise) => handlers.set(`GET ${path}`, handler)), + post: vi.fn(), put: vi.fn(), patch: vi.fn(), delete: vi.fn(), use: vi.fn(), + }; + const auth = { + api: { + getSession: vi.fn(async (input: { headers: Headers }) => { + const bearer = input.headers.get('authorization')?.replace(/^Bearer /, ''); + const s = bearer ? SESSIONS[bearer] : undefined; + if (!s) return null; + return { + user: { id: s.userId, email: `${s.userId}@example.test`, ...(s.authGate ? { authGate: s.authGate } : {}) }, + session: { id: `ses_${bearer}`, userId: s.userId, activeOrganizationId: s.organizationId }, + }; + }), + }, + }; + // inbox mounted; email known, its transport absent. + const service = new MessagingService({ logger: silent, getData: () => ql as never, mandatoryTopics: MANDATORY }); + service.registerChannel(channel('inbox')); + service.registerChannelProvider('email', () => undefined); + + const find = vi.spyOn(ql, 'find'); + const effective = vi.spyOn(service, 'effectivePreferencesFor'); + registerMyPreferencesRoutes(http as never, { + getEngine: () => ({ + find: async (object: string, q: any = {}) => { + if (object !== 'sys_member') return []; + const rows = MEMBERSHIPS.filter((row) => Object.entries(q?.where ?? {}).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`membership double: ${k} is not implemented`); + return (row as Record)[k] === v; + })); + return typeof q?.limit === 'number' ? rows.slice(0, q.limit) : rows; + }, + }), + getAuth: () => auth as never, + tenancy: undefined, + knownChannels: () => service.getKnownChannels(), + getData: () => ql as never, + readFlows: async () => { + if (opts.failFlows) throw new Error('the flow list could not be read'); + return []; + }, + effectivePreferences: (userId, organizationId, topics, channels) => + service.effectivePreferencesFor(userId, organizationId, topics, channels), + }); + + async function call(o: { bearer?: string; query?: Record } = {}) { + const handler = handlers.get(`GET ${MY_PREFERENCES_ROUTE}`); + if (!handler) throw new Error('the door mounted no GET handler at its route'); + const answer: { status: number; body: any } = { status: 0, body: undefined }; + const res = { + status: (code: number) => { answer.status = code; return res; }, + json: (body: unknown) => { answer.body = body; }, + header: () => res, + send: () => undefined, + }; + await handler( + { params: {}, query: o.query ?? {}, headers: o.bearer ? { authorization: `Bearer ${o.bearer}` } : {}, method: 'GET', path: MY_PREFERENCES_ROUTE }, + res, + ); + expect(envelopeViolations(answer.body), JSON.stringify(answer.body)).toEqual([]); + return answer; + } + + return { call, find, effective, service }; +} + +function envelope(answer: { status: number; body: any }): [unknown, number] { + expect(answer.body?.success).toBe(false); + expect(ApiErrorSchema.safeParse(answer.body.error).success, JSON.stringify(answer.body.error)).toBe(true); + return [answer.body.error.code, answer.status]; +} + +const topicOf = (data: any, topic: string) => data.topics.find((t: any) => t.topic === topic); +const cellOf = (data: any, topic: string, ch: string) => topicOf(data, topic)?.channels.find((c: any) => c.channel === ch); + +describe('the caller\'s own preferences door — mounted', () => { + it('registers exactly one route: GET /api/v1/messaging/me/preferences', () => { + const http = { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn(), delete: vi.fn(), use: vi.fn() }; + registerMyPreferencesRoutes(http as never, {} as never); + expect(http.get.mock.calls.map((c) => c[0])).toEqual(['/api/v1/messaging/me/preferences']); + for (const verb of ['post', 'put', 'patch', 'delete', 'use'] as const) expect(http[verb]).not.toHaveBeenCalled(); + }); +}); + +describe('the caller\'s own preferences door — the effective matrix', () => { + it('answers each cell with its value and where it comes from, and the general settings', async () => { + const ql = await boot(); + // The organization's defaults. + await pref(ql, 'org_a', { topic: 'approval.reminder', channel: 'email', enabled: false }); + await pref(ql, 'org_a', { topic: 'approval.comment', channel: '*', enabled: false }); + await pref(ql, 'org_a', { topic: '*', channel: '*', enabled: true, digest: 'daily' }); + // Alice's own rows. + const ownReminder = await pref(ql, 'org_a', { user_id: ALICE, topic: 'approval.reminder', channel: 'inbox', enabled: false }); + const ownMandatory = await pref(ql, 'org_a', { user_id: ALICE, topic: 'security.access_upgrade', channel: 'email', enabled: false }); + const ownCustom = await pref(ql, 'org_a', { user_id: ALICE, topic: 'custom.only_mine', channel: 'slack', enabled: false }); + const d = door(ql); + + const answer = await d.call({ bearer: 'alice' }); + expect(answer.status).toBe(200); + const data = answer.body.data; + + // Columns: every known channel, then a channel only her own rows name. + expect(data.channels).toEqual([ + { channel: 'inbox', configured: true }, + { channel: 'email', configured: false }, + { channel: 'slack', configured: false }, + ]); + // Rows: `*` first, the catalogue, then a topic only her own rows name. + expect(data.topics[0]).toMatchObject({ topic: '*', wildcard: true, mandatory: false }); + expect(data.topics.at(-1)).toMatchObject({ topic: 'custom.only_mine', wildcard: false }); + for (const t of data.topics) expect(t.channels.map((c: any) => c.channel)).toEqual(['inbox', 'email', 'slack']); + + expect(cellOf(data, 'approval.reminder', 'inbox')).toEqual({ channel: 'inbox', enabled: false, source: 'own', ownRowId: ownReminder }); + expect(cellOf(data, 'approval.reminder', 'email')).toEqual({ channel: 'email', enabled: false, source: 'default' }); + expect(cellOf(data, 'approval.comment', 'inbox')).toEqual({ channel: 'inbox', enabled: false, source: 'default' }); + expect(cellOf(data, 'approval.requested', 'inbox')).toEqual({ channel: 'inbox', enabled: true, source: 'default' }); + expect(cellOf(data, 'custom.only_mine', 'slack')).toEqual({ channel: 'slack', enabled: false, source: 'own', ownRowId: ownCustom }); + // A mandatory topic is on, whatever her row says, and still offers her row's id. + expect(topicOf(data, 'security.access_upgrade').mandatory).toBe(true); + expect(cellOf(data, 'security.access_upgrade', 'email')).toEqual({ channel: 'email', enabled: true, source: 'mandatory', ownRowId: ownMandatory }); + + expect(data.general).toEqual({ + enabled: { value: true, source: 'default' }, + digest: { value: 'daily', source: 'default' }, + quietHours: { value: null, source: 'builtin' }, + }); + }); + + it("her own general (*, *) row carries her quiet hours, and decides every cell no more specific row of hers decides", async () => { + const ql = await boot(); + await pref(ql, 'org_a', { topic: 'approval.reminder', channel: 'email', enabled: false }); + await pref(ql, 'org_a', { topic: '*', channel: '*', enabled: true, digest: 'daily' }); + const ownGeneral = await pref(ql, 'org_a', { + user_id: ALICE, topic: '*', channel: '*', enabled: true, + quiet_hours: { tz: 'Europe/Berlin', start: '22:00', end: '07:00' }, + }); + const data = (await door(ql).call({ bearer: 'alice' })).body.data; + expect(data.general).toEqual({ + ownRowId: ownGeneral, + enabled: { value: true, source: 'own' }, + digest: { value: 'daily', source: 'default' }, + quietHours: { value: { tz: 'Europe/Berlin', start: '22:00', end: '07:00' }, source: 'own' }, + }); + // A person's rows come before the organization's in the lookup, so her (*, *) row + // decides even where the default names the exact topic and channel. + expect(cellOf(data, 'approval.reminder', 'email')).toEqual({ channel: 'email', enabled: true, source: 'own' }); + }); + + it('with no row at all every cell is the built-in default: on', async () => { + const ql = await boot(); + const data = (await door(ql).call({ bearer: 'alice' })).body.data; + for (const t of data.topics) { + for (const c of t.channels) expect(c).toEqual({ channel: c.channel, enabled: true, source: t.mandatory ? 'mandatory' : 'builtin' }); + } + expect(data.general).toEqual({ + enabled: { value: true, source: 'builtin' }, + digest: { value: 'none', source: 'builtin' }, + quietHours: { value: null, source: 'builtin' }, + }); + }); + + it('every cell equals what emit\'s filter decides for her (one implementation)', async () => { + const ql = await boot(); + await pref(ql, 'org_a', { topic: 'collab.mention', channel: 'email', enabled: false }); + await pref(ql, 'org_a', { topic: '*', channel: 'inbox', enabled: false }); + await pref(ql, 'org_a', { user_id: ALICE, topic: 'collab.mention', channel: '*', enabled: true }); + await pref(ql, 'org_a', { user_id: ALICE, topic: 'approval.requested', channel: 'email', enabled: false }); + await pref(ql, 'org_a', { user_id: ALICE, topic: 'security.access_upgrade', channel: '*', enabled: false }); + const d = door(ql); + const data = (await d.call({ bearer: 'alice' })).body.data; + const resolver = (d.service as any).preferences; + const channels = data.channels.map((c: any) => c.channel); + for (const t of data.topics) { + const [target] = await resolver.filter([ALICE], channels, { topic: t.topic, organizationId: 'org_a' }); + const accepted = target?.channels ?? []; + expect(t.channels.filter((c: any) => c.enabled).map((c: any) => c.channel), t.topic).toEqual(accepted); + } + }); + + it("nothing of another person or another organization leaves the door", async () => { + const ql = await boot(); + const bobs = await pref(ql, 'org_a', { user_id: BOB, topic: 'deal.won', channel: 'inbox', enabled: false }); + const bobsGeneral = await pref(ql, 'org_a', { user_id: BOB, topic: '*', channel: '*', enabled: false, digest: 'weekly' }); + await pref(ql, 'org_b', { topic: 'approval.requested', channel: 'inbox', enabled: false }); + await pref(ql, 'org_b', { topic: '*', channel: '*', enabled: true, digest: 'weekly' }); + await pref(ql, 'org_b', { user_id: ALICE, topic: 'approval.requested', channel: 'email', enabled: false }); + const d = door(ql); + const answer = await d.call({ bearer: 'alice' }); + const text = JSON.stringify(answer.body); + for (const leaked of [BOB, bobs, bobsGeneral, 'deal.won']) expect(text).not.toContain(leaked); + const data = answer.body.data; + expect(cellOf(data, 'approval.requested', 'inbox')).toEqual({ channel: 'inbox', enabled: true, source: 'builtin' }); + expect(cellOf(data, 'approval.requested', 'email')).toEqual({ channel: 'email', enabled: true, source: 'builtin' }); + expect(data.general.digest).toEqual({ value: 'none', source: 'builtin' }); + // Only what the answer needs is read, by equality under the caller's + // organization term: her own rows and the default's (both stored + // spellings of the empty reference). No other person's row is read. + const prefReads = d.find.mock.calls.filter((c) => c[0] === 'sys_notification_preference'); + expect(prefReads.map((c) => (c[1] as any).where)).toEqual([ + { organization_id: 'org_a', user_id: ALICE }, + { organization_id: 'org_a', user_id: null }, + { organization_id: 'org_a', user_id: '' }, + ]); + }); + + it("an organization with more rows than one read's cap still answers the caller's own row, with its id", async () => { + const ql = await boot(); + // Bob holds more rows than a read may answer on EACH side of Alice's + // row and the default's, so a capped read of the whole organization + // misses them in insertion order and in its reverse alike. + await bulk(ql, 'org_a', BOB, EFFECTIVE_PREFERENCES_READ_CAP + 1); + await pref(ql, 'org_a', { topic: 'approval.requested', channel: 'email', enabled: false }); + const alices = await pref(ql, 'org_a', { user_id: ALICE, topic: 'approval.requested', channel: 'inbox', enabled: false }); + await bulk(ql, 'org_a', BOB, EFFECTIVE_PREFERENCES_READ_CAP + 1, 'late'); + const answer = await door(ql).call({ bearer: 'alice' }); + expect(answer.status).toBe(200); + const data = answer.body.data; + expect(cellOf(data, 'approval.requested', 'inbox')).toEqual({ channel: 'inbox', enabled: false, source: 'own', ownRowId: alices }); + expect(cellOf(data, 'approval.requested', 'email')).toEqual({ channel: 'email', enabled: false, source: 'default' }); + expect(JSON.stringify(data)).not.toContain('bulk.'); + expect(JSON.stringify(data)).not.toContain('late.'); + }, 120_000); + + it('a caller with no organization reads no preference row, and is answered the built-in defaults', async () => { + const ql = await boot(); + await pref(ql, 'org_a', { topic: '*', channel: '*', enabled: false }); + const d = door(ql); + const answer = await d.call({ bearer: 'nobody' }); + expect(answer.status).toBe(200); + expect(d.find.mock.calls.filter((c) => c[0] === 'sys_notification_preference')).toEqual([]); + expect(answer.body.data.general.enabled).toEqual({ value: true, source: 'builtin' }); + }); +}); + +describe('the caller\'s own preferences door — refusals, before anything is read', () => { + it('refuses an anonymous caller 401 UNAUTHENTICATED', async () => { + const d = door(await boot()); + expect(envelope(await d.call())).toEqual(['UNAUTHENTICATED', 401]); + expect(d.effective).not.toHaveBeenCalled(); + }); + + it("refuses a held sign-in 403 with the policy's own code", async () => { + const d = door(await boot()); + expect(envelope(await d.call({ bearer: 'held' }))).toEqual(['PASSWORD_EXPIRED', 403]); + expect(d.effective).not.toHaveBeenCalled(); + }); + + it('refuses any query parameter 400 VALIDATION_ERROR naming it — there is no asking about another person', async () => { + const d = door(await boot()); + const answer = await d.call({ bearer: 'alice', query: { user: BOB } }); + expect(envelope(answer)).toEqual(['VALIDATION_ERROR', 400]); + expect(answer.body.error.message).toContain("'user'"); + expect(d.effective).not.toHaveBeenCalled(); + expect(d.find).not.toHaveBeenCalled(); + }); + + it('answers a source it cannot read 500 INTERNAL_ERROR, never an "everything on" answer', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined); + const d = door(await boot(), { failFlows: true }); + const answer = await d.call({ bearer: 'alice' }); + expect(envelope(answer)).toEqual(['INTERNAL_ERROR', 500]); + expect(answer.body.data).toBeUndefined(); + error.mockRestore(); + }); + + it("answers a read past the cap 500 INTERNAL_ERROR, never a partial matrix: the caller's own rows exceed it", async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined); + const ql = await boot(); + await bulk(ql, 'org_a', ALICE, EFFECTIVE_PREFERENCES_READ_CAP + 1); + const answer = await door(ql).call({ bearer: 'alice' }); + expect(envelope(answer)).toEqual(['INTERNAL_ERROR', 500]); + expect(answer.body.data).toBeUndefined(); + error.mockRestore(); + }, 120_000); + + it('answers a preference read that fails 500 INTERNAL_ERROR: the matrix never fails open', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined); + const ql = await boot(); + const d = door(ql); + d.find.mockImplementation(async (object: string) => { + if (object === 'sys_notification_preference') throw new Error('no such table'); + return []; + }); + const answer = await d.call({ bearer: 'alice' }); + expect(envelope(answer)).toEqual(['INTERNAL_ERROR', 500]); + error.mockRestore(); + }); +}); diff --git a/packages/services/service-messaging/src/my-preferences-routes.ts b/packages/services/service-messaging/src/my-preferences-routes.ts new file mode 100644 index 00000000000..9377b047646 --- /dev/null +++ b/packages/services/service-messaging/src/my-preferences-routes.ts @@ -0,0 +1,179 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { + ANONYMOUS_DENY_CODE, + ANONYMOUS_DENY_MESSAGE, + ANONYMOUS_DENY_STATUS, + evaluateAuthGate, + isApiKeyLifecycleRefusalError, + isAuthzStoreUnavailableError, + shouldDenyAnonymous, +} from '@objectstack/core'; +import type { ErrorCode } from '@objectstack/spec/api'; +import type { IHttpRequest, IHttpResponse, IHttpServer } from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { sendError, sendOk, sendServerFault } from '@objectstack/types'; +import { resolveMessagingCaller, type MessagingCallerSources } from './messaging-request-caller.js'; +import { PREFERENCE_WILDCARD, readPreferenceOptions, type PreferenceOptionsSources } from './preference-options.js'; +import type { EffectivePreferences, EffectiveTopic } from './preference-resolver.js'; + +/** + * The caller's own notification preferences door: + * `GET /api/v1/messaging/me/preferences` (rulings 6968686390 and 6969143776). + * It answers the signed-in person's EFFECTIVE preferences — what `emit` would + * do for them — so the Account app's Notification Settings page draws the + * same rules, from the one implementation (`PreferenceResolver.effectiveFor`). + * It reads and never writes: the page writes the person's own + * `sys_notification_preference` rows through the data door, as them, where + * `member_default`'s own-row policy decides which rows they may write. + * + * ## Who may ask — the posture of `GET /api/v1/messaging/preference-options` + * + * Any signed-in person, about themselves only: the route takes no user id, and + * the person is the caller the platform's one request-to-context composition + * resolves. In order, before anything is read: + * + * 1. **The caller** (`resolveRequestExecutionContext`, from the session or API + * key). A permission store that cannot be read, or an API key its + * lifecycle refuses, answers its own code and status, relayed as declared. + * 2. **A held sign-in** (ADR-0069): `403` with the authentication policy's + * own code. + * 3. **Anonymous** (ADR-0056 D2): `UNAUTHENTICATED` / `401`. + * 4. **The request**: the closed query set is EMPTY (AGENTS.md, route rule + * 5): a request carrying any parameter is refused `VALIDATION_ERROR` / + * `400` naming it, never ignored. ⛔ In particular there is no `user` + * parameter: nobody asks this door about another person. + * + * ## What the door answers + * + * `200` with {@link MyPreferences}: + * + * - `topics`: `*` (all topics) first, then every topic the organization's + * preference options list names (`readPreferenceOptions`: the platform's + * fixed topics, the flows' notify topics, the organization's stored + * topics), then any other topic the person's own rows name. Each topic says + * whether it is mandatory and, per channel, whether it is on and where that + * comes from: `own` (their row), `default` (the organization's default for + * everyone), `builtin` (no row: on), or `mandatory`. + * - `channels`: the column order, each known channel and whether the + * deployment can send on it now (`configured`). + * - `general`: their general on/off, digest and quiet hours, each with its + * source, and the id of their own `(*, *)` row when they have one. + * + * What it never answers: another person's row, or any row's id but the + * caller's own. The organization's defaults are read to compute the answer + * and surface only as `source: 'default'` on the caller's own cells (ruled). + * + * A source that cannot be read (the event table, the flow list, the + * preference rows) is a fault: `500` / `INTERNAL_ERROR` with this door's + * sentence, never a partial or "everything on" answer. So is a preference + * read that answers more rows than `EFFECTIVE_PREFERENCES_READ_CAP`. + * + * A caller with no organization is answered from no row at all (the + * built-in defaults). There `emit`, which reads without the organization term + * when it has none, can decide otherwise: this door never reads across + * organizations (ADR-0131 D1). + */ + +/** The route the door is mounted at. */ +export const MY_PREFERENCES_ROUTE = '/api/v1/messaging/me/preferences'; + +/** A channel column of the effective matrix. */ +export interface MyPreferencesChannel { + channel: string; + /** Whether the deployment can send on this channel right now. A channel only the caller's own rows name is `false`. */ + configured: boolean; +} + +/** The door's success payload. */ +export interface MyPreferences { + topics: EffectiveTopic[]; + channels: MyPreferencesChannel[]; + general: EffectivePreferences['general']; +} + +/** What the door is composed over — every member read when a request arrives. */ +export interface MyPreferencesRoutesDeps extends PreferenceOptionsSources, MessagingCallerSources { + /** The messaging service's effective read (`MessagingService.effectivePreferencesFor`). */ + effectivePreferences( + userId: string, + organizationId: string | undefined, + topics: readonly string[], + channels: readonly string[], + ): Promise; +} + +/** Mount the door on `http`. Nothing on `deps` is called until a request arrives. */ +export function registerMyPreferencesRoutes(http: IHttpServer, deps: MyPreferencesRoutesDeps): void { + http.get(MY_PREFERENCES_ROUTE, (req, res) => handleMyPreferences(req, res, deps)); +} + +/** Read the caller's effective preferences over the organization's options list. */ +export async function readMyPreferences( + deps: Pick & PreferenceOptionsSources, + userId: string, + organizationId: string | undefined, +): Promise { + const options = await readPreferenceOptions(deps, organizationId); + const topics = [PREFERENCE_WILDCARD, ...options.topics.filter((t) => !t.wildcard).map((t) => t.value)]; + const known = new Map(options.channels.filter((c) => !c.wildcard).map((c) => [c.value, c.configured])); + const effective = await deps.effectivePreferences(userId, organizationId, topics, [...known.keys()]); + return { + topics: effective.topics, + channels: effective.channels.map((channel) => ({ channel, configured: known.get(channel) ?? false })), + general: effective.general, + }; +} + +async function handleMyPreferences(req: IHttpRequest, res: IHttpResponse, deps: MyPreferencesRoutesDeps): Promise { + // ① The caller. + let context: ExecutionContext | undefined; + try { + context = await resolveMessagingCaller(req, deps); + } catch (err) { + if (isAuthzStoreUnavailableError(err) || isApiKeyLifecycleRefusalError(err)) { + sendError(res, err.status, err.code, err.message); + return; + } + sendServerFault(res, 500, 'INTERNAL_ERROR', 'The caller of this request could not be resolved.', err, { + method: 'GET', + path: MY_PREFERENCES_ROUTE, + }); + return; + } + + // ② A held sign-in. + const gate = evaluateAuthGate(context, ''); + if (gate) { + sendError(res, 403, gate.code as ErrorCode, gate.message); + return; + } + + // ③ Anonymous. + if (!context || !context.userId || shouldDenyAnonymous({ userId: context.userId, method: req.method })) { + sendError(res, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE); + return; + } + + // ④ The request: the closed query set is empty. + const query = Object.keys(req.query ?? {}); + if (query.length > 0) { + sendError( + res, + 400, + 'VALIDATION_ERROR', + `Your notification preferences take no query parameter, and this request carries ${query.map((q) => `'${q}'`).join(', ')}. ` + + 'Ask with no parameters: the answer is always every topic and channel, for the signed-in person only.', + ); + return; + } + + try { + sendOk(res, await readMyPreferences(deps, context.userId, context.tenantId)); + } catch (err) { + sendServerFault(res, 500, 'INTERNAL_ERROR', 'Your notification preferences could not be read.', err, { + method: 'GET', + path: MY_PREFERENCES_ROUTE, + }); + } +} diff --git a/packages/services/service-messaging/src/preference-resolver.ts b/packages/services/service-messaging/src/preference-resolver.ts index 32b9143fc21..5e9da8c84b1 100644 --- a/packages/services/service-messaging/src/preference-resolver.ts +++ b/packages/services/service-messaging/src/preference-resolver.ts @@ -66,6 +66,37 @@ export interface QuietHours { /** Digest cadence declared on a preference row (P3b-2). `none` ⇒ no batching. */ export type DigestCadence = 'daily' | 'weekly'; +/** + * [rulings 6968686390 and 6969143776] The context + * {@link PreferenceResolver.effectiveFor} reads the preference rows under: the + * explicit system opt-in. Kept apart from {@link FAN_OUT_SYSTEM_CONTEXT} on + * purpose, because what this read derives DOES reach a caller: the + * caller-scoped door answers a person whether each topic and channel is on + * and whether that comes from the organization's default — the ruled + * answer, which a member's own grant cannot read (the default rows are + * outside their row scope). The read is bounded by the `organization_id` + * term, never by the context; the rows themselves, and every row of another + * person, stay inside the method. + */ +export const EFFECTIVE_PREFERENCES_SYSTEM_CONTEXT = { isSystem: true } as const; + +/** + * The most rows one of {@link PreferenceResolver.effectiveFor}'s reads may + * answer. Each read is one person's rows, or the organization's default rows, + * so a real answer is far below it. A read that comes back with MORE is a + * fault, never a page: the rows past the cap could be the very rows that + * decide a cell (or the row id the page edits), and a short answer would be + * drawn as `default` / `builtin` and invite a duplicate row. + */ +export const EFFECTIVE_PREFERENCES_READ_CAP = 10000; + +/** + * The stored spellings of the admin-global default's empty `user_id` that an + * equality read can name — `null` and `''` (see {@link isGlobalDefaultUser}; + * `undefined` is never stored). + */ +const GLOBAL_DEFAULT_USER_SPELLINGS: readonly (string | null)[] = [null, '']; + /** The topic / channel wildcard. ⛔ Not a user: see {@link GLOBAL_USER}. */ const WILDCARD = '*'; @@ -154,20 +185,7 @@ export class PreferenceResolver { return all(); } - // Index rows by `${user}|${topic}|${channel}` → { enabled, quietHours }. - const recipientSet = new Set(recipients); - const index = new Map(); - for (const r of rows) { - const user = isGlobalDefaultUser(r.user_id) ? GLOBAL_USER : String(r.user_id); - if (user !== GLOBAL_USER && !recipientSet.has(user)) continue; // ignore unrelated users - const topic = String(r.topic ?? WILDCARD); - const channel = String(r.channel ?? WILDCARD); - index.set(`${user}|${topic}|${channel}`, { - enabled: asBool(r.enabled), - quietHours: parseQuietHours(r.quiet_hours), - digest: parseDigest(r.digest), - }); - } + const index = indexRows(rows, new Set(recipients)); const nowMs = ctx.now ?? Date.now(); const critical = ctx.severity === 'critical'; @@ -185,13 +203,13 @@ export class PreferenceResolver { let notBefore: number | undefined; let digest: { window: string } | undefined; if (!critical) { - const cadence = this.resolveDigest(index, recipient, ctx.topic); + const cadence = this.resolveDigest(index, recipient, ctx.topic)?.digest; if (cadence) { - const d = digestDeferral(cadence, nowMs, this.resolveQuietHours(index, recipient, ctx.topic)?.tz); + const d = digestDeferral(cadence, nowMs, this.resolveQuietHours(index, recipient, ctx.topic)?.quietHours?.tz); notBefore = d.notBefore; digest = { window: d.window }; } else { - const qh = this.resolveQuietHours(index, recipient, ctx.topic); + const qh = this.resolveQuietHours(index, recipient, ctx.topic)?.quietHours; notBefore = qh ? quietHoursDeferral(qh, nowMs) : undefined; } } @@ -239,11 +257,11 @@ export class PreferenceResolver { * row (`(user, *, *)` or `(user, topic, *)`) — quiet hours are a per-person, * channel-agnostic setting. Most-specific user/topic wins. */ - private resolveQuietHours(index: Map, user: string, topic: string): QuietHours | undefined { + private resolveQuietHours(index: Map, user: string, topic: string): PrefRowLite | undefined { for (const u of [user, GLOBAL_USER]) { for (const t of [topic, WILDCARD]) { const hit = index.get(`${u}|${t}|${WILDCARD}`); - if (hit?.quietHours) return hit.quietHours; + if (hit?.quietHours) return hit; } } return undefined; @@ -254,23 +272,211 @@ export class PreferenceResolver { * channel-wildcard row (`(user, *, *)` or `(user, topic, *)`) — batching is a * per-person, channel-agnostic setting. Most-specific user/topic wins. */ - private resolveDigest(index: Map, user: string, topic: string): DigestCadence | undefined { + private resolveDigest(index: Map, user: string, topic: string): PrefRowLite | undefined { for (const u of [user, GLOBAL_USER]) { for (const t of [topic, WILDCARD]) { const hit = index.get(`${u}|${t}|${WILDCARD}`); - if (hit?.digest) return hit.digest; + if (hit?.digest) return hit; } } return undefined; } + + /** + * [rulings 6968686390 and 6969143776] One person's EFFECTIVE preferences — + * what `filter` would decide for them — for every `topic` × `channel` + * named, with where each answer comes from. The caller-scoped door + * `GET /api/v1/messaging/me/preferences` answers this, so the Account + * page draws the same rules `emit` applies, from this one implementation. + * + * The topics and channels are the ones asked for, then any other the + * person's own rows name. Per cell: a mandatory topic is on (`mandatory`); otherwise the + * most-specific row wins exactly as in {@link filter} — the person's own + * (`own`), the organization's default (`default`), or none and the + * built-in default on (`builtin`). Digest and quiet hours are the + * person's general ones: the channel-wildcard lookup {@link filter} runs, + * for the `*` topic. + * + * ⚠️ The rows are read under the system opt-in, and only the rows the + * answer needs: the person's own and the organization's default, each by + * equality on `user_id` under the `organization_id` term (one read for + * `userId`, one per stored spelling of the empty default reference — the + * equality shape {@link loadRows} uses, so no driver needs IN). No other + * person's row is read. What leaves is the computed answer for `userId`, + * plus the ids of `userId`'s OWN rows (`ownRowId`, the rows the person + * edits). A read that answers more than + * {@link EFFECTIVE_PREFERENCES_READ_CAP} rows rejects (a fault, never a + * partial answer). No organization ⇒ no row is read: every stored row + * carries one (ADR-0131 D1), and a read without the term would cross + * organizations. + * + * Unlike {@link filter} this does not fail open: a read that fails + * rejects, and the door answers the fault — a page must never draw + * "everything on" because a read failed. + */ + async effectiveFor( + userId: string, + organizationId: string | undefined, + topics: readonly string[], + channels: readonly string[], + ): Promise { + const data = this.opts.getData(); + const rows: Record[] = []; + if (data && organizationId) { + const reads = await Promise.all( + [userId, ...GLOBAL_DEFAULT_USER_SPELLINGS].map((user) => + data.find( + this.objectName, + { where: { organization_id: organizationId, user_id: user }, limit: EFFECTIVE_PREFERENCES_READ_CAP + 1 }, + { context: EFFECTIVE_PREFERENCES_SYSTEM_CONTEXT }, + ), + ), + ); + for (const read of reads) { + const found = (read ?? []) as Record[]; + if (found.length > EFFECTIVE_PREFERENCES_READ_CAP) { + throw new Error( + `${this.objectName} answered more than ${EFFECTIVE_PREFERENCES_READ_CAP} rows for one person or for the default; ` + + 'refusing to compute a partial answer.', + ); + } + rows.push(...found); + } + } + const index = indexRows(rows, new Set([userId])); + // The person's own rows name topics and channels too: a topic only + // they ever muted, a channel id a plugin no longer registers. Each is + // listed after the ones asked for, so their own row is never hidden. + const ownKeys = [...index.values()].filter((row) => row.user === userId); + const listed = (asked: readonly string[], ownValues: string[]): string[] => { + const seen = new Set(asked); + return [...asked, ...[...new Set(ownValues)].filter((v) => !seen.has(v)).sort()]; + }; + const allTopics = listed(topics, ownKeys.map((row) => row.topic)); + const allChannels = listed(channels, ownKeys.map((row) => row.channel).filter((c) => c !== WILDCARD)); + const own = (topic: string, channel: string): { ownRowId?: string } => { + const id = index.get(`${userId}|${topic}|${channel}`)?.id; + return id ? { ownRowId: id } : {}; + }; + const sourceOf = (hit: PrefRowLite | undefined): EffectiveSource => + !hit ? 'builtin' : hit.user === GLOBAL_USER ? 'default' : 'own'; + + const effectiveTopics = allTopics.map((topic): EffectiveTopic => { + const mandatory = this.isMandatory(topic); + return { + topic, + wildcard: topic === WILDCARD, + mandatory, + channels: allChannels.map((channel): EffectiveCell => { + if (mandatory) return { channel, enabled: true, source: 'mandatory', ...own(topic, channel) }; + const hit = this.resolveRow(index, userId, topic, channel); + return { channel, enabled: hit?.enabled ?? true, source: sourceOf(hit), ...own(topic, channel) }; + }), + }; + }); + + const general = this.resolveRow(index, userId, WILDCARD, WILDCARD); + const digest = this.resolveDigest(index, userId, WILDCARD); + const quietHours = this.resolveQuietHours(index, userId, WILDCARD); + return { + topics: effectiveTopics, + channels: allChannels, + general: { + ...own(WILDCARD, WILDCARD), + enabled: { value: general?.enabled ?? true, source: sourceOf(general) }, + digest: { value: digest?.digest ?? 'none', source: sourceOf(digest) }, + quietHours: { value: quietHours?.quietHours ?? null, source: sourceOf(quietHours) }, + }, + }; + } +} + +/** Where an effective answer comes from (see {@link PreferenceResolver.effectiveFor}). */ +export type EffectiveSource = 'own' | 'default' | 'builtin'; + +/** One channel of one topic, as {@link PreferenceResolver.effectiveFor} answers it. */ +export interface EffectiveCell { + channel: string; + /** Whether a notification of this topic is delivered on this channel. */ + enabled: boolean; + /** `mandatory` when the topic bypasses preferences; otherwise the row that decided. */ + source: EffectiveSource | 'mandatory'; + /** The person's own row for exactly this (topic, channel), when they have one. */ + ownRowId?: string; +} + +/** One topic's row of the effective matrix. */ +export interface EffectiveTopic { + topic: string; + /** `true` on the `*` (all topics) row alone. */ + wildcard: boolean; + /** The topic bypasses preferences: every channel is on, and no row changes that. */ + mandatory: boolean; + channels: EffectiveCell[]; +} + +/** An effective value and the row that decided it. */ +export interface EffectiveSetting { + value: T; + source: EffectiveSource; +} + +/** One person's effective preferences (see {@link PreferenceResolver.effectiveFor}). */ +export interface EffectivePreferences { + /** The topics asked for, then any other topic the person's own rows name. */ + topics: EffectiveTopic[]; + /** The channels asked for, then any other channel the person's own rows name; the column order of every topic. */ + channels: string[]; + /** + * The person's general settings, decided on the `(*, *)` lookup: whether + * notifications reach them at all where nothing more specific says, their + * digest cadence and their quiet hours. `ownRowId` is their own `(*, *)` + * row, the one a digest or quiet-hours change is written to. + */ + general: { + ownRowId?: string; + enabled: EffectiveSetting; + digest: EffectiveSetting<'none' | DigestCadence>; + quietHours: EffectiveSetting; + }; } interface PrefRowLite { + /** The row's id, as stored. */ + id?: string; + /** The index key's parts: a user id or {@link GLOBAL_USER}, the topic and the channel. */ + user: string; + topic: string; + channel: string; enabled: boolean; quietHours?: QuietHours; digest?: DigestCadence; } +/** + * Index rows by `${user}|${topic}|${channel}`. Rows of a user outside `users` + * are dropped; the admin-global default's rows are always kept. + */ +function indexRows(rows: readonly Record[], users: ReadonlySet): Map { + const index = new Map(); + for (const r of rows) { + const user = isGlobalDefaultUser(r.user_id) ? GLOBAL_USER : String(r.user_id); + if (user !== GLOBAL_USER && !users.has(user)) continue; // ignore unrelated users + const topic = String(r.topic ?? WILDCARD); + const channel = String(r.channel ?? WILDCARD); + index.set(`${user}|${topic}|${channel}`, { + ...(r.id != null ? { id: String(r.id) } : {}), + user, + topic, + channel, + enabled: asBool(r.enabled), + quietHours: parseQuietHours(r.quiet_hours), + digest: parseDigest(r.digest), + }); + } + return index; +} + function asBool(v: unknown): boolean { return v === true || v === 1 || v === '1' || v === 'true'; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 04ee821bb13..a0dc9c04fb7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2233,6 +2233,9 @@ importers: '@objectstack/service-i18n': specifier: workspace:* version: link:../../services/service-i18n + '@objectstack/service-messaging': + specifier: workspace:* + version: link:../../services/service-messaging '@types/node': specifier: ^26.6.5 version: 26.6.5 diff --git a/scripts/check-route-envelope.mjs b/scripts/check-route-envelope.mjs index 833040cdcb8..6c2e71403a8 100644 --- a/scripts/check-route-envelope.mjs +++ b/scripts/check-route-envelope.mjs @@ -292,6 +292,13 @@ const MODULES = { // the same PR that created the module. 'packages/services/service-messaging/src/in-app-message-routes.ts': { responses: 0, ok: 0, err: 0 }, + // [#34728] The caller's own notification preferences door + // (`GET /api/v1/messaging/me/preferences`), mounted by `MessagingServicePlugin` + // beside the preference options door. Every body it answers is written by the + // shared pair (`sendOk` / `sendError` / `sendServerFault`), so it builds none + // itself. Declared in the same PR that created the module. + 'packages/services/service-messaging/src/my-preferences-routes.ts': { responses: 0, ok: 0, err: 0 }, + // [#30209] The shareable-objects door (`GET /api/v1/sharing/shareable-objects`), // mounted by `SharingServicePlugin` straight on `IHttpServer`. Every body it // answers is written by the shared pair (`sendOk` / `sendError` / diff --git a/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.test.tsx b/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.test.tsx new file mode 100644 index 00000000000..b4e6b8ef6f0 --- /dev/null +++ b/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.test.tsx @@ -0,0 +1,256 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The account app's Notification Settings page (objectstack#34728): it draws + * the door's matrix as the door answered it, a switch writes the person's own + * row through the data door and the page reads the door again, a mandatory + * topic cannot be switched, and a failed read says so instead of drawing a + * guess. + * + * `t` echoes the KEY, so the assertions read which string the page asked for. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import type { ReactNode } from 'react'; + +vi.mock('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ t: (key: string) => `«${key}»`, language: 'en' }), +})); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'alice' } }), +})); + +import { AdapterCtx, SchemaRendererProvider } from '@object-ui/react'; +import { builtInLocales } from '@object-ui/i18n/locales'; +import { NotificationSettingsPage } from './NotificationSettingsPage'; +import { MY_PREFERENCES_URL } from './myPreferences'; +import { getAppComponent } from '../../services/componentRegistry'; +// The registry check below loads every built-in page, which reaches the +// metadata admin's dynamic `@objectstack/lint` import: pay that load at +// collection, never inside a test's clocked window. +import '@objectstack/lint'; +import '../../services/builtinComponents'; + +type General = { digest: { value: string; source: string }; quietHours: { value: unknown; source: string } }; + +const BUILTIN_GENERAL: General = { digest: { value: 'none', source: 'builtin' }, quietHours: { value: null, source: 'builtin' } }; + +function answer(taskEnabled: boolean, taskRow?: string, general: General = BUILTIN_GENERAL) { + return { + data: { + topics: [ + { topic: '*', wildcard: true, mandatory: false, channels: [{ channel: 'email', enabled: true, source: 'builtin' }, { channel: 'slack', enabled: true, source: 'builtin' }] }, + { topic: 'security.login', wildcard: false, mandatory: true, channels: [{ channel: 'email', enabled: true, source: 'mandatory' }, { channel: 'slack', enabled: true, source: 'mandatory' }] }, + { + topic: 'task.assigned', + wildcard: false, + mandatory: false, + channels: [ + { channel: 'email', enabled: taskEnabled, source: taskRow ? 'own' : 'default', ...(taskRow ? { ownRowId: taskRow } : {}) }, + { channel: 'slack', enabled: true, source: 'builtin' }, + ], + }, + ], + channels: [{ channel: 'email', configured: true }, { channel: 'slack', configured: false }], + general: { + enabled: { value: true, source: 'builtin' }, + ...general, + }, + }, + }; +} + +function host(apiFetch: ReturnType, adapter: { create: ReturnType; update: ReturnType }) { + return ({ children }: { children: ReactNode }) => ( + + + {children} + + + ); +} + +const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status }); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe('NotificationSettingsPage', () => { + it('draws the matrix the door answered, sources and unconfigured channels included', async () => { + const apiFetch = vi.fn(async () => json(answer(false))); + const adapter = { create: vi.fn(), update: vi.fn() }; + render(, { wrapper: host(apiFetch, adapter) }); + + const cell = await screen.findByTestId('notification-settings-cell-task.assigned-email'); + expect(apiFetch).toHaveBeenCalledWith(MY_PREFERENCES_URL, expect.anything()); + expect(cell).toHaveAttribute('aria-checked', 'false'); + expect(screen.getByTestId('notification-settings-topic-task.assigned')).toHaveTextContent('«notificationSettings.sourceDefault»'); + expect(screen.getByTestId('notification-settings-channel-slack')).toHaveTextContent('«notificationSettings.notConfigured»'); + expect(screen.getByTestId('notification-settings-channel-email')).not.toHaveTextContent('«notificationSettings.notConfigured»'); + expect(screen.getByTestId('notification-settings-topic-*')).toHaveTextContent('«notificationSettings.allTopics»'); + expect(screen.getByTestId('notification-settings-general-warning')).toBeInTheDocument(); + }); + + it('a mandatory topic is always delivered and cannot be switched off', async () => { + const apiFetch = vi.fn(async () => json(answer(false))); + const adapter = { create: vi.fn(), update: vi.fn() }; + render(, { wrapper: host(apiFetch, adapter) }); + + const cell = await screen.findByTestId('notification-settings-cell-security.login-email'); + expect(cell).toBeDisabled(); + expect(screen.getByTestId('notification-settings-topic-security.login')).toHaveTextContent('«notificationSettings.alwaysDelivered»'); + }); + + it('switching a cell creates the person’s own row, then draws the door’s new answer', async () => { + const apiFetch = vi.fn().mockResolvedValueOnce(json(answer(false))).mockResolvedValueOnce(json(answer(true, 'row-new'))); + const adapter = { create: vi.fn(async () => ({ id: 'row-new' })), update: vi.fn() }; + render(, { wrapper: host(apiFetch, adapter) }); + + fireEvent.click(await screen.findByTestId('notification-settings-cell-task.assigned-email')); + await waitFor(() => + expect(screen.getByTestId('notification-settings-cell-task.assigned-email')).toHaveAttribute('aria-checked', 'true'), + ); + expect(adapter.create).toHaveBeenCalledWith('sys_notification_preference', { + user_id: 'alice', + topic: 'task.assigned', + channel: 'email', + enabled: true, + }); + expect(adapter.update).not.toHaveBeenCalled(); + expect(apiFetch).toHaveBeenCalledTimes(2); + expect(screen.getByTestId('notification-settings-topic-task.assigned')).toHaveTextContent('«notificationSettings.sourceOwn»'); + }); + + it('switching a cell the person already set updates their row', async () => { + const apiFetch = vi.fn().mockResolvedValueOnce(json(answer(false, 'row-1'))).mockResolvedValueOnce(json(answer(true, 'row-1'))); + const adapter = { create: vi.fn(), update: vi.fn(async () => ({})) }; + render(, { wrapper: host(apiFetch, adapter) }); + + fireEvent.click(await screen.findByTestId('notification-settings-cell-task.assigned-email')); + await waitFor(() => expect(adapter.update).toHaveBeenCalledWith('sys_notification_preference', 'row-1', { enabled: true })); + expect(adapter.create).not.toHaveBeenCalled(); + }); + + it('changing the digest writes the person’s own (*, *) row', async () => { + const apiFetch = vi.fn().mockResolvedValue(json(answer(false))); + const adapter = { create: vi.fn(async () => ({})), update: vi.fn() }; + render(, { wrapper: host(apiFetch, adapter) }); + + fireEvent.change(await screen.findByTestId('notification-settings-digest'), { target: { value: 'weekly' } }); + await waitFor(() => + expect(adapter.create).toHaveBeenCalledWith('sys_notification_preference', { + user_id: 'alice', + topic: '*', + channel: '*', + enabled: true, + digest: 'weekly', + }), + ); + }); + + it('an organization digest in force: "No digest" is not offered, and the digest shows where it comes from', async () => { + const orgDaily: General = { ...BUILTIN_GENERAL, digest: { value: 'daily', source: 'default' } }; + const apiFetch = vi.fn().mockResolvedValue(json(answer(false, undefined, orgDaily))); + const adapter = { create: vi.fn(async () => ({})), update: vi.fn() }; + render(, { wrapper: host(apiFetch, adapter) }); + + const select = (await screen.findByTestId('notification-settings-digest')) as HTMLSelectElement; + expect(select.value).toBe('daily'); + expect([...select.options].map((o) => o.value)).toEqual(['daily', 'weekly']); + expect(screen.getByTestId('notification-settings-digest-source')).toHaveTextContent('«notificationSettings.sourceDefault»'); + expect(screen.getByTestId('notification-settings-digest-no-off')).toHaveTextContent('«notificationSettings.digestNoOff»'); + }); + + it('with no digest in force, "No digest" is the current value and the hint is not shown', async () => { + const apiFetch = vi.fn().mockResolvedValue(json(answer(false))); + render(, { wrapper: host(apiFetch, { create: vi.fn(), update: vi.fn() }) }); + + const select = (await screen.findByTestId('notification-settings-digest')) as HTMLSelectElement; + expect(select.value).toBe('none'); + expect(screen.getByTestId('notification-settings-digest-source')).toHaveTextContent('«notificationSettings.sourceBuiltin»'); + expect(screen.queryByTestId('notification-settings-digest-no-off')).toBeNull(); + }); + + it('organization quiet hours in force: clearing the window cannot be saved, a complete window can', async () => { + const orgQuiet: General = { ...BUILTIN_GENERAL, quietHours: { value: { start: '22:00', end: '07:00' }, source: 'default' } }; + const apiFetch = vi.fn().mockResolvedValue(json(answer(false, undefined, orgQuiet))); + const adapter = { create: vi.fn(async () => ({})), update: vi.fn() }; + render(, { wrapper: host(apiFetch, adapter) }); + + const start = await screen.findByTestId('quiet-hours-start'); + const end = screen.getByTestId('quiet-hours-end'); + const save = screen.getByTestId('notification-settings-quiet-hours-save'); + expect(screen.getByTestId('notification-settings-quiet-hours-source')).toHaveTextContent('«notificationSettings.sourceDefault»'); + + fireEvent.change(start, { target: { value: '' } }); + fireEvent.change(end, { target: { value: '' } }); + expect(await screen.findByTestId('notification-settings-quiet-hours-no-clear')).toHaveTextContent('«notificationSettings.quietHoursNoClear»'); + expect(save).toBeDisabled(); + fireEvent.click(save); + expect(adapter.create).not.toHaveBeenCalled(); + + fireEvent.change(start, { target: { value: '23:00' } }); + fireEvent.change(end, { target: { value: '06:00' } }); + await waitFor(() => expect(save).not.toBeDisabled()); + expect(screen.queryByTestId('notification-settings-quiet-hours-no-clear')).toBeNull(); + fireEvent.click(save); + await waitFor(() => + expect(adapter.create).toHaveBeenCalledWith('sys_notification_preference', { + user_id: 'alice', + topic: '*', + channel: '*', + enabled: true, + quiet_hours: { start: '23:00', end: '06:00' }, + }), + ); + }); + + it('a refused write is shown, and the matrix keeps what is in force', async () => { + const apiFetch = vi.fn().mockResolvedValue(json(answer(false))); + const adapter = { create: vi.fn(async () => Promise.reject(new Error('Permission denied'))), update: vi.fn() }; + render(, { wrapper: host(apiFetch, adapter) }); + + fireEvent.click(await screen.findByTestId('notification-settings-cell-task.assigned-email')); + expect(await screen.findByTestId('notification-settings-save-failed')).toHaveTextContent('«notificationSettings.saveFailed»'); + expect(screen.getByTestId('notification-settings-cell-task.assigned-email')).toHaveAttribute('aria-checked', 'false'); + }); + + it('a failed read says so and draws no matrix', async () => { + const apiFetch = vi.fn(async () => json({}, 500)); + const adapter = { create: vi.fn(), update: vi.fn() }; + render(, { wrapper: host(apiFetch, adapter) }); + + expect(await screen.findByTestId('notification-settings-load-failed')).toHaveTextContent('«notificationSettings.loadFailed»'); + expect(screen.queryByTestId('notification-settings-matrix')).toBeNull(); + }); + + it('every built-in locale carries the same keys and placeholders', () => { + type Pack = { notificationSettings?: Record }; + const en = (builtInLocales as Record).en.notificationSettings!; + const placeholders = (s: string) => (s.match(/\{\{\w+\}\}/g) ?? []).sort(); + for (const [locale, pack] of Object.entries(builtInLocales as Record)) { + expect(Object.keys(pack.notificationSettings ?? {}).sort(), locale).toEqual(Object.keys(en).sort()); + for (const key of Object.keys(en)) { + expect(placeholders(pack.notificationSettings![key]), `${locale}.notificationSettings.${key}`).toEqual(placeholders(en[key])); + } + } + }); +}); + +describe('the account app names the page', () => { + it('account:notification_settings resolves to this page', async () => { + const entry = getAppComponent('account:notification_settings'); + expect(entry).toMatchObject({ ref: 'account:notification_settings', source: '@object-ui/app-shell' }); + const apiFetch = vi.fn(async () => json(answer(false))); + const Registered = entry!.component; + render(, { wrapper: host(apiFetch, { create: vi.fn(), update: vi.fn() }) }); + expect(await screen.findByTestId('notification-settings-matrix')).toBeInTheDocument(); + }); +}); diff --git a/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.tsx b/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.tsx new file mode 100644 index 00000000000..89c88e7d7ea --- /dev/null +++ b/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.tsx @@ -0,0 +1,314 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The account app's Notification Settings page (`account:notification_settings`): + * the signed-in person's own notification preferences, as a topic × channel + * matrix of switches plus their general digest and quiet hours. + * + * It draws what the messaging service's caller-scoped door answers + * (`GET /api/v1/messaging/me/preferences`) and computes nothing itself: each + * cell says whether it is on and whether that is the person's own setting, the + * organization's default, the built-in default or a mandatory topic. Every + * change writes the person's own `sys_notification_preference` row through the + * data door, as them, and then reads the door again, so what the page shows is + * always what is in force. See `myPreferences.ts`. + * + * Digest and quiet hours offer only values that take effect when saved + * (`digestChoices`, `quietHoursSaveable`): the resolver reads a stored + * `'none'` or an empty window as "no opinion" and falls through to the + * organization's default, so neither is ever offered as a way to turn + * something off. + * + * Channels are columns as the door lists them, so a channel the deployment + * adds later (Slack, …) appears without a change here; a channel the + * deployment cannot send on yet says so in its header. + */ + +import { Suspense, useCallback, useContext, useEffect, useState } from 'react'; +import { BellRing } from 'lucide-react'; +import { useAuth } from '@object-ui/auth'; +import { + Alert, + AlertDescription, + Badge, + Button, + Card, + CardContent, + Label, + Switch, + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from '@object-ui/components'; +import { getLazyFieldWidget } from '@object-ui/fields'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { SchemaRendererContext, useAdapter } from '@object-ui/react'; +import { PageHeader } from '../../layout/PageHeader.js'; +import { + cellWrite, + digestChoices, + quietHoursSaveable, + generalWrite, + loadMyPreferences, + PREFERENCE_WILDCARD, + sendPreferenceWrite, + type DigestCadence, + type MyPreferences, + type PreferenceCell, + type PreferenceSource, + type PreferenceTopic, + type PreferenceWrite, + type QuietHoursWindow, +} from './myPreferences.js'; + +type Load = { readonly state: 'loading' } | { readonly state: 'failed' } | { readonly state: 'read'; readonly prefs: MyPreferences }; + +const DIGEST_KEY: Record = { + none: 'notificationSettings.digestNone', + daily: 'notificationSettings.digestDaily', + weekly: 'notificationSettings.digestWeekly', +}; + +/** The quiet-hours face of `@object-ui/fields`, resolved once (lazy: render inside `Suspense`). */ +const QuietHours = getLazyFieldWidget('quiet-hours'); + +const SOURCE_KEY: Record = { + own: 'notificationSettings.sourceOwn', + default: 'notificationSettings.sourceDefault', + builtin: 'notificationSettings.sourceBuiltin', + mandatory: 'notificationSettings.sourceMandatory', +}; + +function errorText(err: unknown): string { + return err instanceof Error && err.message ? err.message : String(err); +} + +export function NotificationSettingsPage() { + const { t } = useObjectTranslation(); + const { user } = useAuth(); + const adapter = useAdapter(); + const apiFetch = useContext(SchemaRendererContext)?.apiFetch; + const [load, setLoad] = useState({ state: 'loading' }); + const [saving, setSaving] = useState(false); + const [saveError, setSaveError] = useState(null); + const [quietDraft, setQuietDraft] = useState(undefined); + + const read = useCallback(async () => { + // The host's authenticated fetch only: a host that supplies none cannot read the door. + if (!apiFetch) throw new Error('no authenticated fetch'); + return loadMyPreferences(apiFetch); + }, [apiFetch]); + + useEffect(() => { + let cancelled = false; + read() + .then((prefs) => { + if (!cancelled) setLoad({ state: 'read', prefs }); + }) + .catch(() => { + if (!cancelled) setLoad({ state: 'failed' }); + }); + return () => { + cancelled = true; + }; + }, [read]); + + const apply = useCallback( + async (write: PreferenceWrite | null) => { + if (!write || !adapter) return; + setSaving(true); + setSaveError(null); + try { + await sendPreferenceWrite(adapter, write); + setLoad({ state: 'read', prefs: await read() }); + setQuietDraft(undefined); + } catch (err) { + setSaveError(errorText(err)); + } finally { + setSaving(false); + } + }, + [adapter, read], + ); + + const header = ( +