From dd34877ccabcb872788e040c355a706aa9f96216 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 04:43:32 +0000 Subject: [PATCH 01/11] feat(security): member_default grants a member their own notification preferences The own-row policy declares the write check and binds ordinary members only (rulings 6968686390 and 6969143776); an integration suite pins the member and administrator readings and the effect on the next emit. Claude-Session: https://claude.ai/code/session_01JQwxbXh6yuW2pNn3XoA8sB Co-authored-by: Claude --- packages/plugins/plugin-security/package.json | 1 + ...otification-preference.integration.test.ts | 294 ++++++++++++++++++ .../src/objects/default-permission-sets.ts | 36 +++ .../plugins/plugin-security/vitest.config.ts | 8 + pnpm-lock.yaml | 3 + 5 files changed, 342 insertions(+) create mode 100644 packages/plugins/plugin-security/src/default-permission-sets.notification-preference.integration.test.ts diff --git a/packages/plugins/plugin-security/package.json b/packages/plugins/plugin-security/package.json index e18cc28dbcb..64af1e92305 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..a6d95dc724c --- /dev/null +++ b/packages/plugins/plugin-security/src/default-permission-sets.notification-preference.integration.test.ts @@ -0,0 +1,294 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [rulings 6968686390 and 6969143776] A member reads and writes their OWN + * notification preferences, and nothing else; an organization administrator + * keeps the Setup grid exactly as it was. + * + * `member_default` names `sys_notification_preference` (read, create, edit, no + * delete) and declares `sys_notification_preference_self`: row scope + * `user_id == current_user.id`, the write check `user_id == current_user.id`, + * `positions: ['org_member']`. This suite drives that line and that policy, 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 the + * member's `org_member` and the administrator's `org_admin` are the + * resolver's answer, not this file's; + * - the REAL `PreferenceResolver`, the filter `emit` runs, over what the + * member wrote. + * + * The readings pinned are the ones os-dev-report 6968930571 measured. Each key + * of the policy is load-bearing: without the `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; without `positions`, the + * administrator's grid narrows to their own rows. Both ablations are in the + * pull request that landed this suite. + * + * 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 and an organization administrator. */ +const ALICE = 'usr_npref_alice'; +const BOB = 'usr_npref_bob'; +const CAROL = 'usr_npref_carol'; + +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: a member reads and writes only their own notification preferences', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + const as: Record = {}; + /** Rows seeded as the system: the organization default, and one row each for bob and alice. */ + 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' }; + for (const userId of [ALICE, BOB, CAROL]) { + 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 alice's name an administrator wrote: its `created_by` is not hers. + seeded.aliceByAdmin = String((await insert(SYS, { user_id: ALICE, topic: 'approval.comment', channel: 'inbox', enabled: true })).id); + + for (const [name, userId] of [['alice', ALICE], ['carol', CAROL]] as const) as[name] = 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 makes alice an ordinary member and carol an organization administrator', () => { + expect(as.alice.positions).toEqual(expect.arrayContaining(['org_member', 'everyone'])); + expect(as.carol.positions).toEqual(expect.arrayContaining(['org_admin', 'everyone'])); + expect(as.carol.positions).not.toContain('org_member'); + }); + + describe('a member, on their own rows', () => { + it('creates a preference in their own name and lists only their own rows', async () => { + const row = await insert(as.alice, { user_id: ALICE, topic: 'approval.requested', channel: 'email', enabled: false }); + expect((await storedById(String(row.id)))?.user_id).toBe(ALICE); + const mine = await list(as.alice); + expect(mine.every((r) => r.user_id === ALICE)).toBe(true); + expect(keys(mine)).toEqual(expect.arrayContaining([`${ALICE}|approval.requested|email`, `${ALICE}|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.alice, { user_id: ALICE, topic: 'approval.returned', channel: '*', enabled: true })).id); + await update(as.alice, own, { enabled: false, digest: 'daily' }); + expect(await storedById(own)).toMatchObject({ user_id: ALICE, enabled: false, digest: 'daily' }); + await update(as.alice, seeded.aliceByAdmin, { enabled: false }); + expect((await storedById(seeded.aliceByAdmin))?.enabled).toBe(false); + }); + + it('deletes nothing: the grant carries no delete bit', async () => { + const own = String((await insert(as.alice, { user_id: ALICE, topic: 'approval.escalated', channel: 'email', enabled: false })).id); + expect(await refusal(() => ql.delete(OBJ, { where: { id: own }, context: as.alice } as never))).toEqual({ + status: 403, + code: 'PERMISSION_DENIED', + }); + expect(await storedById(own)).toBeDefined(); + }); + }); + + describe('a member 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.${label.length}`; + expect(await refusal(() => insert(as.alice, { ...data, topic, channel: '*', enabled: false }))).toEqual({ + status: 403, + code: 'PERMISSION_DENIED', + }); + expect(await stored({ topic })).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.alice, { user_id: ALICE, topic: `move.${String(to)}`, channel: '*', enabled: false })).id); + expect((await storedById(own))?.created_by).toBe(ALICE); + expect(await refusal(() => update(as.alice, own, { user_id: to }))).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + expect((await storedById(own))?.user_id).toBe(ALICE); + }); + } + + it("refuses moving a row an administrator wrote in their name: 403 PERMISSION_DENIED", async () => { + expect(await refusal(() => update(as.alice, seeded.aliceByAdmin, { user_id: BOB }))).toEqual({ + status: 403, + code: 'PERMISSION_DENIED', + }); + expect((await storedById(seeded.aliceByAdmin))?.user_id).toBe(ALICE); + }); + + it("neither reads nor edits the organization's default or another member's row: 404 RECORD_NOT_FOUND", async () => { + const visible = (await list(as.alice)).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.alice, id, { enabled: true }))).toEqual({ status: 404, code: 'RECORD_NOT_FOUND' }); + expect((await storedById(id))?.enabled).toBe(false); + } + }); + }); + + describe('an organization administrator keeps the Setup grid', () => { + it("lists every row of the organization, the default and each member's", async () => { + const ids = (await list(as.carol)).map((r) => String(r.id)); + expect(ids).toEqual(expect.arrayContaining([seeded.everyone, seeded.bob, seeded.aliceByAdmin])); + }); + + it("creates and edits the organization's default, and edits another person's row", async () => { + const created = await insert(as.carol, { topic: 'system.upgrade_impact', channel: 'email', enabled: false }); + expect((await storedById(String(created.id)))?.user_id ?? null).toBeNull(); + await update(as.carol, seeded.everyone, { digest: 'weekly' }); + expect((await storedById(seeded.everyone))?.digest).toBe('weekly'); + await update(as.carol, seeded.bob, { enabled: true }); + expect((await storedById(seeded.bob))?.enabled).toBe(true); + await update(as.carol, seeded.bob, { enabled: false }); + }); + }); + + 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..f2444a76d90 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 and 6969143776] 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 ordinary members only; read that policy 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,32 @@ const baseDefaultPermissionSets: PermissionSet[] = [ operation: 'all', using: 'user_id == current_user.id', }, + // [rulings 6968686390 and 6969143776] 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 + // this policy must keep a member off it on every face, and its two + // added keys are each load-bearing (measured, os-dev-report 6968930571): + // - `check`: without it the write check is the OR of every applicable + // `using` (`writeCheckPolicies`, case 2), and the `owner_only_writes` + // floor above takes 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. + // - `positions: ['org_member']`: this set resolves for organization + // administrators too (the `everyone` anchor), and a policy here + // would narrow their Setup grid to their own rows. Administrators + // keep listing every row, writing the default and editing another + // person's row. + // `default-permission-sets.notification-preference.integration.test.ts` + // pins both, and the administrator's access beside them. + { + name: 'sys_notification_preference_self', + object: 'sys_notification_preference', + operation: 'all', + using: 'user_id == current_user.id', + check: 'user_id == current_user.id', + positions: ['org_member'], + }, { name: 'sys_api_key_self', object: 'sys_api_key', 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/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 From c25d6ae9000bfabc02bf4107205f736331849b0f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 04:52:01 +0000 Subject: [PATCH 02/11] feat(messaging): GET /api/v1/messaging/me/preferences answers the caller's effective preferences The resolver emit filters with computes, per topic and channel, whether it is on and where that comes from, plus the general digest and quiet hours; the Account app gains the Notification Settings entry. Claude-Session: https://claude.ai/code/session_01JQwxbXh6yuW2pNn3XoA8sB Co-authored-by: Claude --- .../platform-objects/src/apps/account.app.ts | 17 + .../src/apps/translations/ar.ts | 1 + .../src/apps/translations/de.ts | 1 + .../src/apps/translations/en.ts | 1 + .../src/apps/translations/es-ES.ts | 1 + .../src/apps/translations/fr.ts | 1 + .../src/apps/translations/ja-JP.ts | 1 + .../src/apps/translations/ko.ts | 1 + .../src/apps/translations/pt-BR.ts | 1 + .../src/apps/translations/ru.ts | 1 + .../src/apps/translations/zh-CN.ts | 1 + .../src/apps/translations/zh-Hant.ts | 1 + .../src/objects/rbac-objects.test.ts | 1 + ...messaging-route-ledger.conformance.test.ts | 6 +- .../src/messaging-route-ledger.ts | 10 +- .../src/messaging-service-plugin.ts | 23 +- .../src/messaging-service.ts | 18 +- .../my-preferences-routes.integration.test.ts | 345 ++++++++++++++++++ .../src/my-preferences-routes.ts | 173 +++++++++ .../src/preference-resolver.ts | 211 +++++++++-- 20 files changed, 782 insertions(+), 33 deletions(-) create mode 100644 packages/services/service-messaging/src/my-preferences-routes.integration.test.ts create mode 100644 packages/services/service-messaging/src/my-preferences-routes.ts 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/src/objects/rbac-objects.test.ts b/packages/plugins/plugin-security/src/objects/rbac-objects.test.ts index 23f9d0f2b9b..919d648ecab 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,7 @@ 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. + 'sys_notification_preference_self', 'sys_notification_receipt_self', 'sys_oauth_application_self', 'sys_oauth_consent_self', 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..2a6fd86a182 --- /dev/null +++ b/packages/services/service-messaging/src/my-preferences-routes.integration.test.ts @@ -0,0 +1,345 @@ +// 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 { 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); +} + +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' }); + // The read was the caller's organization's, by its term. + const prefReads = d.find.mock.calls.filter((c) => c[0] === 'sys_notification_preference'); + expect(prefReads.length).toBe(1); + expect((prefReads[0][1] as any).where).toEqual({ organization_id: 'org_a' }); + }); + + 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 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..99c1bd768f4 --- /dev/null +++ b/packages/services/service-messaging/src/my-preferences-routes.ts @@ -0,0 +1,173 @@ +// 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. + */ + +/** 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..4ceedb0392b 100644 --- a/packages/services/service-messaging/src/preference-resolver.ts +++ b/packages/services/service-messaging/src/preference-resolver.ts @@ -66,6 +66,20 @@ 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 topic / channel wildcard. ⛔ Not a user: see {@link GLOBAL_USER}. */ const WILDCARD = '*'; @@ -154,20 +168,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 +186,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 +240,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 +255,191 @@ 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 fan-out's system opt-in, as + * {@link filter} reads them: they include other people's rows, which are + * dropped here and never leave this method. What leaves is the computed + * answer for `userId`, plus the ids of `userId`'s OWN rows (`ownRowId`, + * the rows the person edits). 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 = data && organizationId + ? ((await data.find( + this.objectName, + { where: { organization_id: organizationId }, limit: 10000 }, + { context: EFFECTIVE_PREFERENCES_SYSTEM_CONTEXT }, + )) ?? []) + : []; + 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'; } From f109986e98a15df9173cdfa313a8f2f36d3b2c3c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 05:01:15 +0000 Subject: [PATCH 03/11] feat(account): Notification Settings page over the caller-scoped preferences door The account app's `account:notification_settings` component: the signed-in person's topic x channel matrix, digest and quiet hours, read from GET /api/v1/messaging/me/preferences through the host's authenticated fetch, written as their own sys_notification_preference rows through the data door, then read again. Locale keys in every built-in pack, and the changeset. Claude-Session: https://claude.ai/code/session_01JQwxbXh6yuW2pNn3XoA8sB Co-authored-by: Claude --- .changeset/34728-notification-settings.md | 29 ++ .../NotificationSettingsPage.test.tsx | 196 ++++++++++++ .../NotificationSettingsPage.tsx | 286 ++++++++++++++++++ .../myPreferences.test.ts | 121 ++++++++ .../notification-settings/myPreferences.ts | 209 +++++++++++++ .../src/services/builtinComponents.tsx | 16 + ui/packages/i18n/src/locales/ar.ts | 25 ++ ui/packages/i18n/src/locales/de.ts | 25 ++ ui/packages/i18n/src/locales/en.ts | 25 ++ ui/packages/i18n/src/locales/es.ts | 25 ++ ui/packages/i18n/src/locales/fr.ts | 25 ++ ui/packages/i18n/src/locales/ja.ts | 25 ++ ui/packages/i18n/src/locales/ko.ts | 25 ++ ui/packages/i18n/src/locales/pt-BR.ts | 25 ++ ui/packages/i18n/src/locales/ru.ts | 25 ++ ui/packages/i18n/src/locales/zh-Hans.ts | 25 ++ ui/packages/i18n/src/locales/zh-Hant.ts | 25 ++ 17 files changed, 1132 insertions(+) create mode 100644 .changeset/34728-notification-settings.md create mode 100644 ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.test.tsx create mode 100644 ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.tsx create mode 100644 ui/packages/app-shell/src/console/notification-settings/myPreferences.test.ts create mode 100644 ui/packages/app-shell/src/console/notification-settings/myPreferences.ts diff --git a/.changeset/34728-notification-settings.md b/.changeset/34728-notification-settings.md new file mode 100644 index 00000000000..44aab172bd0 --- /dev/null +++ b/.changeset/34728-notification-settings.md @@ -0,0 +1,29 @@ +--- +'@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 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` now grants ordinary members (`positions: ['org_member']`) read, create and edit on the object, with no delete. The policy has two parts: + - the row scope is `user_id == current_user.id`; + - the write check is the same expression, so the row as written must still be your own. + + A member's 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. A member lists only their own rows. +- **Administrators are unchanged.** They still list every row, create and edit the organization default, and edit another person's row in the Setup grid. + +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/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..fde40bd15fd --- /dev/null +++ b/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.test.tsx @@ -0,0 +1,196 @@ +// 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'; + +function answer(taskEnabled: boolean, taskRow?: string) { + 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' }, + digest: { value: 'none', source: 'builtin' }, + quietHours: { value: null, source: 'builtin' }, + }, + }, + }; +} + +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('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..9a0500c8cfd --- /dev/null +++ b/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.tsx @@ -0,0 +1,286 @@ +// 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`. + * + * 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, + 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 DIGESTS: readonly DigestCadence[] = ['none', 'daily', 'weekly']; + +const DIGEST_KEY: Record = { + none: 'notificationSettings.digestNone', + daily: 'notificationSettings.digestDaily', + weekly: 'notificationSettings.digestWeekly', +}; + +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 = ( +