Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .changeset/39641-notification-topic-registry.md
Original file line number Diff line number Diff line change
@@ -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.
15 changes: 15 additions & 0 deletions packages/core/src/security/change-record-owner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/security/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,7 @@ export {
CHANGE_OWNER_DISABLED,
CHANGE_OWNER_NOTIFICATION_TEXT,
CHANGE_OWNER_NOTIFICATION_TOPIC,
CHANGE_OWNER_NOTIFICATION_TOPIC_DESCRIPTOR,
changeOwnerOffReason,
changeOwnerOffRefusal,
changeRecordOwner,
Expand Down
Original file line number Diff line number Diff line change
@@ -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<void>) | undefined;

afterEach(async () => {
try { await stop?.(); } catch { /* noop */ }
stop = undefined;
});

async function compose(): Promise<{ topics: () => Promise<Array<Record<string, unknown>>> }> {
const engine = new ObjectQL();
engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), true);
await engine.init();
const registered = new Set<string>();
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<string, (req: unknown, res: unknown) => Promise<void>>();
const mount = (verb: string) => (path: string, handler: (req: unknown, res: unknown) => Promise<void>) => {
handlers.set(`${verb} ${path}`, handler);
};
const logger: any = { info() {}, debug() {}, warn() {}, error() {}, child: () => logger };
const services: Record<string, unknown> = {
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> | 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> | 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<Record<string, unknown>>;
},
};
}

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<string>();
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]);
});
});
Loading
Loading