diff --git a/.changeset/39641-notification-topic-registry.md b/.changeset/39641-notification-topic-registry.md new file mode 100644 index 00000000000..486635167a8 --- /dev/null +++ b/.changeset/39641-notification-topic-registry.md @@ -0,0 +1,24 @@ +--- +'@objectstack/service-messaging': patch +'@objectstack/core': patch +'@objectstack/plugin-audit': patch +'@objectstack/plugin-security': patch +'@objectstack/plugin-auth': patch +'@objectstack/plugin-approvals': patch +--- + +feat(service-messaging): each sending feature registers its notification topics, and the preference options door serves each one's name, when it fires and its variables + +Clause-②: yes (widening) +Metadata-protocol: none + +`GET /api/v1/messaging/preference-options` now serves, for each topic a sending feature registered, a `label`, a one-sentence `description` of when it fires and, where the sender declared them, its `variables`. The topic pickers in the Console still show the bare topic id: drawing the name and description is a later Console change (#39651). Which platform topics are offered now follows composition: a platform topic is offered only where the feature that sends it is composed and registers it, and four topics are newly offered on a fresh boot (`approval.approved`, `approval.rejected`, `approval.abandoned`, `org.announcement`). `GET /api/v1/messaging/me/preferences` lists each person's own notification preferences from the same topics, so a person's own list gains and loses the same topics by composition. A typed or stored topic value is still accepted everywhere: the list is a suggestion, not a closed set. + +- `@objectstack/service-messaging`: `MessagingService.registerNotificationTopics(descriptors)` registers the topics a feature sends: each descriptor carries the topic id, a `label` and a `description` (each an English `fallback`, with an optional catalog `key`), and optional `variables`. A malformed descriptor, or a topic another feature already registered, is refused with a `TypeError` and nothing from the call is kept. `GET /api/v1/messaging/preference-options` serves each registered topic with its `label` and `description`, and its `variables` only when the descriptor declares them (absent means not declared yet, so the generic variables apply; `[]` means the sender declared none), rendered in the caller's language where the catalog has an entry; topics that come only from flows or stored notifications carry none of the three. No sender declares variables yet. The registry is the door's only platform source: the fixed topic list the package kept (`PLATFORM_NOTIFICATION_TOPICS`, never exported) is deleted, and every topic it offered is now registered by the feature that sends it. The plugin registers the Slack link removal notice (`messaging.slack_link_removed`), the in-app message door's topic (`org.announcement`, now offered on a fresh boot) and core's Change Owner notice. The new types `NotificationTopicDescriptor`, `NotificationTopicText` and `NotificationTopicVariable` are exported. +- `@objectstack/core`: exports `CHANGE_OWNER_NOTIFICATION_TOPIC_DESCRIPTOR`, the Change Owner topic's name and description. +- `@objectstack/plugin-audit`: registers `collab.mention` and `collab.reply`. +- `@objectstack/plugin-security`: registers `security.access_upgrade` and `system.upgrade_impact`. +- `@objectstack/plugin-auth`: registers `auth.phone_otp` and `auth.phone_invite`. +- `@objectstack/plugin-approvals`: registers the fifteen topics the approval service sends, among them `approval.approved`, `approval.rejected` and `approval.abandoned`, which no topic picker offered before. + +Each sender registers when the messaging service offers the member. A refusal is logged at `warn` without stopping the boot, and the registry keeps nothing from the refused call: those topics are then not offered at all (one collision drops every topic of that sender's call) unless a flow names one or the organization has stored one. The notices themselves are sent exactly as before. diff --git a/packages/core/src/security/change-record-owner.ts b/packages/core/src/security/change-record-owner.ts index ce2ccba0d0c..e31f1b11188 100644 --- a/packages/core/src/security/change-record-owner.ts +++ b/packages/core/src/security/change-record-owner.ts @@ -185,6 +185,21 @@ async function writeOwner(engine: ChangeOwnerEngine, object: string, id: string, /** The notification topic a notified new owner receives. */ export const CHANGE_OWNER_NOTIFICATION_TOPIC = 'record.owner_changed'; +/** + * {@link CHANGE_OWNER_NOTIFICATION_TOPIC} as the messaging service's topic + * registry describes it to an administrator picking a topic: the name and the + * one sentence on when it fires, each a `{ fallback }` text. This package + * cannot depend on `@objectstack/service-messaging` (which depends on it), so + * `MessagingServicePlugin` registers this constant beside its own topics, the + * way its bundle already carries {@link CHANGE_OWNER_NOTIFICATION_TEXT}; that + * call is where its shape is checked against the registry's descriptor. + */ +export const CHANGE_OWNER_NOTIFICATION_TOPIC_DESCRIPTOR = { + topic: CHANGE_OWNER_NOTIFICATION_TOPIC, + label: { fallback: 'Record handed to a new owner' }, + description: { fallback: 'Someone used Change Owner to make a person the owner of one or more records; the new owner is told.' }, +} as const; + /** * The new owner's notification title, as catalog ids of the `messages` face and * their English text. The notice rides `keyedText`, so the messaging service diff --git a/packages/core/src/security/index.ts b/packages/core/src/security/index.ts index 2ded64d5c8c..9a58cd698ad 100644 --- a/packages/core/src/security/index.ts +++ b/packages/core/src/security/index.ts @@ -710,6 +710,7 @@ export { CHANGE_OWNER_DISABLED, CHANGE_OWNER_NOTIFICATION_TEXT, CHANGE_OWNER_NOTIFICATION_TOPIC, + CHANGE_OWNER_NOTIFICATION_TOPIC_DESCRIPTOR, changeOwnerOffReason, changeOwnerOffRefusal, changeRecordOwner, diff --git a/packages/plugins/plugin-approvals/src/approval-notification-topics.test.ts b/packages/plugins/plugin-approvals/src/approval-notification-topics.test.ts new file mode 100644 index 00000000000..d07ec52e3c5 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-notification-topics.test.ts @@ -0,0 +1,229 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#39641] The approval plugin describes every topic its service sends to the + * messaging service's topic registry, and the preference options door + * (`GET /api/v1/messaging/preference-options`) serves each with its name and + * when it fires (ruling 7409753977 on #39412: each sending feature registers + * its own topics). + * + * - the real composition: the real `MessagingServicePlugin` and the real + * `ApprovalsServicePlugin` over a real `ObjectQL` (better-sqlite3), the + * door driven through the handler the messaging plugin mounts; every + * approval topic is offered with label and description, among them the + * three no list offered before (`approval.approved`, `approval.rejected`, + * `approval.abandoned`) and every approval topic the deleted fixed list + * offered; + * - the registered set is the set the plugin sends: every `'approval.*'` + * topic literal of this package's source is registered, so a new notice + * cannot ship undescribed; + * - feature detection: a messaging service without the member is no error, + * and a refusal is one `warn` that leaves the plugin's start alone. + */ + +import { readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { MessagingServicePlugin } from '@objectstack/service-messaging'; +import { ApprovalsServicePlugin } from './approvals-plugin.js'; +import { APPROVAL_NOTIFICATION_TOPICS, registerApprovalNotificationTopics } from './approval-notification-topics.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { SysApprovalToken } from './sys-approval-token.object.js'; + +const ROUTE = '/api/v1/messaging/preference-options'; +const USER = 'usr_alice'; +const ORG = 'org_a'; + +/** + * The approval topics `PLATFORM_NOTIFICATION_TOPICS` of service-messaging + * offered before the list was deleted (#39641), as it read at origin/main + * 18028154: each must still be offered once the approval plugin is composed. + */ +const FORMERLY_LISTED = [ + 'approval.comment', + 'approval.escalated', + 'approval.flow_not_continued', + 'approval.ooo_skipped', + 'approval.ooo_substituted', + 'approval.reassigned', + 'approval.reminder', + 'approval.request_info', + 'approval.requested', + 'approval.returned', + 'approval.sla_breached', + 'approval.status_mirror_refused', +]; + +/** The three topics the plugin sent that no list offered. */ +const NEVER_LISTED = ['approval.approved', 'approval.rejected', 'approval.abandoned']; + +let stop: (() => Promise) | undefined; + +afterEach(async () => { + try { await stop?.(); } catch { /* noop */ } + stop = undefined; +}); + +async function compose(): Promise<{ topics: () => Promise>> }> { + const engine = new ObjectQL(); + engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), true); + await engine.init(); + const registered = new Set(); + const register = (def: any) => { + registered.add(def.name); + engine.registry.registerObject(def, 'approvals-topics-test', 'approvals-topics-test'); + }; + for (const def of [SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { + register(def); + } + // The door's caller resolution reads the authorization store: alice holds a + // membership in her session's organization, and no position or permission + // set. Every other read goes to the real engine. + const objectql = new Proxy(engine, { + get(target, prop, receiver) { + if (prop !== 'find') { + const value = Reflect.get(target, prop, receiver); + return typeof value === 'function' ? value.bind(target) : value; + } + return async (object: string, q: any = {}, ...rest: unknown[]) => { + if (object === 'sys_member') { + const where = q?.where ?? {}; + return where.user_id === USER && where.organization_id === ORG + ? [{ id: 'mem_alice', user_id: USER, organization_id: ORG, role: 'member' }] + : []; + } + if (!registered.has(object)) return []; + return (target.find as any)(object, q, ...rest); + }; + }, + }); + + const handlers = new Map Promise>(); + const mount = (verb: string) => (path: string, handler: (req: unknown, res: unknown) => Promise) => { + handlers.set(`${verb} ${path}`, handler); + }; + const logger: any = { info() {}, debug() {}, warn() {}, error() {}, child: () => logger }; + const services: Record = { + objectql, + data: objectql, + manifest: { register: (m: any) => { for (const def of m.objects ?? []) register(def); } }, + 'http-server': { get: mount('GET'), post: mount('POST'), put: mount('PUT'), delete: mount('DELETE'), patch: mount('PATCH'), use() {} }, + auth: { + api: { + getSession: async ({ headers }: { headers: Headers }) => headers.get('authorization') === 'Bearer alice' + ? { user: { id: USER, email: `${USER}@example.test` }, session: { id: 'ses_alice', userId: USER, activeOrganizationId: ORG } } + : null, + }, + }, + }; + const readyHooks: Array<() => Promise | void> = []; + const ctx: any = { + getService: (name: string) => { + if (!(name in services)) throw new Error(`[Kernel] Service '${name}' not found`); + return services[name]; + }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + hook: (event: string, fn: () => Promise | void) => { if (event === 'kernel:ready') readyHooks.push(fn); }, + logger, + }; + + const messagingPlugin = new MessagingServicePlugin({ reliableDelivery: false }); + await messagingPlugin.init(ctx); + await engine.syncSchemas(); + await new ApprovalsServicePlugin().start(ctx); + for (const fn of readyHooks) await fn(); + stop = async () => { + await messagingPlugin.destroy?.(); + await engine.destroy(); + }; + + return { + topics: async () => { + const handler = handlers.get(`GET ${ROUTE}`); + if (!handler) throw new Error(`no GET ${ROUTE}`); + const out: { status: number; body: any } = { status: 0, body: undefined }; + const res = { + status: (c: number) => { out.status = c; return res; }, + json: (b: unknown) => { out.body = b; }, + header: () => res, + send: () => undefined, + }; + await handler({ params: {}, query: {}, headers: { authorization: 'Bearer alice' }, method: 'GET', path: ROUTE }, res); + expect(out.status, JSON.stringify(out.body)).toBe(200); + return out.body.data.topics as Array>; + }, + }; +} + +describe('the approval topics on the preference options door (#39641)', () => { + it('offers every approval topic with its label and description, the three never listed among them', async () => { + const c = await compose(); + const byValue = new Map((await c.topics()).map((t) => [t.value, t])); + for (const d of APPROVAL_NOTIFICATION_TOPICS) { + expect(byValue.get(d.topic), d.topic).toEqual({ + value: d.topic, + wildcard: false, + sources: ['platform'], + label: d.label.fallback, + description: d.description.fallback, + }); + } + for (const id of [...NEVER_LISTED, ...FORMERLY_LISTED]) { + expect(byValue.get(id), id).toMatchObject({ sources: ['platform'], label: expect.any(String), description: expect.any(String) }); + } + }); +}); + +describe('the registered topics are the topics the plugin sends', () => { + /** Every non-test source file of this package's `src/`. */ + function sourceFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((e) => { + const path = join(dir, e.name); + if (e.isDirectory()) return sourceFiles(path); + return e.name.endsWith('.ts') && !/\.(test|spec)\.ts$|\.testkit\.ts$/.test(e.name) ? [path] : []; + }); + } + + it("registers every 'approval.*' topic literal of the package source, and nothing else", () => { + const sent = new Set(); + for (const file of sourceFiles(fileURLToPath(new URL('.', import.meta.url)))) { + if (file.endsWith('approval-notification-topics.ts')) continue; + for (const m of readFileSync(file, 'utf8').matchAll(/'(approval\.[a-z_]+)'/g)) sent.add(m[1]); + } + // CONTROL: the scan reads the senders (the decision notices are in approval-service.ts). + expect(sent.has('approval.approved')).toBe(true); + expect(APPROVAL_NOTIFICATION_TOPICS.map((d) => d.topic)).toEqual([...sent].sort()); + }); +}); + +describe('registerApprovalNotificationTopics — feature-detected, a refusal is one warn', () => { + it('a messaging service without the member is no error and registers nothing', () => { + const warn = vi.fn(); + expect(registerApprovalNotificationTopics({ emit: async () => undefined }, { warn })).toBe(false); + expect(registerApprovalNotificationTopics(undefined, { warn })).toBe(false); + expect(warn).not.toHaveBeenCalled(); + }); + + it('a refused registration is logged once at warn and answers false', () => { + const warn = vi.fn(); + const messaging = { + registerNotificationTopics: () => { throw new TypeError("the topic 'approval.approved' is already registered"); }, + }; + expect(registerApprovalNotificationTopics(messaging, { warn })).toBe(false); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0][1]).toEqual({ error: "the topic 'approval.approved' is already registered" }); + }); + + it('hands the registry the whole list in one call', () => { + const calls: unknown[] = []; + const messaging = { registerNotificationTopics: (d: unknown) => { calls.push(d); } }; + expect(registerApprovalNotificationTopics(messaging, { warn: vi.fn() })).toBe(true); + expect(calls).toEqual([APPROVAL_NOTIFICATION_TOPICS]); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-notification-topics.ts b/packages/plugins/plugin-approvals/src/approval-notification-topics.ts new file mode 100644 index 00000000000..64fc466bfe6 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-notification-topics.ts @@ -0,0 +1,153 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The notification topics the approval service sends (`approval-service.ts`, + * every `notify()` call), as the messaging service's topic registry describes + * them to an administrator picking a topic for a preference or a template + * (ruling 7409753977 on #39412: each sending feature registers its own + * topics). + * + * Registered by `ApprovalsServicePlugin` at start, beside the approval e-mail + * templates, and feature-detected the same way: a messaging service without + * `registerNotificationTopics` is a composition that cannot describe topics, + * never an error. A refusal (a topic another feature already registered) is + * logged at `warn`, and the registry keeps nothing from the refused call: the + * topic pickers then do not offer these topics at all (one collision drops + * all of them), unless a flow names one or the organization has stored one. + * The notices are sent either way. + * + * The texts are English; the catalog keys and the declared variables are not + * filled yet. + */ + +/** + * The part of `@objectstack/service-messaging`'s `NotificationTopicDescriptor` + * these topics fill, declared here structurally: service-messaging is only a + * dev dependency of this package (as `ApprovalMessagingSurface`). The registry + * itself checks each descriptor and refuses a malformed one. + */ +export interface ApprovalTopicDescriptor { + readonly topic: string; + readonly label: { readonly fallback: string }; + readonly description: { readonly fallback: string }; +} + +function topic(id: string, label: string, description: string): ApprovalTopicDescriptor { + return { topic: id, label: { fallback: label }, description: { fallback: description } }; +} + +/** Every topic the approval service sends, each with its name and when it fires; sorted by id. */ +export const APPROVAL_NOTIFICATION_TOPICS: readonly ApprovalTopicDescriptor[] = [ + topic( + 'approval.abandoned', + 'Approval did not finish', + 'The approval of a record stopped between two of its steps and the record was put back to an open status; the submitter is told.', + ), + topic( + 'approval.approved', + 'Request approved', + 'A request was approved at its last step; the submitter is told.', + ), + topic( + 'approval.comment', + 'Comment on an approval', + 'Someone commented on an approval request, or a request has no one who can decide it yet; the other side of the request is told.', + ), + topic( + 'approval.escalated', + 'Approval escalated', + 'An overdue approval was escalated; the people it was escalated to are told.', + ), + topic( + 'approval.flow_not_continued', + 'Approval flow not seen through', + "An approval was decided at its last step, but its flow could not be seen through to its end after that step; the organization's administrators are told.", + ), + topic( + 'approval.ooo_skipped', + 'Approval routed to a delegate', + 'An approval went to the delegate of an approver who is out of office; the out-of-office approver is told.', + ), + topic( + 'approval.ooo_substituted', + 'Approval covered for an out-of-office approver', + 'An approval went to a delegate because the approver is out of office; the delegate is told.', + ), + topic( + 'approval.reassigned', + 'Approval handed over', + 'An approval was handed to another approver; the new approver is told.', + ), + topic( + 'approval.rejected', + 'Request rejected', + 'A request was rejected; the submitter is told.', + ), + topic( + 'approval.reminder', + 'Approval reminder', + 'A decision on an approval is still waiting; the approvers who have not decided yet are reminded.', + ), + topic( + 'approval.request_info', + 'More information requested', + 'An approver asked for more information on a request; the submitter is told.', + ), + topic( + 'approval.requested', + 'Approval requested', + 'A step of an approval opened and a decision is waiting; each approver of the step is told.', + ), + topic( + 'approval.returned', + 'Sent back for revision', + 'A request was sent back for revision, or rejected for going over its revision limit; the submitter is told.', + ), + topic( + 'approval.sla_breached', + 'Approval overdue', + 'A decision on an approval went past its time limit; the approvers and the submitter are told.', + ), + topic( + 'approval.status_mirror_refused', + 'Approval status not written', + "A rule or a hook of the app refused to write an approval's status onto its record; the organization's administrators are told.", + ), +]; + +/** The member of the messaging service the registration calls, when the service offers it. */ +interface ApprovalTopicRegistrar { + registerNotificationTopics(descriptors: readonly ApprovalTopicDescriptor[]): void; +} + +function offersRegistration(messaging: unknown): messaging is ApprovalTopicRegistrar { + return ( + !!messaging && + typeof messaging === 'object' && + typeof (messaging as Partial).registerNotificationTopics === 'function' + ); +} + +/** The logger slice the refusal is reported on. */ +export interface ApprovalTopicLogger { + warn(message: string, meta?: Record): void; +} + +/** + * Register {@link APPROVAL_NOTIFICATION_TOPICS} on `messaging` when it offers + * the member. Returns whether they were registered. + */ +export function registerApprovalNotificationTopics(messaging: unknown, logger: ApprovalTopicLogger): boolean { + if (!offersRegistration(messaging)) return false; + try { + messaging.registerNotificationTopics(APPROVAL_NOTIFICATION_TOPICS); + return true; + } catch (err) { + logger.warn( + 'ApprovalsServicePlugin: the approval notification topics were NOT described to the messaging service — ' + + 'the notices are still sent, but the topic pickers do not offer these topics', + { error: err instanceof Error ? err.message : String(err) }, + ); + return false; + } +} diff --git a/packages/plugins/plugin-approvals/src/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index e824bae73c6..c875e631563 100644 --- a/packages/plugins/plugin-approvals/src/approvals-plugin.ts +++ b/packages/plugins/plugin-approvals/src/approvals-plugin.ts @@ -52,6 +52,7 @@ import { backfillActionSlots } from './action-slot-backfill.js'; import { backfillApprovalDisplayLabels } from './display-label-backfill.js'; import { backfillProcessPackages, logProcessPackageBackfill, type FlowHolderSource } from './stored-process-package-backfill.js'; import { APPROVAL_EMAIL_TEMPLATES } from './approval-email-templates.js'; +import { registerApprovalNotificationTopics } from './approval-notification-topics.js'; import { consolePageLink, resolvePublicBaseUrl } from './public-base-url.js'; export interface ApprovalsPluginOptions { @@ -520,6 +521,9 @@ export class ApprovalsServicePlugin implements Plugin { }); } } + // [#39641] Every topic the service sends, with its name and when it + // fires, for the topic pickers (`approval-notification-topics.ts`). + registerApprovalNotificationTopics(messaging, ctx.logger); } } catch { /* messaging not installed */ } diff --git a/packages/plugins/plugin-audit/src/audit-plugin.test.ts b/packages/plugins/plugin-audit/src/audit-plugin.test.ts index 079348da0ca..d1af3a16cff 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.test.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.test.ts @@ -2,7 +2,9 @@ import { describe, it, expect, vi } from 'vitest'; import { ObjectQLPlugin } from '@objectstack/objectql'; +import { MessagingService } from '@objectstack/service-messaging'; import { AuditPlugin } from './audit-plugin.js'; +import { COLLAB_NOTIFICATION_TOPICS } from './collab-notification-topics.js'; /** * Regression coverage: a freshly provisioned env READS sys_activity (the home @@ -677,3 +679,52 @@ describe('AuditPlugin — hands its sealer\'s expiry to the lifecycle service (A await expect(start(new AuditPlugin({ cryptoProvider: { label: 'host' } as never }), undefined)).resolves.toBeUndefined(); }); }); + +/** + * [#39641] The `@mention` and comment reply topics are described to the + * messaging service's topic registry at `kernel:ready`, beside the e-mail + * templates: the real `MessagingService`, so the registry's own checks judge + * the descriptors. A refusal is a `warn` and the boot goes on; a messaging + * service without the member is no error. + */ +describe('AuditPlugin — the collaboration notification topics', () => { + async function bootWith(messaging: unknown) { + const { engine } = makeFakeEngine(); + const { ctx, logs, fireReady } = makeCtx(engine); + if (messaging !== undefined) ctx.registerService('messaging', messaging); + const plugin = new AuditPlugin(); + await plugin.init(ctx); + await plugin.start(ctx); + await fireReady(); + return logs; + } + + it('registers collab.mention and collab.reply with a label and a description', async () => { + const messaging = new MessagingService({ logger: { debug() {}, info() {}, warn() {}, error() {} } as any }); + const logs = await bootWith(messaging); + expect(messaging.notificationTopics.ids()).toEqual(['collab.mention', 'collab.reply']); + const rendered = messaging.notificationTopics.render(undefined, undefined); + for (const d of COLLAB_NOTIFICATION_TOPICS) { + expect(rendered.find((t) => t.topic === d.topic)).toEqual({ + topic: d.topic, + label: d.label.fallback, + description: d.description.fallback, + }); + } + expect(logs.warn.filter((m) => m.includes('notification topics'))).toEqual([]); + }); + + it('a refused registration is one warn naming the topics, and the boot goes on', async () => { + const messaging = new MessagingService({ logger: { debug() {}, info() {}, warn() {}, error() {} } as any }); + // Another feature already holds the topic: the registry refuses the whole call. + messaging.registerNotificationTopics([COLLAB_NOTIFICATION_TOPICS[0]!]); + const logs = await bootWith(messaging); + expect(messaging.notificationTopics.ids()).toEqual(['collab.mention']); + expect(logs.warn.filter((m) => m.includes('@mention and comment reply notification topics'))).toHaveLength(1); + }); + + it('a messaging service without the member registers nothing and logs nothing about it', async () => { + const logs = await bootWith({ emit: async () => undefined }); + expect(logs.warn.filter((m) => m.includes('notification topics'))).toEqual([]); + }); +}); diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index 6885fe70ffe..b2e4bad4059 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -45,6 +45,7 @@ import { SysAuditLogDetailPage } from './sys-audit-log.page.js'; // @objectstack/service-storage for the same ownership reason (ADR-0052 §3: a // file↔record link belongs with storage, not the compliance ledger). import { installAuditWriters, type AuditActorSnapshot, type AuditI18nSurface, type MessagingEmitSurface } from './audit-writers.js'; +import { registerCollabNotificationTopics } from './collab-notification-topics.js'; import { MENTION_EMAIL_TEMPLATES, REPLY_EMAIL_TEMPLATES } from './mention-email.js'; import { createAppActivityWriter } from './app-activity-door.js'; import { installReadAuditWriter, type ReadAuditWriterHandle } from './read-audit.js'; @@ -699,6 +700,9 @@ export class AuditPlugin implements Plugin { }); } } + // The two topics' names and when they fire, for the topic pickers + // (`collab-notification-topics.ts`). + registerCollabNotificationTopics(messagingAtReady, ctx.logger); const auditWriters = installAuditWriters(engine as any, this.name, { getMessaging, getI18n, diff --git a/packages/plugins/plugin-audit/src/collab-notification-topics.ts b/packages/plugins/plugin-audit/src/collab-notification-topics.ts new file mode 100644 index 00000000000..5c03de6c908 --- /dev/null +++ b/packages/plugins/plugin-audit/src/collab-notification-topics.ts @@ -0,0 +1,90 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The collaboration notification topics this package sends — the `@mention` + * notice and the comment reply notice (`mention-email.ts`) — as the messaging + * service's topic registry describes them to an administrator picking a topic + * for a preference or a template (ruling 7409753977 on #39412: each sending + * feature registers its own topics). + * + * Registered by `AuditPlugin` on `kernel:ready`, beside the two e-mail + * template sets, and feature-detected the same way: a messaging service + * without `registerNotificationTopics` is a composition that cannot describe + * topics, never an error. A refusal (a topic another feature already + * registered) is logged at `warn`, and the registry keeps nothing from the + * refused call: the topic pickers then do not offer either topic, unless a + * flow names it or the organization has stored it. The notices are sent + * either way. + */ + +import { MENTION_TOPIC, REPLY_TOPIC } from './mention-email.js'; + +/** + * The part of `@objectstack/service-messaging`'s `NotificationTopicDescriptor` + * these topics fill, declared here structurally so this package takes no + * dependency on service-messaging (as `MessagingEmitSurface` in + * `audit-writers.ts`). The registry itself checks each descriptor and refuses + * a malformed one; the catalog keys and the declared variables are not filled + * yet. + */ +export interface CollabTopicDescriptor { + readonly topic: string; + readonly label: { readonly fallback: string }; + readonly description: { readonly fallback: string }; +} + +/** The two topics, each with its name and when it fires. */ +export const COLLAB_NOTIFICATION_TOPICS: readonly CollabTopicDescriptor[] = [ + { + topic: MENTION_TOPIC, + label: { fallback: 'Mentioned in a comment' }, + description: { fallback: 'Someone mentioned a person with @ in a comment on a record; the mentioned person is told.' }, + }, + { + topic: REPLY_TOPIC, + label: { fallback: 'Reply in a comment thread' }, + description: { + fallback: 'Someone replied in a comment thread on a record; the people who started or replied in the thread are told.', + }, + }, +]; + +/** The member of the messaging service the registration calls, when the service offers it. */ +interface CollabTopicRegistrar { + registerNotificationTopics(descriptors: readonly CollabTopicDescriptor[]): void; +} + +function offersRegistration(messaging: unknown): messaging is CollabTopicRegistrar { + return ( + !!messaging && + typeof messaging === 'object' && + typeof (messaging as Partial).registerNotificationTopics === 'function' + ); +} + +/** The logger slice the refusal is reported on. */ +export interface CollabTopicLogger { + warn(message: string, meta?: Record): void; +} + +/** + * Register {@link COLLAB_NOTIFICATION_TOPICS} on `messaging` when it offers + * the member. Returns whether they were registered. + */ +export function registerCollabNotificationTopics( + messaging: unknown, + logger: CollabTopicLogger, +): boolean { + if (!offersRegistration(messaging)) return false; + try { + messaging.registerNotificationTopics(COLLAB_NOTIFICATION_TOPICS); + return true; + } catch (err) { + logger.warn( + 'AuditPlugin: the @mention and comment reply notification topics were NOT described to the messaging service — ' + + 'the notices are still sent, but the topic pickers do not offer these topics', + { error: err instanceof Error ? err.message : String(err) }, + ); + return false; + } +} diff --git a/packages/plugins/plugin-auth/src/auth-plugin.test.ts b/packages/plugins/plugin-auth/src/auth-plugin.test.ts index 6ee559b6af1..65bb08ff10a 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.test.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.test.ts @@ -5,7 +5,11 @@ import { AuthPlugin } from './auth-plugin'; import type { AuthPluginOptions } from './auth-plugin'; import { AuthManager } from './auth-manager'; import { invitationAcceptPath } from './invitation-link-action'; +import { PHONE_SMS_NOTIFICATION_TOPICS } from './phone-sms-notification-topics'; +import { MessagingService } from '@objectstack/service-messaging'; import { ObjectKernel } from '@objectstack/core'; +// Paid at collection: the source under test reaches it by dynamic import (`sso-discovery-egress.ts`). +import '@objectstack/core/egress'; import type { Plugin, PluginContext } from '@objectstack/core'; import { ObjectQLPlugin, assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; @@ -235,6 +239,21 @@ describe('AuthPlugin', () => { expect(mockContext.hook).toHaveBeenCalledWith('kernel:ready', expect.any(Function)); }); + it('[#39641] describes the two auth SMS topics to the messaging service on kernel:ready', async () => { + const messaging = new MessagingService({ logger: mockContext.logger as any }); + mockContext.getService = vi.fn((name: string) => { + if (name === 'messaging') return messaging; + throw new Error(`Service not found: ${name}`); + }) as unknown as PluginContext['getService']; + await authPlugin.start(mockContext); + expect(messaging.notificationTopics.ids()).toEqual([]); + + await hookCapture.trigger('kernel:ready'); + + expect(messaging.notificationTopics.ids()).toEqual(['auth.phone_invite', 'auth.phone_otp']); + expect(messaging.notificationTopics.get('auth.phone_otp')?.label.fallback).toBe(PHONE_SMS_NOTIFICATION_TOPICS[0]!.label.fallback); + }); + it('should register routes with HTTP server on kernel:ready', async () => { const mockRawApp = { all: vi.fn(), diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index dba71d1e336..a5f7da6cd3e 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -196,6 +196,7 @@ import { } from './auth-settings-declared.js'; import { FORWARDED_CLIENT_ADDRESS_HEADERS } from './client-address-forwarding.js'; import { runAtMountDoor } from './request-client-address.js'; +import { registerPhoneSmsNotificationTopics } from './phone-sms-notification-topics.js'; import { runAdminBanUser, runAdminUnbanUser, @@ -1395,6 +1396,15 @@ export class AuthPlugin implements Plugin { await reportSsoProviderAccessSweep(ql, ctx.logger); }); + // The two auth SMS topics, described for the template topic picker + // (`phone-sms-notification-topics.ts`). On `kernel:ready`, where every + // service is registered; never throws into boot. + ctx.hook('kernel:ready', async () => { + let messaging: unknown; + try { messaging = ctx.getService('messaging'); } catch { return; } + registerPhoneSmsNotificationTopics(messaging, ctx.logger); + }); + // [#23367, ruling A] Record when this deployment started enforcing the // API-key lifecycle policy — ONCE, in the `auth` settings, so the anchor // survives restarts and every node reads the same instant (⛔ never the diff --git a/packages/plugins/plugin-auth/src/phone-sms-notification-topics.test.ts b/packages/plugins/plugin-auth/src/phone-sms-notification-topics.test.ts new file mode 100644 index 00000000000..3c20b0a973d --- /dev/null +++ b/packages/plugins/plugin-auth/src/phone-sms-notification-topics.test.ts @@ -0,0 +1,50 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#39641] The two auth SMS topics, described to the messaging service's topic + * registry (`phone-sms-notification-topics.ts`): a real `MessagingService`, so + * the registry's own checks judge the descriptors. A refusal is one `warn`; a + * messaging service without the member, or none at all, is no error. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { MessagingService } from '@objectstack/service-messaging'; +import { PHONE_SMS_TOPICS } from './phone-sms-texts.js'; +import { PHONE_SMS_NOTIFICATION_TOPICS, registerPhoneSmsNotificationTopics } from './phone-sms-notification-topics.js'; + +const silent = { debug() {}, info() {}, warn() {}, error() {} } as any; + +describe('registerPhoneSmsNotificationTopics', () => { + it('registers auth.phone_otp and auth.phone_invite with a label and a description', () => { + const messaging = new MessagingService({ logger: silent }); + const logger = { warn: vi.fn() }; + expect(registerPhoneSmsNotificationTopics(messaging, logger)).toBe(true); + expect(messaging.notificationTopics.ids()).toEqual([PHONE_SMS_TOPICS.invite, PHONE_SMS_TOPICS.otp]); + const rendered = messaging.notificationTopics.render(undefined, undefined); + for (const d of PHONE_SMS_NOTIFICATION_TOPICS) { + expect(rendered.find((t) => t.topic === d.topic)).toEqual({ + topic: d.topic, + label: d.label.fallback, + description: d.description.fallback, + }); + } + expect(logger.warn).not.toHaveBeenCalled(); + }); + + it('a refused registration is one warn, and nothing throws', () => { + const messaging = new MessagingService({ logger: silent }); + messaging.registerNotificationTopics([PHONE_SMS_NOTIFICATION_TOPICS[0]!]); + const logger = { warn: vi.fn() }; + expect(registerPhoneSmsNotificationTopics(messaging, logger)).toBe(false); + expect(messaging.notificationTopics.ids()).toEqual([PHONE_SMS_TOPICS.otp]); + expect(logger.warn).toHaveBeenCalledTimes(1); + expect(logger.warn.mock.calls[0]![1]).toMatchObject({ error: expect.stringContaining('already registered') }); + }); + + it('a messaging service without the member, or none, registers nothing and says nothing', () => { + const logger = { warn: vi.fn() }; + expect(registerPhoneSmsNotificationTopics({ emit: async () => undefined }, logger)).toBe(false); + expect(registerPhoneSmsNotificationTopics(undefined, logger)).toBe(false); + expect(logger.warn).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/plugins/plugin-auth/src/phone-sms-notification-topics.ts b/packages/plugins/plugin-auth/src/phone-sms-notification-topics.ts new file mode 100644 index 00000000000..9b4e93f1bf9 --- /dev/null +++ b/packages/plugins/plugin-auth/src/phone-sms-notification-topics.ts @@ -0,0 +1,69 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The two auth SMS topics (`phone-sms-texts.ts`, {@link PHONE_SMS_TOPICS}) as + * the messaging service's topic registry describes them to an administrator + * picking a topic for a `sys_notification_template` row (ruling 7409753977 + * on #39412: each sending feature registers its own topics). Auth sends these + * texts itself, through the `sms` service; the topic is what an organization's + * own template row is keyed by. + * + * Registered by `AuthPlugin` on `kernel:ready`, where every service is + * registered, and feature-detected: a messaging service without + * `registerNotificationTopics` cannot describe topics, which is no error. A + * refusal (a topic another feature already registered) is logged at `warn`, + * and the registry keeps nothing from the refused call: the template topic + * picker then does not offer either topic, unless the organization has + * stored it. The texts are sent either way. + */ + +import type { NotificationTopicDescriptor } from '@objectstack/service-messaging'; +import { PHONE_SMS_TOPICS } from './phone-sms-texts.js'; + +/** The two topics, each with its name and when it fires. */ +export const PHONE_SMS_NOTIFICATION_TOPICS: readonly NotificationTopicDescriptor[] = [ + { + topic: PHONE_SMS_TOPICS.otp, + label: { fallback: 'Phone verification code' }, + description: { + fallback: 'A person asked to sign in or reset their password with their phone number; the text message carries a one-time code.', + }, + }, + { + topic: PHONE_SMS_TOPICS.invite, + label: { fallback: 'Phone account invitation' }, + description: { + fallback: 'An administrator imported a person with a phone number and chose to invite them; the text message tells them how to sign in.', + }, + }, +]; + +/** The logger slice the refusal is reported on. */ +export interface PhoneSmsTopicLogger { + warn(message: string, meta?: Record): void; +} + +/** + * Register {@link PHONE_SMS_NOTIFICATION_TOPICS} on `messaging` when it offers + * the member. Returns whether they were registered. + */ +export function registerPhoneSmsNotificationTopics(messaging: unknown, logger: PhoneSmsTopicLogger): boolean { + const registrar = messaging as { registerNotificationTopics?: unknown } | null | undefined; + if (!registrar || typeof registrar !== 'object' || typeof registrar.registerNotificationTopics !== 'function') { + return false; + } + try { + (registrar.registerNotificationTopics as (d: readonly NotificationTopicDescriptor[]) => void).call( + registrar, + PHONE_SMS_NOTIFICATION_TOPICS, + ); + return true; + } catch (err) { + logger.warn( + 'Auth: the phone verification code and phone invitation topics were NOT described to the messaging service — ' + + 'the texts are still sent, but the template topic picker does not offer these topics', + { error: err instanceof Error ? err.message : String(err) }, + ); + return false; + } +} diff --git a/packages/plugins/plugin-security/src/access-upgrade-report.wiring.test.ts b/packages/plugins/plugin-security/src/access-upgrade-report.wiring.test.ts index 928e837499b..248ec14345d 100644 --- a/packages/plugins/plugin-security/src/access-upgrade-report.wiring.test.ts +++ b/packages/plugins/plugin-security/src/access-upgrade-report.wiring.test.ts @@ -20,6 +20,10 @@ * none in any other organization. The same finding set carries the same * `dedupKey` on the next boot, which is what the ingress deduplicates on. An * unknown value raises nothing in-app and says so. + * + * [#39641] The two upgrade reports' topics are described to the messaging + * service's topic registry at `kernel:ready`: a real `MessagingService` + * registry behind the `messaging` service, so its own checks judge them. */ import { afterEach, describe, expect, it, vi } from 'vitest'; @@ -30,12 +34,15 @@ import { SysMetadataObject, SysMetadataHistoryObject, SysMetadataCommitObject, SysMetadataAuditObject, } from '@objectstack/metadata-core'; import { resetPlatformAdminEmailMemo } from '@objectstack/core'; +import { MessagingService } from '@objectstack/service-messaging'; import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity'; import { SysMetadataActivation } from '@objectstack/platform-objects/system'; import { SecurityPlugin } from './security-plugin.js'; import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js'; import { ACCESS_UPGRADE_TOPIC } from './access-upgrade-report.js'; +import { UPGRADE_IMPACT_TOPIC } from './upgrade-impact-report.js'; +import { UPGRADE_REPORT_NOTIFICATION_TOPICS } from './security-plugin-start-hooks.js'; const SYS = { isSystem: true } as const; const POSTURE_ENV = 'OS_TENANCY_POSTURE'; @@ -59,7 +66,12 @@ afterEach(async () => { } }); -async function boot(posture: 'single' | 'isolated' | 'group', renamed: boolean, ownerOrganization?: string) { +async function boot( + posture: 'single' | 'isolated' | 'group', + renamed: boolean, + ownerOrganization?: string, + messagingMembers: Record = {}, +) { const walled = posture !== 'single'; if (walled) process.env[POSTURE_ENV] = posture; process.env[OWNER_ENV] = OPERATOR; @@ -103,7 +115,7 @@ async function boot(posture: 'single' | 'isolated' | 'group', renamed: boolean, objectql: engine, metadata, protocol, - messaging: { emit }, + messaging: { emit, ...messagingMembers }, sharingRules: { listDeclaredRules: async () => [] }, ...(walled ? { 'org-scoping': { name: 'com.objectstack.org-scoping' }, tenancy: { posture } } : {}), }; @@ -147,7 +159,7 @@ async function boot(posture: 'single' | 'isolated' | 'group', renamed: boolean, }, { context: { isSystem: true, tenantId: DEFAULT_ORG } } as any); for (const handler of hooks.get('kernel:bootstrapped') ?? []) await handler(); - return { emit, logger }; + return { emit, logger, hooks }; } describe('[ADR-0126 §6 wall 3] the access upgrade report, wired at kernel:bootstrapped', () => { @@ -213,3 +225,35 @@ describe('[ADR-0126 §6 wall 3] the access upgrade report, wired at kernel:boots }); } }); + +describe('the upgrade reports describe their topics to the messaging service at kernel:ready', () => { + const silent = { debug() {}, info() {}, warn() {}, error() {} } as any; + + it('registers security.access_upgrade and system.upgrade_impact with a label and a description', async () => { + const registry = new MessagingService({ logger: silent }); + const { hooks, logger } = await boot('single', false, undefined, { + registerNotificationTopics: (d: never) => registry.registerNotificationTopics(d), + }); + expect(registry.notificationTopics.ids()).toEqual([]); + for (const handler of hooks.get('kernel:ready') ?? []) await handler(); + expect(registry.notificationTopics.ids()).toEqual([ACCESS_UPGRADE_TOPIC, UPGRADE_IMPACT_TOPIC]); + const rendered = registry.notificationTopics.render(undefined, undefined); + for (const d of UPGRADE_REPORT_NOTIFICATION_TOPICS) { + expect(rendered.find((t) => t.topic === d.topic)).toEqual({ + topic: d.topic, label: d.label.fallback, description: d.description.fallback, + }); + } + expect(logger.warn.mock.calls.some(([m]: any[]) => String(m).includes('notification topics were NOT described'))).toBe(false); + }); + + it('a refused registration is one warn, and the boot goes on', async () => { + const registry = new MessagingService({ logger: silent }); + registry.registerNotificationTopics([UPGRADE_REPORT_NOTIFICATION_TOPICS[1]!]); + const { hooks, logger } = await boot('single', false, undefined, { + registerNotificationTopics: (d: never) => registry.registerNotificationTopics(d), + }); + for (const handler of hooks.get('kernel:ready') ?? []) await handler(); + expect(registry.notificationTopics.ids()).toEqual([UPGRADE_IMPACT_TOPIC]); + expect(logger.warn.mock.calls.filter(([m]: any[]) => String(m).includes('notification topics were NOT described'))).toHaveLength(1); + }); +}); diff --git a/packages/plugins/plugin-security/src/security-plugin-start-hooks.ts b/packages/plugins/plugin-security/src/security-plugin-start-hooks.ts index 066913d5b3e..96636fb72ee 100644 --- a/packages/plugins/plugin-security/src/security-plugin-start-hooks.ts +++ b/packages/plugins/plugin-security/src/security-plugin-start-hooks.ts @@ -58,12 +58,13 @@ import { reportCatalogReferences } from './catalog-reference-report.js'; import { backfillStoredPermissionSetPackagesAtBoot } from './stored-permission-set-package-backfill.js'; import { createPositionRenameCarryRuns } from './position-renamed-holder-carry.js'; import { + ACCESS_UPGRADE_TOPIC, reportAccessUpgrade, SHARING_RULES_SERVICE, type AccessUpgradeNotifier, type DeclaredSharingRuleReader, } from './access-upgrade-report.js'; -import { reportUpgradeImpact, SETTINGS_SERVICE, type SettingsManifestReader } from './upgrade-impact-report.js'; +import { reportUpgradeImpact, SETTINGS_SERVICE, UPGRADE_IMPACT_TOPIC, type SettingsManifestReader } from './upgrade-impact-report.js'; import { applyManagedWriteDenies } from './managed-object-write-denies.js'; import { reportPackagedPermissionSetOverlays } from './packaged-permission-set-overlay-detection.js'; import { registerObjectPostureGate } from './object-posture-gate.js'; @@ -99,6 +100,40 @@ export interface StartHooksHost { deploymentOrgScopingEntitlement: SecurityPlugin['deploymentOrgScopingEntitlement']; } +/** + * The topics the two upgrade reports raise, as the messaging service's topic + * registry describes them to an administrator picking a topic (ruling + * 7409753977 on #39412: each sending feature registers its own topics). The + * part of `@objectstack/service-messaging`'s `NotificationTopicDescriptor` + * they fill, declared structurally: this package takes no dependency on + * service-messaging (as `AccessUpgradeNotifier`), and the registry checks + * each descriptor itself. + */ +export const UPGRADE_REPORT_NOTIFICATION_TOPICS: ReadonlyArray<{ + readonly topic: string; + readonly label: { readonly fallback: string }; + readonly description: { readonly fallback: string }; +}> = [ + { + topic: ACCESS_UPGRADE_TOPIC, + label: { fallback: 'Access choices an upgrade affected' }, + description: { + fallback: + 'At startup after an upgrade, a permission set, position or sharing rule the organization switched off, ' + + 'cloned or wrote no longer matches what the installed packages ship; the administrators are told.', + }, + }, + { + topic: UPGRADE_IMPACT_TOPIC, + label: { fallback: 'Customizations an upgrade affected' }, + description: { + fallback: + 'At startup after an upgrade, a flow, action or webhook switch, a stored override, an object extension, a ' + + 'navigation entry or a stored setting no longer matches what the installed packages ship; the administrators are told.', + }, + }, +]; + /** The registrations `SecurityPlugin#start` makes after the authorization middleware, in that order; the comments inside are their contract. */ export function registerStartHooks( this: Pick, @@ -623,4 +658,34 @@ export function registerStartHooks( } else { void runOrgAdminBackfill(); } + + // The two upgrade reports' topics, registered for the topic pickers. On + // `kernel:ready`, where every service is registered, and feature-detected: + // a messaging service without the member cannot describe topics, which is + // no error. A refusal keeps nothing from the call, so the pickers do not + // offer either topic (unless a flow names it or the organization has + // stored it); it never costs the reports. + const registerUpgradeReportTopics = (): void => { + let messaging: { registerNotificationTopics?: (d: typeof UPGRADE_REPORT_NOTIFICATION_TOPICS) => void } | undefined; + try { + messaging = ctx.getService('messaging') ?? undefined; + } catch { + return; + } + if (typeof messaging?.registerNotificationTopics !== 'function') return; + try { + messaging.registerNotificationTopics(UPGRADE_REPORT_NOTIFICATION_TOPICS); + } catch (e) { + ctx.logger.warn( + '[security] the access upgrade and upgrade impact notification topics were NOT described to the messaging ' + + 'service — the reports are still raised, but the topic pickers do not offer these topics', + { error: (e as Error)?.message }, + ); + } + }; + if (typeof (ctx as any).hook === 'function') { + (ctx as any).hook('kernel:ready', registerUpgradeReportTopics); + } else { + registerUpgradeReportTopics(); + } } diff --git a/packages/services/service-messaging/src/in-app-message-routes.ts b/packages/services/service-messaging/src/in-app-message-routes.ts index 6a05b005a74..fe2cbe01a4b 100644 --- a/packages/services/service-messaging/src/in-app-message-routes.ts +++ b/packages/services/service-messaging/src/in-app-message-routes.ts @@ -15,6 +15,7 @@ import type { ExecutionContext } from '@objectstack/spec/kernel'; import { sendError, sendOk, sendServerFault } from '@objectstack/types'; import { FAN_OUT_SYSTEM_CONTEXT } from './fan-out-system-context.js'; import type { EmitInput, EmitResult } from './messaging-service.js'; +import type { NotificationTopicDescriptor } from './notification-topic-registry.js'; import { ORGANIZATION_MEMBERS_AUDIENCE } from './recipient-resolver.js'; /** @@ -134,6 +135,18 @@ export const IN_APP_MESSAGE_CAPABILITY = 'setup.write'; /** The topic every message this door sends is emitted under. */ export const IN_APP_MESSAGE_TOPIC = 'org.announcement'; +/** + * {@link IN_APP_MESSAGE_TOPIC} as the topic registry describes it to an + * administrator picking a topic; registered by `MessagingServicePlugin`. + */ +export const IN_APP_MESSAGE_TOPIC_DESCRIPTOR: NotificationTopicDescriptor = { + topic: IN_APP_MESSAGE_TOPIC, + label: { fallback: 'Message from an administrator' }, + description: { + fallback: 'An administrator sent an in-app message from Setup to chosen people or to everyone in the organization.', + }, +}; + /** The body keys the door reads — the whole closed set. */ export const IN_APP_MESSAGE_BODY_KEYS: readonly string[] = Object.freeze(['recipients', 'everyone', 'title', 'body', 'severity', 'link']); diff --git a/packages/services/service-messaging/src/index.ts b/packages/services/service-messaging/src/index.ts index c2ca7dba3b5..fe7e8d197d7 100644 --- a/packages/services/service-messaging/src/index.ts +++ b/packages/services/service-messaging/src/index.ts @@ -147,6 +147,12 @@ export type { RenderInput, NotificationTemplateStoreOptions, } from './template-renderer.js'; +// The descriptor a sending feature hands `MessagingService.registerNotificationTopics`. +export type { + NotificationTopicDescriptor, + NotificationTopicText, + NotificationTopicVariable, +} from './notification-topic-registry.js'; export type { MessagingChannel, MessagingChannelContext, diff --git a/packages/services/service-messaging/src/messaging-service-plugin.ts b/packages/services/service-messaging/src/messaging-service-plugin.ts index 1a209390d85..fc6d6ccf98a 100644 --- a/packages/services/service-messaging/src/messaging-service-plugin.ts +++ b/packages/services/service-messaging/src/messaging-service-plugin.ts @@ -2,15 +2,16 @@ import { randomUUID } from 'node:crypto'; import type { Plugin, PluginContext, RequestAuthService, TenancyPostureSource } from '@objectstack/core'; -import { resolveLocalizationContext, wakeAfterOpenUnitsCommit } from '@objectstack/core'; +import { CHANGE_OWNER_NOTIFICATION_TOPIC_DESCRIPTOR, resolveLocalizationContext, wakeAfterOpenUnitsCommit } from '@objectstack/core'; import { installEgressGuard, type EgressGuard, type EgressPolicy } from '@objectstack/core/egress'; 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 { IN_APP_MESSAGE_ROUTE, IN_APP_MESSAGE_TOPIC_DESCRIPTOR, registerInAppMessageRoutes } from './in-app-message-routes.js'; import { MY_PREFERENCES_ROUTE, registerMyPreferencesRoutes } from './my-preferences-routes.js'; import { NOTIFICATION_TEMPLATE_PREVIEW_ROUTE, registerNotificationTemplatePreviewRoutes } from './notification-template-preview-routes.js'; import { resolveMessagingCaller, type MessagingCallerSources } from './messaging-request-caller.js'; import type { PreferenceOptionsEngine } from './preference-options.js'; +import type { NotificationTopicI18n } from './notification-topic-registry.js'; import { MessagingService } from './messaging-service.js'; import type { MessagingChannel } from './channel.js'; import { createInboxChannel } from './inbox-channel.js'; @@ -23,6 +24,7 @@ import { createSmsChannel } from './sms-channel.js'; import { createPushChannel } from './push-channel.js'; import { mountSlackChannel } from './slack-channel.js'; import { + SLACK_LINK_REMOVED_TOPIC_DESCRIPTOR, SlackLinkStore, bindSlackLinkRemovalTriggers, unbindSlackLinkRemovalTriggers, @@ -387,6 +389,14 @@ export class MessagingServicePlugin implements Plugin { } ctx.registerService('messaging', service); + // [ruling 7409753977 on #39412] The topics this package sends, and core's + // Change Owner notice (core cannot reach this package), described for the + // preference options door (`notification-topic-registry.ts`). + service.registerNotificationTopics([ + SLACK_LINK_REMOVED_TOPIC_DESCRIPTOR, + IN_APP_MESSAGE_TOPIC_DESCRIPTOR, + CHANGE_OWNER_NOTIFICATION_TOPIC_DESCRIPTOR, + ]); // [#34730 step 2] The Slack link store: the organization's install // (`sys_channel_account`) and each person's link to their own Slack @@ -871,6 +881,8 @@ export class MessagingServicePlugin implements Plugin { const raw = await protocol.getMetaItems({ type: 'flow' }); return Array.isArray(raw) ? raw : ((raw as { items?: unknown[] } | null)?.items ?? []); }, + registeredTopics: (locale: string | undefined) => + service.notificationTopics.render(optional('i18n'), locale), }; registerPreferenceOptionsRoutes(http, { ...callerSources, ...optionSources }); ctx.logger.info(`[messaging] preference options list mounted at GET ${PREFERENCE_OPTIONS_ROUTE}`); diff --git a/packages/services/service-messaging/src/messaging-service.ts b/packages/services/service-messaging/src/messaging-service.ts index e9dc07ed6ba..76494f59cf5 100644 --- a/packages/services/service-messaging/src/messaging-service.ts +++ b/packages/services/service-messaging/src/messaging-service.ts @@ -28,6 +28,7 @@ import { assertActorReferenceResolves } from './actor-reference.js'; import { USER_OBJECT } from './recipient-locale.js'; import { DeviceRegistry } from './device-registry.js'; import { BuiltinNotificationTemplates, type BuiltinNotificationTemplate } from './template-renderer.js'; +import { NotificationTopicRegistry, type NotificationTopicDescriptor } from './notification-topic-registry.js'; import type { RegisterDeviceRequest, RegisterDeviceResponse, @@ -384,6 +385,12 @@ export class MessagingService { * organization's own `sys_notification_template` rows. */ readonly builtinTemplates = new BuiltinNotificationTemplates(); + /** + * The topics the platform's sending features registered — see + * {@link MessagingService.registerNotificationTopics}. The preference + * options door reads it on every request. + */ + readonly notificationTopics = new NotificationTopicRegistry(); constructor(private readonly ctx: MessagingServiceContext) { this.now = ctx.now ?? (() => new Date().toISOString()); @@ -422,6 +429,23 @@ export class MessagingService { this.builtinTemplates.register(templates); } + /** + * Register the notification topics a feature sends: each topic's id, the + * label an administrator picks it by, one sentence on when it fires, and + * the payload members a template for it may use + * (`notification-topic-registry.ts`). Every text is a catalog key with its + * English fallback, rendered in the reader's language by the preference + * options door. Nothing is stored. + * + * A sender calls it at boot, beside {@link registerBuiltinTemplates}, and + * feature-detects it the same way. A malformed descriptor, or a topic + * already registered, is refused with a `TypeError` and nothing from the + * call is kept. + */ + registerNotificationTopics(descriptors: readonly NotificationTopicDescriptor[]): void { + this.notificationTopics.register(descriptors); + } + /* ------------------------------------------------------------------ */ /* Push devices — `INotificationService`'s device members (ADR-0012 */ /* §6), over `sys_user_device`. See `./device-registry.ts`. */ 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 index ee026fd9a58..68af8c3b871 100644 --- a/packages/services/service-messaging/src/my-preferences-routes.integration.test.ts +++ b/packages/services/service-messaging/src/my-preferences-routes.integration.test.ts @@ -112,6 +112,14 @@ function door(ql: ObjectQL, opts: { failFlows?: boolean } = {}) { }; // inbox mounted; email known, its transport absent. const service = new MessagingService({ logger: silent, getData: () => ql as never, mandatoryTopics: MANDATORY }); + // The topics the platform's sending features would register at boot. + service.registerNotificationTopics( + ['approval.comment', 'approval.reminder', 'approval.requested', 'security.access_upgrade'].map((topic) => ({ + topic, + label: { fallback: topic }, + description: { fallback: `When ${topic} fires.` }, + })), + ); service.registerChannel(channel('inbox')); service.registerChannelProvider('email', () => undefined); @@ -136,6 +144,7 @@ function door(ql: ObjectQL, opts: { failFlows?: boolean } = {}) { if (opts.failFlows) throw new Error('the flow list could not be read'); return []; }, + registeredTopics: (locale) => service.notificationTopics.render(undefined, locale), effectivePreferences: (userId, organizationId, topics, channels) => service.effectivePreferencesFor(userId, organizationId, topics, channels), }); diff --git a/packages/services/service-messaging/src/my-preferences-routes.ts b/packages/services/service-messaging/src/my-preferences-routes.ts index 9377b047646..9d9563e82e3 100644 --- a/packages/services/service-messaging/src/my-preferences-routes.ts +++ b/packages/services/service-messaging/src/my-preferences-routes.ts @@ -49,9 +49,9 @@ import type { EffectivePreferences, EffectiveTopic } from './preference-resolver * `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 + * preference options list names (`readPreferenceOptions`: the topics the + * platform's features registered, 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`. diff --git a/packages/services/service-messaging/src/notification-topic-registry.test.ts b/packages/services/service-messaging/src/notification-topic-registry.test.ts new file mode 100644 index 00000000000..5d6e1d00082 --- /dev/null +++ b/packages/services/service-messaging/src/notification-topic-registry.test.ts @@ -0,0 +1,142 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The notification topic registry (`notification-topic-registry.ts`) and the + * preference options read over it (`readPreferenceOptions`): + * + * - a sending feature registers a topic through the messaging service's + * member, and a malformed descriptor or a second registration of one topic + * is refused whole; + * - the texts render in the reader's language through the catalog, else their + * English fallback; + * - the door serves a registered topic with source `platform` and its label, + * description and variables, and a topic no feature registered with none. + */ + +import { describe, it, expect } from 'vitest'; +import { MessagingService } from './messaging-service.js'; +import { NotificationTopicRegistry, type NotificationTopicDescriptor, type NotificationTopicI18n } from './notification-topic-registry.js'; +import { readPreferenceOptions, type PreferenceOptionsSources } from './preference-options.js'; + +const silent: any = { debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return silent; } }; + +const APPROVED: NotificationTopicDescriptor = { + topic: 'approval.approved', + label: { key: 'messages.approvalApprovedTopicLabel', fallback: 'Approval approved' }, + description: { key: 'messages.approvalApprovedTopicDescription', fallback: 'Sent to the submitter when their request is approved.' }, + variables: [{ name: 'record_name', description: { key: 'messages.approvalTopicRecordName', fallback: 'The name of the record under approval.' } }], +}; + +const REJECTED: NotificationTopicDescriptor = { + topic: 'approval.rejected', + label: { fallback: 'Approval rejected' }, + description: { fallback: 'Sent to the submitter when their request is rejected.' }, +}; + +/** A catalog that knows the approved topic's texts in zh-CN alone. */ +const ZH: Record = { + 'messages.approvalApprovedTopicLabel': '审批已通过', + 'messages.approvalApprovedTopicDescription': '申请获批时通知提交人。', + 'messages.approvalTopicRecordName': '审批记录的名称。', +}; +const i18n: NotificationTopicI18n = { + t: (key, locale) => (locale === 'zh-CN' ? (ZH[key] ?? key) : key), + getLocales: () => ['en', 'zh-CN'], +}; + +describe('MessagingService.registerNotificationTopics', () => { + it('registers each topic once and keeps a copy the sender can no longer change', () => { + const service = new MessagingService({ logger: silent }); + const mine = { ...REJECTED, label: { fallback: 'Approval rejected' } }; + service.registerNotificationTopics([APPROVED, mine]); + (mine.label as { fallback: string }).fallback = 'changed'; + expect(service.notificationTopics.ids()).toEqual(['approval.approved', 'approval.rejected']); + expect(service.notificationTopics.get('approval.rejected')?.label.fallback).toBe('Approval rejected'); + }); + + it.each<[string, unknown, RegExp]>([ + ['not an array', APPROVED, /takes an array/], + ['no topic', [{ ...REJECTED, topic: '' }], /is not a topic id/], + ['the wildcard', [{ ...REJECTED, topic: '*' }], /preference wildcard/], + ['an unknown member', [{ ...REJECTED, channel: 'email' }], /carrying 'channel'/], + ['no label', [{ ...REJECTED, label: undefined }], /label of topic 'approval.rejected' is not/], + ['an empty description', [{ ...REJECTED, description: { fallback: ' ' } }], /description of topic 'approval.rejected' has no fallback/], + ['a one-segment key', [{ ...REJECTED, label: { key: 'label', fallback: 'x' } }], /is not a catalog key/], + ['a variable that is no hole path', [{ ...REJECTED, variables: [{ name: 'a b', description: { fallback: 'x' } }] }], /not a template hole path/], + ['a variable twice', [{ ...REJECTED, variables: [{ name: 'a', description: { fallback: 'x' } }, { name: 'a', description: { fallback: 'y' } }] }], /'a' of topic 'approval.rejected' twice/], + ])('refuses %s with a TypeError and keeps nothing from the call', (_name, input, message) => { + const registry = new NotificationTopicRegistry(); + const call = () => registry.register(Array.isArray(input) ? [APPROVED, ...input] : (input as never)); + expect(call).toThrow(TypeError); + expect(call).toThrow(message); + expect(registry.ids()).toEqual([]); + }); + + it('refuses a topic already registered, in the same call or an earlier one', () => { + const registry = new NotificationTopicRegistry(); + expect(() => registry.register([REJECTED, REJECTED])).toThrow(/'approval.rejected' is already registered/); + expect(registry.ids()).toEqual([]); + registry.register([REJECTED]); + expect(() => registry.register([APPROVED, REJECTED])).toThrow(/'approval.rejected' is already registered/); + expect(registry.ids()).toEqual(['approval.rejected']); + }); +}); + +describe('NotificationTopicRegistry.render', () => { + const registry = new NotificationTopicRegistry(); + registry.register([APPROVED, REJECTED]); + + it('renders each keyed text in the negotiated reader language', () => { + const [approved] = registry.render(i18n, 'zh'); + expect(approved).toEqual({ + topic: 'approval.approved', + label: '审批已通过', + description: '申请获批时通知提交人。', + variables: [{ name: 'record_name', description: '审批记录的名称。' }], + }); + }); + + it('serves the English fallback where the catalog has no entry, there is no i18n service, or no locale', () => { + for (const [svc, locale] of [[i18n, 'ja-JP'], [undefined, 'zh-CN'], [i18n, undefined]] as const) { + const [approved, rejected] = registry.render(svc, locale); + expect(approved.label).toBe('Approval approved'); + expect(rejected).toEqual({ + topic: 'approval.rejected', + label: 'Approval rejected', + description: 'Sent to the submitter when their request is rejected.', + }); + // Not declared is not "declares none": the rendering keeps the member absent. + expect(rejected).not.toHaveProperty('variables'); + } + }); +}); + +describe('readPreferenceOptions over the registry', () => { + it('serves a registered topic as platform with its texts, and lists no topic no feature registered', async () => { + const service = new MessagingService({ logger: silent }); + service.registerNotificationTopics([APPROVED]); + let askedLocale: string | undefined; + const sources: PreferenceOptionsSources = { + knownChannels: () => [], + getData: () => undefined, + readFlows: async () => [{ name: 'f', nodes: [{ id: 'n', type: 'notify', config: { topic: 'approval.approved' } }] }], + registeredTopics: (locale) => { + askedLocale = locale; + return service.notificationTopics.render(i18n, locale); + }, + }; + const { topics } = await readPreferenceOptions(sources, 'org_a', 'zh-CN'); + expect(askedLocale).toBe('zh-CN'); + const approved = topics.find((t) => t.value === 'approval.approved'); + expect(approved).toEqual({ + value: 'approval.approved', + wildcard: false, + sources: ['platform', 'flow'], + label: '审批已通过', + description: '申请获批时通知提交人。', + variables: [{ name: 'record_name', description: '审批记录的名称。' }], + }); + // The registry is the only platform source: there is no held list of ids beside it. + expect(topics.map((t) => t.value)).toEqual(['*', 'approval.approved']); + }); +}); diff --git a/packages/services/service-messaging/src/notification-topic-registry.ts b/packages/services/service-messaging/src/notification-topic-registry.ts new file mode 100644 index 00000000000..d1ac5e580d5 --- /dev/null +++ b/packages/services/service-messaging/src/notification-topic-registry.ts @@ -0,0 +1,254 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The notification topics the platform's own features send, as each sending + * feature registers them: the topic id, what an administrator reads as its + * name, one sentence on when it fires, and the payload members a template for + * it may use (ruling 7409753977 on #39412, option D: "each sending feature + * registers its own topics with the messaging service in code"). + * + * ## Who fills it + * + * The feature that sends the topic, at boot, beside its built-in templates + * (`MessagingService.registerBuiltinTemplates` is the sibling seam and the + * pattern: the sender feature-detects the member on the `messaging` service it + * already resolves, and a messaging service without it is a composition that + * cannot describe topics, never an error). Nothing is stored: the registry is + * code, rebuilt on every boot, one per messaging service. + * + * ## Who reads it + * + * The preference options door (`preference-options.ts`): every registered + * topic is offered with source `platform`, with its label, description and + * variables rendered in the caller's language. The topics an environment's + * flows send stay metadata (each `notify` step names its own), and are not + * registered here. + * + * ## The text + * + * Each text is a catalog key with its English fallback, the shape a + * notification's keyed params already take (`notification-text.ts`): the key + * is an `II18nService` key the sender contributes through its own translation + * bundle (ADR-0029 D8), and the fallback is what a reader is served when the + * catalog has no entry in their language, or there is no `i18n` service. ⛔ + * There is no second catalog here. + * + * ## Refusals + * + * A malformed descriptor, or a topic already registered, is refused with a + * `TypeError` and nothing from the call is kept: it is a sender bug, and a + * silent last-one-wins would let two features disagree about what one topic + * is called without anyone seeing it. + */ + +import { resolveBundleLocale } from '@objectstack/spec/system'; + +/** One text of a descriptor: a catalog key, with the English text served when the key has no entry. */ +export interface NotificationTopicText { + /** An `II18nService` key, a face and an id (`messages.approvalApprovedTopicLabel`). Absent: the fallback alone. */ + readonly key?: string; + /** The English text, served when the key cannot be rendered in the reader's language. */ + readonly fallback: string; +} + +/** One payload member a template for the topic may use, as `{{ name }}` or `{{ payload.name }}`. */ +export interface NotificationTopicVariable { + /** The payload member's path, as a template hole names it (`record_name`, `request.id`). */ + readonly name: string; + /** What the value is. */ + readonly description: NotificationTopicText; +} + +/** A topic as its sending feature registers it. */ +export interface NotificationTopicDescriptor { + /** The topic id the feature emits under (`approval.approved`). */ + readonly topic: string; + /** The name an administrator picks the topic by. */ + readonly label: NotificationTopicText; + /** When the topic fires, in one sentence. */ + readonly description: NotificationTopicText; + /** + * The payload members the feature sends under this topic. Empty when it + * sends none; absent when it has not declared them, which a reader tells + * apart (the generic variables apply), so the rendering keeps it absent. + */ + readonly variables?: readonly NotificationTopicVariable[]; +} + +/** A registered topic, rendered for one reader. */ +export interface RenderedNotificationTopic { + readonly topic: string; + readonly label: string; + readonly description: string; + /** Absent exactly when the descriptor declares no `variables` member. */ + readonly variables?: ReadonlyArray<{ readonly name: string; readonly description: string }>; +} + +/** The slice of `II18nService` a rendering asks: `t()`, and `getLocales()` to negotiate when offered. */ +export interface NotificationTopicI18n { + t(key: string, locale: string, params?: Record): string; + getLocales?(): string[]; +} + +/** A catalog key: a face and an id, dot-separated — the shape `notification-text.ts` refuses everything else by. */ +const CATALOG_KEY_SHAPE = /^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/; + +/** A template hole's path: identifier segments, dot-separated. */ +const VARIABLE_NAME_SHAPE = /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/; + +const DESCRIPTOR_MEMBERS: ReadonlySet = new Set(['topic', 'label', 'description', 'variables']); +const TEXT_MEMBERS: ReadonlySet = new Set(['key', 'fallback']); +const VARIABLE_MEMBERS: ReadonlySet = new Set(['name', 'description']); + +function isPlainObject(value: unknown): value is Record { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function unknownMember(value: Record, allowed: ReadonlySet): string | undefined { + return Object.keys(value).find((k) => !allowed.has(k)); +} + +function textProblem(at: string, text: unknown): string | undefined { + if (!isPlainObject(text)) return `${at} is not a { key, fallback } text`; + const extra = unknownMember(text, TEXT_MEMBERS); + if (extra !== undefined) return `${at} carries '${extra}', which is not one of key, fallback`; + if (typeof text.fallback !== 'string' || !text.fallback.trim()) return `${at} has no fallback text`; + if (text.key !== undefined && (typeof text.key !== 'string' || !CATALOG_KEY_SHAPE.test(text.key))) { + return `${at} has key ${JSON.stringify(text.key)}, which is not a catalog key (a face and an id, e.g. 'messages.myTopicLabel')`; + } + return undefined; +} + +function descriptorProblem(d: unknown): string | undefined { + if (!isPlainObject(d)) return 'got a descriptor that is not an object'; + if (typeof d.topic !== 'string' || !d.topic.trim() || /\s/.test(d.topic)) { + return `got a descriptor whose topic ${JSON.stringify(d.topic)} is not a topic id (a non-empty string with no whitespace)`; + } + if (d.topic === '*') return "got the topic '*', which is the preference wildcard, not a topic"; + const extra = unknownMember(d, DESCRIPTOR_MEMBERS); + if (extra !== undefined) { + return `got a descriptor for topic '${d.topic}' carrying '${extra}', which is not one of ${[...DESCRIPTOR_MEMBERS].join(', ')}`; + } + const label = textProblem(`the label of topic '${d.topic}'`, d.label); + if (label) return `got ${label}`; + const description = textProblem(`the description of topic '${d.topic}'`, d.description); + if (description) return `got ${description}`; + if (d.variables === undefined) return undefined; + if (!Array.isArray(d.variables)) return `got variables for topic '${d.topic}' that are not an array`; + const names = new Set(); + for (const v of d.variables) { + if (!isPlainObject(v)) return `got a variable of topic '${d.topic}' that is not an object`; + const extraMember = unknownMember(v, VARIABLE_MEMBERS); + if (extraMember !== undefined) { + return `got a variable of topic '${d.topic}' carrying '${extraMember}', which is not one of name, description`; + } + if (typeof v.name !== 'string' || !VARIABLE_NAME_SHAPE.test(v.name)) { + return `got a variable of topic '${d.topic}' named ${JSON.stringify(v.name)}, which is not a template hole path (e.g. 'record_name')`; + } + if (names.has(v.name)) return `got the variable '${v.name}' of topic '${d.topic}' twice`; + names.add(v.name); + const problem = textProblem(`the description of variable '${v.name}' of topic '${d.topic}'`, v.description); + if (problem) return `got ${problem}`; + } + return undefined; +} + +/** + * The registered topics of one messaging service. Producers fill it through + * `MessagingService.registerNotificationTopics`; the preference options door + * reads it on every request, so a topic registered at any point of the boot is + * offered from then on. + */ +export class NotificationTopicRegistry { + private readonly topics = new Map(); + + register(descriptors: readonly NotificationTopicDescriptor[]): void { + if (!Array.isArray(descriptors)) { + throw new TypeError('messaging: registerNotificationTopics() takes an array of topic descriptors'); + } + const staged = new Map(); + for (const d of descriptors) { + const problem = descriptorProblem(d); + if (problem) throw new TypeError(`messaging: registerNotificationTopics() ${problem}`); + if (this.topics.has(d.topic) || staged.has(d.topic)) { + throw new TypeError(`messaging: registerNotificationTopics() the topic '${d.topic}' is already registered`); + } + staged.set(d.topic, freeze(d)); + } + for (const [topic, d] of staged) this.topics.set(topic, d); + } + + /** The registered topic ids, sorted. */ + ids(): string[] { + return [...this.topics.keys()].sort(); + } + + /** The descriptor registered for `topic`, else `undefined`. */ + get(topic: string): NotificationTopicDescriptor | undefined { + return this.topics.get(topic); + } + + /** + * Every registered topic with its texts in `locale` (negotiated against + * the locales `i18n` holds), each text its fallback where the catalog has + * no entry, `i18n` is absent, or no locale is asked. + */ + render(i18n: NotificationTopicI18n | undefined, locale: string | undefined): RenderedNotificationTopic[] { + const answerLocale = i18n && locale ? negotiatedLocale(i18n, locale) : undefined; + const text = (t: NotificationTopicText): string => + (i18n && answerLocale && t.key ? lookup(i18n, t.key, answerLocale) : undefined) ?? t.fallback; + return this.ids().map((id) => { + const d = this.topics.get(id)!; + return { + topic: id, + label: text(d.label), + description: text(d.description), + ...(d.variables !== undefined + ? { variables: d.variables.map((v) => ({ name: v.name, description: text(v.description) })) } + : {}), + }; + }); + } +} + +/** A deep copy the sender can no longer mutate under the registry. */ +function freeze(d: NotificationTopicDescriptor): NotificationTopicDescriptor { + const text = (t: NotificationTopicText): NotificationTopicText => + Object.freeze(t.key !== undefined ? { key: t.key, fallback: t.fallback } : { fallback: t.fallback }); + return Object.freeze({ + topic: d.topic, + label: text(d.label), + description: text(d.description), + ...(d.variables !== undefined + ? { variables: Object.freeze(d.variables.map((v) => Object.freeze({ name: v.name, description: text(v.description) }))) } + : {}), + }); +} + +/** `t()`'s answer, or `undefined` for a miss (`t()` echoes the key), an empty answer or a throw. */ +function lookup(i18n: NotificationTopicI18n, key: string, locale: string): string | undefined { + try { + const text = i18n.t(key, locale); + return typeof text === 'string' && text.trim().length > 0 && text !== key ? text : undefined; + } catch { + // A misbehaving i18n service costs the language, never the list. + return undefined; + } +} + +/** The locale `i18n` can answer in for `requested`: `resolveBundleLocale`, the one negotiation rule. */ +function negotiatedLocale(i18n: NotificationTopicI18n, requested: string): string { + if (typeof i18n.getLocales !== 'function') return requested; + let available: unknown; + try { + available = i18n.getLocales(); + } catch { + return requested; + } + if (!Array.isArray(available) || available.length === 0) return requested; + const offered: Record = {}; + for (const code of available) { + if (typeof code === 'string' && code.length > 0) offered[code] = true; + } + return resolveBundleLocale(offered, requested) ?? requested; +} diff --git a/packages/services/service-messaging/src/preference-options-routes.integration.test.ts b/packages/services/service-messaging/src/preference-options-routes.integration.test.ts index 66b17d154a3..1fc760be729 100644 --- a/packages/services/service-messaging/src/preference-options-routes.integration.test.ts +++ b/packages/services/service-messaging/src/preference-options-routes.integration.test.ts @@ -8,7 +8,8 @@ * `SqlDriver` (better-sqlite3) holding two organizations, on the `isolated` * posture. * - * - a member is served `*` first, then the platform's fixed topics, the + * - a member is served `*` first, then the topics the platform's features + * registered with the messaging service (with their label and description), the * topics this environment's flow notify steps send under, and their own * organization's stored topics, each with its sources; and `*` first, then * every known channel, a known one with no transport marked not configured; @@ -27,7 +28,6 @@ import { ApiErrorSchema, envelopeViolations } from '@objectstack/spec/api'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { currentCredentialUseClient, hashApiKey } from '@objectstack/core'; import { PREFERENCE_OPTIONS_ROUTE, registerPreferenceOptionsRoutes } from './preference-options-routes.js'; -import { PLATFORM_NOTIFICATION_TOPICS } from './preference-options.js'; import { MessagingService } from './messaging-service.js'; import type { MessagingChannel } from './channel.js'; @@ -55,6 +55,29 @@ const FLOWS = [ { name: 'update', nodes: [{ id: 'u', type: 'update_record', config: { topic: 'not.a.notify.topic' } }] }, ]; +/** The one topic a sending feature of this composition registered. */ +const REQUESTED = { + topic: 'approval.requested', + label: { fallback: 'Approval requested' }, + description: { fallback: 'A step of an approval opened; each approver is told.' }, +}; + +/** A registered topic whose sender declared its variables. */ +const REMINDER = { + topic: 'approval.reminder', + label: { fallback: 'Approval reminder' }, + description: { fallback: 'An approval step is still waiting; each approver is reminded.' }, + variables: [{ name: 'record_name', description: { fallback: 'The name of the record under approval.' } }], +}; + +/** A registered topic whose sender declared that it sends no variables. */ +const ANNOUNCEMENT = { + topic: 'org.announcement', + label: { fallback: 'Announcement' }, + description: { fallback: 'An administrator sent a message to the organization.' }, + variables: [], +}; + let engine: ObjectQL | undefined; afterEach(async () => { @@ -112,6 +135,7 @@ function door(setup: DoorSetup) { }; // inbox and sms mounted; email known, its transport absent. const service = new MessagingService({ logger: silent }); + service.registerNotificationTopics([REQUESTED, REMINDER, ANNOUNCEMENT]); service.registerChannel(channel('inbox')); service.registerChannelProvider('email', () => undefined); service.registerChannelProvider('sms', () => channel('sms')); @@ -139,6 +163,7 @@ function door(setup: DoorSetup) { knownChannels: () => service.getKnownChannels(), getData: () => setup.ql as never, readFlows: flows, + registeredTopics: (locale) => service.notificationTopics.render(undefined, locale), }); async function call(opts: { bearer?: string; query?: Record } = {}) { @@ -205,8 +230,22 @@ describe('the preference options door — the list', () => { expect(valuesOf(rest)).toEqual([...valuesOf(rest)].sort()); expect(new Set(valuesOf(topics)).size).toBe(topics.length); const byValue = new Map(rest.map((t: any) => [t.value, t])); - for (const platform of PLATFORM_NOTIFICATION_TOPICS) expect(byValue.has(platform), platform).toBe(true); - expect(byValue.get('approval.requested')).toEqual({ value: 'approval.requested', wildcard: false, sources: ['platform', 'stored'] }); + expect(byValue.get('approval.requested')).toEqual({ + value: 'approval.requested', + wildcard: false, + sources: ['platform', 'stored'], + label: REQUESTED.label.fallback, + description: REQUESTED.description.fallback, + }); + // `variables` is served only where the sender declared it: absent means "not declared yet" + // (the generic variables apply), `[]` means the sender declared that it sends none. + expect(byValue.get('approval.requested')).not.toHaveProperty('variables'); + expect((byValue.get('approval.reminder') as any).variables).toEqual([ + { name: 'record_name', description: 'The name of the record under approval.' }, + ]); + expect((byValue.get('org.announcement') as any).variables).toEqual([]); + // The registry is the only platform source: a topic no feature registered is not listed. + expect(byValue.has('approval.approved')).toBe(false); expect(byValue.get('deal.won')).toEqual({ value: 'deal.won', wildcard: false, sources: ['flow', 'stored'] }); // A notify step that names no topic sends under `notify`. expect(byValue.get('notify')).toEqual({ value: 'notify', wildcard: false, sources: ['flow'] }); diff --git a/packages/services/service-messaging/src/preference-options-routes.ts b/packages/services/service-messaging/src/preference-options-routes.ts index 842ba4ba786..8e03119f8e0 100644 --- a/packages/services/service-messaging/src/preference-options-routes.ts +++ b/packages/services/service-messaging/src/preference-options-routes.ts @@ -48,7 +48,12 @@ import { readPreferenceOptions, type PreferenceOptionsSources } from './preferen * ## What the door answers * * - **Success:** `200` with `{ topics, channels }` (`PreferenceOptions`), - * the caller's organization's stored topics among the topics. + * the caller's organization's stored topics among the topics, and each + * topic a sending feature registered carrying its `label`, `description` + * and, where the sender declared them, `variables` in the caller's + * language (`ExecutionContext.locale`: the request's `Accept-Language`, + * else the `localization` settings). No `variables` member means "not + * declared"; `[]` means the sender declared none. * - **A source that cannot be read** (the event table, the flow list) is a * fault: `500` / `INTERNAL_ERROR` with this door's sentence and the error * in the fault log. A partial list is never served as if it were whole. @@ -113,7 +118,7 @@ async function handlePreferenceOptions( } try { - sendOk(res, await readPreferenceOptions(deps, context.tenantId)); + sendOk(res, await readPreferenceOptions(deps, context.tenantId, context.locale)); } catch (err) { sendServerFault(res, 500, 'INTERNAL_ERROR', 'The notification topics and channels could not be read.', err, { method: 'GET', diff --git a/packages/services/service-messaging/src/preference-options.ts b/packages/services/service-messaging/src/preference-options.ts index dd1084bc933..1e79f7e55ba 100644 --- a/packages/services/service-messaging/src/preference-options.ts +++ b/packages/services/service-messaging/src/preference-options.ts @@ -16,10 +16,12 @@ * * ## Topics — three sources, `*` first * - * - **platform**: {@link PLATFORM_NOTIFICATION_TOPICS}, the fixed topics the - * platform's own features send or template under. No package registers its - * topics (ADR-0030's `defineTopic()` catalog was never built), so the list is - * measured from the send sites and held here. + * - **platform**: the topics the platform's own features send or template + * under, as each sending feature registers them with the messaging service + * (`notification-topic-registry.ts`, ruling 7409753977 on #39412), each + * served with its label, description and variables in the caller's + * language. The registry is the only platform source: a feature that sends + * a fixed topic registers it at its own seam, and there is no list here. * - **flow**: the topic each `notify` step of this environment's flows names. * A step that names none sends under `notify` (the step's own default), so * `notify` is listed for it. Flows are the environment's metadata, not an @@ -42,38 +44,7 @@ * the plugin registers it. */ -/** - * The platform's fixed notification topics, measured from their send and - * template sites: `plugin-approvals` (`approval.*`), `plugin-audit` - * (`collab.mention`, `collab.reply`), `plugin-security` (`security.access_upgrade`, - * `system.upgrade_impact`), `plugin-auth` (the two phone SMS template - * topics), this package's Slack link store (`messaging.slack_link_removed`) - * and core's Change Owner (`record.owner_changed`, `change-record-owner.ts`). - * Kept sorted; a feature that starts sending a new fixed topic adds - * it here. - */ -export const PLATFORM_NOTIFICATION_TOPICS: readonly string[] = [ - 'approval.comment', - 'approval.escalated', - 'approval.flow_not_continued', - 'approval.ooo_skipped', - 'approval.ooo_substituted', - 'approval.reassigned', - 'approval.reminder', - 'approval.request_info', - 'approval.requested', - 'approval.returned', - 'approval.sla_breached', - 'approval.status_mirror_refused', - 'auth.phone_invite', - 'auth.phone_otp', - 'collab.mention', - 'collab.reply', - 'messaging.slack_link_removed', - 'record.owner_changed', - 'security.access_upgrade', - 'system.upgrade_impact', -]; +import type { RenderedNotificationTopic } from './notification-topic-registry.js'; /** The topic a `notify` step sends under when it names none (`notify-node.ts`). */ export const NOTIFY_STEP_DEFAULT_TOPIC = 'notify'; @@ -91,6 +62,23 @@ export interface PreferenceTopicOption { wildcard: boolean; /** Every source that names this topic; empty on the wildcard. */ sources: PreferenceTopicSource[]; + /** The name its sending feature registered, in the caller's language; absent on a topic no feature registered. */ + label?: string; + /** When the topic fires, as its sending feature registered it; absent with `label`. */ + description?: string; + /** + * The payload members a template for the topic may use, as registered. + * Absent with `label`, and absent on a registered topic whose sender has + * not declared its variables: there the generic ones apply. `[]` means the + * sender declared that it sends none. + */ + variables?: PreferenceTopicVariable[]; +} + +/** One payload member a template for a registered topic may use (`{{ name }}` / `{{ payload.name }}`). */ +export interface PreferenceTopicVariable { + name: string; + description: string; } export interface PreferenceChannelOption { @@ -125,6 +113,11 @@ export interface PreferenceOptionsSources { * rejects, and the door answers that failure. */ readFlows(): Promise; + /** + * The topics the platform's sending features registered + * (`MessagingService.notificationTopics`), rendered in `locale`. + */ + registeredTopics?(locale: string | undefined): readonly RenderedNotificationTopic[]; } /** The event object whose stored topics are listed. */ @@ -139,10 +132,11 @@ export const NOTIFICATION_EVENT_OBJECT_NAME = 'sys_notification'; */ export const PREFERENCE_OPTIONS_SYSTEM_CONTEXT = { isSystem: true } as const; -/** Read the options for a caller acting in `organizationId`. */ +/** Read the options for a caller acting in `organizationId`, the registered texts in `locale`. */ export async function readPreferenceOptions( sources: PreferenceOptionsSources, organizationId: string | undefined, + locale?: string, ): Promise { const bySource = new Map>(); const add = (topic: string, source: PreferenceTopicSource): void => { @@ -152,18 +146,35 @@ export async function readPreferenceOptions( set.add(source); }; - for (const topic of PLATFORM_NOTIFICATION_TOPICS) add(topic, 'platform'); + const registered = new Map(); + for (const t of sources.registeredTopics?.(locale) ?? []) { + if (t.topic === PREFERENCE_WILDCARD) continue; + registered.set(t.topic, t); + add(t.topic, 'platform'); + } for (const topic of notifyStepTopics(await sources.readFlows())) add(topic, 'flow'); for (const topic of await storedTopics(sources.getData(), organizationId)) add(topic, 'stored'); const order: PreferenceTopicSource[] = ['platform', 'flow', 'stored']; const topics: PreferenceTopicOption[] = [ { value: PREFERENCE_WILDCARD, wildcard: true, sources: [] }, - ...[...bySource.keys()].sort().map((value) => ({ - value, - wildcard: false, - sources: order.filter((s) => bySource.get(value)!.has(s)), - })), + ...[...bySource.keys()].sort().map((value): PreferenceTopicOption => { + const r = registered.get(value); + return { + value, + wildcard: false, + sources: order.filter((s) => bySource.get(value)!.has(s)), + ...(r + ? { + label: r.label, + description: r.description, + ...(r.variables !== undefined + ? { variables: r.variables.map((v) => ({ name: v.name, description: v.description })) } + : {}), + } + : {}), + }; + }), ]; const channels: PreferenceChannelOption[] = [ diff --git a/packages/services/service-messaging/src/slack-channel-composition.test.ts b/packages/services/service-messaging/src/slack-channel-composition.test.ts index c6172fc727e..642e2ed35ca 100644 --- a/packages/services/service-messaging/src/slack-channel-composition.test.ts +++ b/packages/services/service-messaging/src/slack-channel-composition.test.ts @@ -19,6 +19,11 @@ * `/api/v1/meta/app` door serves (`SchemaRegistry.getApp`): listed under * Integrations with connector-slack composed, absent without it. * + * [#39641] The topics this package sends (the Slack link removal notice and + * the in-app message door's) and core's Change Owner notice are registered by + * the plugin at init, and the preference options door it mounts serves each + * with its label and description. + * * [#36301] The mounted channel's DM link goes under the Console's mount the * composition's auth service composes (`getConsoleUrl`), and carries none on a * composition whose auth service has no composer. @@ -31,13 +36,15 @@ import { assertEngineUpdateDispatch, type EngineFindOneQueryInput, } from '@objectstack/metadata-core'; +import { CHANGE_OWNER_NOTIFICATION_TOPIC_DESCRIPTOR } from '@objectstack/core'; import { SchemaRegistry } from '@objectstack/objectql'; import { SETUP_APP } from '@objectstack/platform-objects/apps'; import { ManifestSchema } from '@objectstack/spec/kernel'; import { PLATFORM_CAPABILITIES } from '@objectstack/spec/security'; import { MessagingServicePlugin } from './messaging-service-plugin.js'; import { SLACK_ADMIN_CAPABILITY } from './slack-link-routes.js'; -import { SlackLinkStore } from './slack-links.js'; +import { SLACK_LINK_REMOVED_TOPIC_DESCRIPTOR, SlackLinkStore } from './slack-links.js'; +import { IN_APP_MESSAGE_TOPIC_DESCRIPTOR } from './in-app-message-routes.js'; import { SLACK_SETUP_COMPONENT_REF, SLACK_SETUP_UI_BUNDLE } from './slack-setup-ui.js'; import type { MessagingService } from './messaging-service.js'; import { MY_PREFERENCES_ROUTE } from './my-preferences-routes.js'; @@ -113,6 +120,7 @@ async function compose(opts: { slack: boolean; getConsoleUrl?: (path: string) => messaging: services.get('messaging') as MessagingService, manifests, optionChannels: async () => (await get(PREFERENCE_OPTIONS_ROUTE)).channels.map((c: any) => c.value), + optionTopics: async () => (await get(PREFERENCE_OPTIONS_ROUTE)).topics as Array>, myChannels: async () => (await get(MY_PREFERENCES_ROUTE)).channels.map((c: any) => c.channel), }; } @@ -209,3 +217,26 @@ describe('Setup lists the Slack page only where connector-slack is composed', () expect(c.manifests.map((m) => m.id)).toContain('com.objectstack.service.messaging'); }); }); + +describe('the plugin describes the topics it sends, and the door it mounts serves them', () => { + it('serves the Slack link removal, in-app message and Change Owner topics with label and description', async () => { + const c = await compose({ slack: false }); + expect(c.messaging.notificationTopics.ids()).toEqual( + ['messaging.slack_link_removed', 'org.announcement', 'record.owner_changed'], + ); + const byValue = new Map((await c.optionTopics()).map((t) => [t.value, t])); + expect(byValue.get('org.announcement')).toEqual({ + value: 'org.announcement', + wildcard: false, + sources: ['platform'], + label: IN_APP_MESSAGE_TOPIC_DESCRIPTOR.label.fallback, + description: IN_APP_MESSAGE_TOPIC_DESCRIPTOR.description.fallback, + }); + for (const d of [SLACK_LINK_REMOVED_TOPIC_DESCRIPTOR, CHANGE_OWNER_NOTIFICATION_TOPIC_DESCRIPTOR]) { + expect(byValue.get(d.topic)).toMatchObject({ sources: ['platform'], label: d.label.fallback, description: d.description.fallback }); + } + // CONTROL: a topic no feature of this composition registered is not offered at all; + // the registry is the door's only platform source. + expect(byValue.has('collab.mention')).toBe(false); + }); +}); diff --git a/packages/services/service-messaging/src/slack-links.ts b/packages/services/service-messaging/src/slack-links.ts index 6f5c4e4222d..c5c8a565b0d 100644 --- a/packages/services/service-messaging/src/slack-links.ts +++ b/packages/services/service-messaging/src/slack-links.ts @@ -51,6 +51,7 @@ import { createHash, randomUUID } from 'node:crypto'; import type { IDataEngine } from '@objectstack/spec/contracts'; import { isEmailVerifiedUserRow } from '@objectstack/types'; import type { EmitInput } from './messaging-service.js'; +import type { NotificationTopicDescriptor } from './notification-topic-registry.js'; import { enMessages, type MessagingMessageId } from './translations/messages.js'; export const CHANNEL_ACCOUNT_OBJECT = 'sys_channel_account'; @@ -58,6 +59,15 @@ export const CHANNEL_USER_LINK_OBJECT = 'sys_channel_user_link'; export const SLACK_CHANNEL_ID = 'slack'; /** The topic of the notice a person gets when an administrator removes their link (rider 2). */ export const SLACK_LINK_REMOVED_TOPIC = 'messaging.slack_link_removed'; +/** + * {@link SLACK_LINK_REMOVED_TOPIC} as the topic registry describes it to an + * administrator picking a topic; registered by `MessagingServicePlugin`. + */ +export const SLACK_LINK_REMOVED_TOPIC_DESCRIPTOR: NotificationTopicDescriptor = { + topic: SLACK_LINK_REMOVED_TOPIC, + label: { fallback: 'Slack link removed' }, + description: { fallback: "An administrator removed the link between a person's account and their Slack user." }, +}; const TOKEN_FIELD = 'bot_token'; const USER_OBJECT = 'sys_user'; const MEMBER_OBJECT = 'sys_member';